switch to using type aliases for HashMap/HashSet to allow easily switching hashers

This commit is contained in:
Jacob Lifshay 2025-04-09 20:03:14 -07:00
parent e0c9939147
commit b08a747e20
Signed by: programmerjake
SSH key fingerprint: SHA256:HnFTLGpSm4Q4Fj502oCFisjZSoakwEuTsJJMSke63RQ
14 changed files with 57 additions and 52 deletions

View file

@ -14,9 +14,9 @@ use crate::{
impl_match_variant_as_self, CanonicalType, MatchVariantWithoutScope, OpaqueSimValue, impl_match_variant_as_self, CanonicalType, MatchVariantWithoutScope, OpaqueSimValue,
StaticType, Type, TypeProperties, TypeWithDeref, StaticType, Type, TypeProperties, TypeWithDeref,
}, },
util::HashMap,
}; };
use bitvec::{slice::BitSlice, vec::BitVec}; use bitvec::{slice::BitSlice, vec::BitVec};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{fmt, marker::PhantomData}; use std::{fmt, marker::PhantomData};
@ -160,7 +160,7 @@ impl Default for BundleTypePropertiesBuilder {
impl Bundle { impl Bundle {
#[track_caller] #[track_caller]
pub fn new(fields: Interned<[BundleField]>) -> Self { pub fn new(fields: Interned<[BundleField]>) -> Self {
let mut name_indexes = HashMap::with_capacity(fields.len()); let mut name_indexes = HashMap::with_capacity_and_hasher(fields.len(), Default::default());
let mut field_offsets = Vec::with_capacity(fields.len()); let mut field_offsets = Vec::with_capacity(fields.len());
let mut type_props_builder = BundleTypePropertiesBuilder::new(); let mut type_props_builder = BundleTypePropertiesBuilder::new();
for (index, &BundleField { name, flipped, ty }) in fields.iter().enumerate() { for (index, &BundleField { name, flipped, ty }) in fields.iter().enumerate() {

View file

@ -19,9 +19,9 @@ use crate::{
CanonicalType, MatchVariantAndInactiveScope, OpaqueSimValue, StaticType, Type, CanonicalType, MatchVariantAndInactiveScope, OpaqueSimValue, StaticType, Type,
TypeProperties, TypeProperties,
}, },
util::HashMap,
}; };
use bitvec::{order::Lsb0, slice::BitSlice, view::BitView}; use bitvec::{order::Lsb0, slice::BitSlice, view::BitView};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{convert::Infallible, fmt, iter::FusedIterator, sync::Arc}; use std::{convert::Infallible, fmt, iter::FusedIterator, sync::Arc};
@ -193,7 +193,8 @@ impl Default for EnumTypePropertiesBuilder {
impl Enum { impl Enum {
#[track_caller] #[track_caller]
pub fn new(variants: Interned<[EnumVariant]>) -> Self { pub fn new(variants: Interned<[EnumVariant]>) -> Self {
let mut name_indexes = HashMap::with_capacity(variants.len()); let mut name_indexes =
HashMap::with_capacity_and_hasher(variants.len(), Default::default());
let mut type_props_builder = EnumTypePropertiesBuilder::new(); let mut type_props_builder = EnumTypePropertiesBuilder::new();
for (index, EnumVariant { name, ty }) in variants.iter().enumerate() { for (index, EnumVariant { name, ty }) in variants.iter().enumerate() {
if let Some(old_index) = name_indexes.insert(*name, index) { if let Some(old_index) = name_indexes.insert(*name, index) {

View file

@ -36,12 +36,11 @@ use crate::{
ty::{CanonicalType, Type}, ty::{CanonicalType, Type},
util::{ util::{
const_str_array_is_strictly_ascending, BitSliceWriteWithBase, DebugAsRawString, const_str_array_is_strictly_ascending, BitSliceWriteWithBase, DebugAsRawString,
GenericConstBool, GenericConstBool, HashMap, HashSet,
}, },
}; };
use bitvec::slice::BitSlice; use bitvec::slice::BitSlice;
use clap::value_parser; use clap::value_parser;
use hashbrown::{HashMap, HashSet};
use num_traits::Signed; use num_traits::Signed;
use serde::Serialize; use serde::Serialize;
use std::{ use std::{
@ -2622,7 +2621,7 @@ fn export_impl(
indent_depth: &indent_depth, indent_depth: &indent_depth,
indent: " ", indent: " ",
}, },
seen_modules: HashSet::new(), seen_modules: HashSet::default(),
unwritten_modules: VecDeque::new(), unwritten_modules: VecDeque::new(),
global_ns, global_ns,
module: ModuleState::default(), module: ModuleState::default(),

View file

@ -1,9 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-or-later // SPDX-License-Identifier: LGPL-3.0-or-later
// See Notices.txt for copyright information // See Notices.txt for copyright information
#![allow(clippy::type_complexity)] #![allow(clippy::type_complexity)]
use crate::intern::type_map::TypeIdMap; use crate::{intern::type_map::TypeIdMap, util::DefaultBuildHasher};
use bitvec::{ptr::BitPtr, slice::BitSlice, vec::BitVec}; use bitvec::{ptr::BitPtr, slice::BitSlice, vec::BitVec};
use hashbrown::{HashTable, hash_map::DefaultHashBuilder as DefaultBuildHasher}; use hashbrown::HashTable;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
any::{Any, TypeId}, any::{Any, TypeId},

View file

@ -24,10 +24,10 @@ use crate::{
sim::{ExternModuleSimGenerator, ExternModuleSimulation}, sim::{ExternModuleSimGenerator, ExternModuleSimulation},
source_location::SourceLocation, source_location::SourceLocation,
ty::{CanonicalType, Type}, ty::{CanonicalType, Type},
util::ScopedRef, util::{HashMap, HashSet, ScopedRef},
wire::{IncompleteWire, Wire}, wire::{IncompleteWire, Wire},
}; };
use hashbrown::{hash_map::Entry, HashMap, HashSet}; use hashbrown::hash_map::Entry;
use num_bigint::BigInt; use num_bigint::BigInt;
use std::{ use std::{
cell::RefCell, cell::RefCell,
@ -1498,7 +1498,7 @@ impl TargetState {
.collect(), .collect(),
}, },
CanonicalType::PhantomConst(_) => TargetStateInner::Decomposed { CanonicalType::PhantomConst(_) => TargetStateInner::Decomposed {
subtargets: HashMap::new(), subtargets: HashMap::default(),
}, },
CanonicalType::Array(ty) => TargetStateInner::Decomposed { CanonicalType::Array(ty) => TargetStateInner::Decomposed {
subtargets: (0..ty.len()) subtargets: (0..ty.len())
@ -1864,7 +1864,7 @@ impl<T: BundleType> Module<T> {
AssertValidityState { AssertValidityState {
module: self.canonical(), module: self.canonical(),
blocks: vec![], blocks: vec![],
target_states: HashMap::with_capacity(64), target_states: HashMap::with_capacity_and_hasher(64, Default::default()),
} }
.assert_validity(); .assert_validity();
} }
@ -2125,8 +2125,8 @@ impl ModuleBuilder {
incomplete_declarations: vec![], incomplete_declarations: vec![],
stmts: vec![], stmts: vec![],
}], }],
annotations_map: HashMap::new(), annotations_map: HashMap::default(),
memory_map: HashMap::new(), memory_map: HashMap::default(),
}, },
}), }),
}; };
@ -2136,7 +2136,7 @@ impl ModuleBuilder {
impl_: RefCell::new(ModuleBuilderImpl { impl_: RefCell::new(ModuleBuilderImpl {
body, body,
io: vec![], io: vec![],
io_indexes: HashMap::new(), io_indexes: HashMap::default(),
module_annotations: vec![], module_annotations: vec![],
}), }),
}; };

View file

@ -24,8 +24,9 @@ use crate::{
}, },
prelude::*, prelude::*,
reset::{ResetType, ResetTypeDispatch}, reset::{ResetType, ResetTypeDispatch},
util::{HashMap, HashSet},
}; };
use hashbrown::{hash_map::Entry, HashMap, HashSet}; use hashbrown::hash_map::Entry;
use num_bigint::BigInt; use num_bigint::BigInt;
use petgraph::unionfind::UnionFind; use petgraph::unionfind::UnionFind;
use std::{fmt, marker::PhantomData}; use std::{fmt, marker::PhantomData};
@ -2251,9 +2252,9 @@ pub fn deduce_resets(
fallback_to_sync_reset: bool, fallback_to_sync_reset: bool,
) -> Result<Interned<Module<Bundle>>, DeduceResetsError> { ) -> Result<Interned<Module<Bundle>>, DeduceResetsError> {
let mut state = State { let mut state = State {
modules_added_to_graph: HashSet::new(), modules_added_to_graph: HashSet::default(),
substituted_modules: HashMap::new(), substituted_modules: HashMap::default(),
expr_resets: HashMap::new(), expr_resets: HashMap::default(),
reset_graph: ResetGraph::default(), reset_graph: ResetGraph::default(),
fallback_to_sync_reset, fallback_to_sync_reset,
}; };

View file

@ -18,10 +18,10 @@ use crate::{
}, },
source_location::SourceLocation, source_location::SourceLocation,
ty::{CanonicalType, Type}, ty::{CanonicalType, Type},
util::HashMap,
wire::Wire, wire::Wire,
}; };
use core::fmt; use core::fmt;
use hashbrown::HashMap;
#[derive(Debug)] #[derive(Debug)]
pub enum SimplifyEnumsError { pub enum SimplifyEnumsError {
@ -965,8 +965,8 @@ pub fn simplify_enums(
kind: SimplifyEnumsKind, kind: SimplifyEnumsKind,
) -> Result<Interned<Module<Bundle>>, SimplifyEnumsError> { ) -> Result<Interned<Module<Bundle>>, SimplifyEnumsError> {
module.fold(&mut State { module.fold(&mut State {
enum_types: HashMap::new(), enum_types: HashMap::default(),
replacement_mem_ports: HashMap::new(), replacement_mem_ports: HashMap::default(),
kind, kind,
module_state_stack: vec![], module_state_stack: vec![],
}) })

View file

@ -14,11 +14,10 @@ use crate::{
}, },
source_location::SourceLocation, source_location::SourceLocation,
ty::{CanonicalType, Type}, ty::{CanonicalType, Type},
util::MakeMutSlice, util::{HashMap, MakeMutSlice},
wire::Wire, wire::Wire,
}; };
use bitvec::{slice::BitSlice, vec::BitVec}; use bitvec::{slice::BitSlice, vec::BitVec};
use hashbrown::HashMap;
use std::{ use std::{
convert::Infallible, convert::Infallible,
fmt::Write, fmt::Write,
@ -897,7 +896,7 @@ impl Folder for State {
module, module,
ModuleState { ModuleState {
output_module: None, output_module: None,
memories: HashMap::new(), memories: HashMap::default(),
}, },
); );
let mut this = PushedState::push_module(self, module); let mut this = PushedState::push_module(self, module);

View file

@ -41,10 +41,9 @@ use crate::{
value::SimValue, value::SimValue,
}, },
ty::StaticType, ty::StaticType,
util::{BitSliceWriteWithBase, DebugAsDisplay}, util::{BitSliceWriteWithBase, DebugAsDisplay, HashMap, HashSet},
}; };
use bitvec::{bits, order::Lsb0, slice::BitSlice, vec::BitVec, view::BitView}; use bitvec::{bits, order::Lsb0, slice::BitSlice, vec::BitVec, view::BitView};
use hashbrown::{HashMap, HashSet};
use num_bigint::BigInt; use num_bigint::BigInt;
use num_traits::{Signed, Zero}; use num_traits::{Signed, Zero};
use petgraph::{ use petgraph::{
@ -580,8 +579,9 @@ impl Assignments {
big_slots, big_slots,
}) = self.slot_readers(); }) = self.slot_readers();
AssignmentsElements { AssignmentsElements {
node_indexes: HashMap::with_capacity( node_indexes: HashMap::with_capacity_and_hasher(
self.assignments().len() + small_slots.len() + big_slots.len(), self.assignments().len() + small_slots.len() + big_slots.len(),
Default::default(),
), ),
nodes: self.node_references(), nodes: self.node_references(),
edges: self.edge_references(), edges: self.edge_references(),
@ -1676,18 +1676,18 @@ impl Compiler {
insns: Insns::new(), insns: Insns::new(),
original_base_module, original_base_module,
base_module, base_module,
modules: HashMap::new(), modules: HashMap::default(),
extern_modules: Vec::new(), extern_modules: Vec::new(),
compiled_values: HashMap::new(), compiled_values: HashMap::default(),
compiled_exprs: HashMap::new(), compiled_exprs: HashMap::default(),
compiled_exprs_to_values: HashMap::new(), compiled_exprs_to_values: HashMap::default(),
decl_conditions: HashMap::new(), decl_conditions: HashMap::default(),
compiled_values_to_dyn_array_indexes: HashMap::new(), compiled_values_to_dyn_array_indexes: HashMap::default(),
compiled_value_bool_dest_is_small_map: HashMap::new(), compiled_value_bool_dest_is_small_map: HashMap::default(),
assignments: Assignments::default(), assignments: Assignments::default(),
clock_triggers: Vec::new(), clock_triggers: Vec::new(),
compiled_value_to_clock_trigger_map: HashMap::new(), compiled_value_to_clock_trigger_map: HashMap::default(),
enum_discriminants: HashMap::new(), enum_discriminants: HashMap::default(),
registers: Vec::new(), registers: Vec::new(),
traces: SimTraces(Vec::new()), traces: SimTraces(Vec::new()),
memories: Vec::new(), memories: Vec::new(),
@ -5976,8 +5976,8 @@ impl SimulationModuleState {
fn new(base_targets: impl IntoIterator<Item = (Target, CompiledValue<CanonicalType>)>) -> Self { fn new(base_targets: impl IntoIterator<Item = (Target, CompiledValue<CanonicalType>)>) -> Self {
let mut retval = Self { let mut retval = Self {
base_targets: Vec::new(), base_targets: Vec::new(),
uninitialized_ios: HashMap::new(), uninitialized_ios: HashMap::default(),
io_targets: HashMap::new(), io_targets: HashMap::default(),
did_initial_settle: false, did_initial_settle: false,
}; };
for (base_target, value) in base_targets { for (base_target, value) in base_targets {
@ -6207,7 +6207,7 @@ impl Default for EarliestWaitTargets {
Self { Self {
settle: false, settle: false,
instant: None, instant: None,
changes: HashMap::new(), changes: HashMap::default(),
} }
} }
} }
@ -6217,14 +6217,14 @@ impl EarliestWaitTargets {
Self { Self {
settle: true, settle: true,
instant: None, instant: None,
changes: HashMap::new(), changes: HashMap::default(),
} }
} }
fn instant(instant: SimInstant) -> Self { fn instant(instant: SimInstant) -> Self {
Self { Self {
settle: false, settle: false,
instant: Some(instant), instant: Some(instant),
changes: HashMap::new(), changes: HashMap::default(),
} }
} }
fn len(&self) -> usize { fn len(&self) -> usize {

View file

@ -7,10 +7,9 @@ use crate::{
intern::{Intern, Interned, Memoize}, intern::{Intern, Interned, Memoize},
source_location::SourceLocation, source_location::SourceLocation,
ty::CanonicalType, ty::CanonicalType,
util::get_many_mut, util::{get_many_mut, HashMap, HashSet},
}; };
use bitvec::{boxed::BitBox, slice::BitSlice}; use bitvec::{boxed::BitBox, slice::BitSlice};
use hashbrown::{HashMap, HashSet};
use num_bigint::BigInt; use num_bigint::BigInt;
use num_traits::{One, Signed, ToPrimitive, Zero}; use num_traits::{One, Signed, ToPrimitive, Zero};
use std::{ use std::{

View file

@ -14,9 +14,10 @@ use crate::{
TraceModuleIO, TraceReg, TraceSInt, TraceScalar, TraceScalarId, TraceScope, TraceSyncReset, TraceModuleIO, TraceReg, TraceSInt, TraceScalar, TraceScalarId, TraceScope, TraceSyncReset,
TraceUInt, TraceWire, TraceWriter, TraceWriterDecls, TraceUInt, TraceWire, TraceWriter, TraceWriterDecls,
}, },
util::HashMap,
}; };
use bitvec::{order::Lsb0, slice::BitSlice}; use bitvec::{order::Lsb0, slice::BitSlice};
use hashbrown::{hash_map::Entry, HashMap}; use hashbrown::hash_map::Entry;
use std::{ use std::{
fmt::{self, Write as _}, fmt::{self, Write as _},
io, mem, io, mem,

View file

@ -2,9 +2,8 @@
// See Notices.txt for copyright information // See Notices.txt for copyright information
use crate::{ use crate::{
intern::{Intern, Interned}, intern::{Intern, Interned},
util::DebugAsDisplay, util::{DebugAsDisplay, HashMap},
}; };
use hashbrown::HashMap;
use std::{cell::RefCell, fmt, num::NonZeroUsize, panic, path::Path}; use std::{cell::RefCell, fmt, num::NonZeroUsize, panic, path::Path};
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
@ -97,7 +96,7 @@ impl NormalizeFilesForTestsState {
fn new() -> Self { fn new() -> Self {
Self { Self {
test_position: panic::Location::caller(), test_position: panic::Location::caller(),
file_pattern_matches: HashMap::new(), file_pattern_matches: HashMap::default(),
} }
} }
} }
@ -143,7 +142,7 @@ impl From<&'_ panic::Location<'_>> for SourceLocation {
map.entry_ref(file) map.entry_ref(file)
.or_insert_with(|| NormalizedFileForTestState { .or_insert_with(|| NormalizedFileForTestState {
file_name_id: NonZeroUsize::new(len + 1).unwrap(), file_name_id: NonZeroUsize::new(len + 1).unwrap(),
positions_map: HashMap::new(), positions_map: HashMap::default(),
}); });
file_str = m.generate_file_name(file_state.file_name_id); file_str = m.generate_file_name(file_state.file_name_id);
file = &file_str; file = &file_str;

View file

@ -3,9 +3,9 @@
use crate::{ use crate::{
cli::{FormalArgs, FormalMode, FormalOutput, RunPhase}, cli::{FormalArgs, FormalMode, FormalOutput, RunPhase},
firrtl::ExportOptions, firrtl::ExportOptions,
util::HashMap,
}; };
use clap::Parser; use clap::Parser;
use hashbrown::HashMap;
use serde::Deserialize; use serde::Deserialize;
use std::{ use std::{
fmt::Write, fmt::Write,
@ -87,7 +87,7 @@ fn get_assert_formal_target_path(test_name: &dyn std::fmt::Display) -> PathBuf {
let index = *DIRS let index = *DIRS
.lock() .lock()
.unwrap() .unwrap()
.get_or_insert_with(HashMap::new) .get_or_insert_with(HashMap::default)
.entry_ref(&dir) .entry_ref(&dir)
.and_modify(|v| *v += 1) .and_modify(|v| *v += 1)
.or_insert(0); .or_insert(0);

View file

@ -9,6 +9,12 @@ mod misc;
mod scoped_ref; mod scoped_ref;
pub(crate) mod streaming_read_utf8; pub(crate) mod streaming_read_utf8;
// allow easily switching the hasher crate-wide for testing
pub(crate) type DefaultBuildHasher = hashbrown::hash_map::DefaultHashBuilder;
pub(crate) type HashMap<K, V> = hashbrown::HashMap<K, V, DefaultBuildHasher>;
pub(crate) type HashSet<T> = hashbrown::HashSet<T, DefaultBuildHasher>;
#[doc(inline)] #[doc(inline)]
pub use const_bool::{ConstBool, ConstBoolDispatch, ConstBoolDispatchTag, GenericConstBool}; pub use const_bool::{ConstBool, ConstBoolDispatch, ConstBoolDispatchTag, GenericConstBool};
#[doc(inline)] #[doc(inline)]