1 use crate::fx::{FxHashMap, FxHasher};
2 use crate::sync::{Lock, LockGuard};
3 use std::borrow::Borrow;
4 use std::collections::hash_map::RawEntryMut;
5 use std::hash::{Hash, Hasher};
8 #[derive(Clone, Default)]
9 #[cfg_attr(parallel_compiler, repr(align(64)))]
10 struct CacheAligned<T>(T);
12 #[cfg(parallel_compiler)]
13 // 32 shards is sufficient to reduce contention on an 8-core Ryzen 7 1700,
14 // but this should be tested on higher core count CPUs. How the `Sharded` type gets used
15 // may also affect the ideal number of shards.
16 const SHARD_BITS: usize = 5;
18 #[cfg(not(parallel_compiler))]
19 const SHARD_BITS: usize = 0;
21 pub const SHARDS: usize = 1 << SHARD_BITS;
23 /// An array of cache-line aligned inner locked structures with convenience methods.
25 pub struct Sharded<T> {
26 shards: [CacheAligned<Lock<T>>; SHARDS],
29 impl<T: Default> Default for Sharded<T> {
31 fn default() -> Self {
38 pub fn new(mut value: impl FnMut() -> T) -> Self {
39 Sharded { shards: [(); SHARDS].map(|()| CacheAligned(Lock::new(value()))) }
42 /// The shard is selected by hashing `val` with `FxHasher`.
44 pub fn get_shard_by_value<K: Hash + ?Sized>(&self, val: &K) -> &Lock<T> {
45 if SHARDS == 1 { &self.shards[0].0 } else { self.get_shard_by_hash(make_hash(val)) }
49 pub fn get_shard_by_hash(&self, hash: u64) -> &Lock<T> {
50 &self.shards[get_shard_index_by_hash(hash)].0
54 pub fn get_shard_by_index(&self, i: usize) -> &Lock<T> {
58 pub fn lock_shards(&self) -> Vec<LockGuard<'_, T>> {
59 (0..SHARDS).map(|i| self.shards[i].0.lock()).collect()
62 pub fn try_lock_shards(&self) -> Option<Vec<LockGuard<'_, T>>> {
63 (0..SHARDS).map(|i| self.shards[i].0.try_lock()).collect()
67 pub type ShardedHashMap<K, V> = Sharded<FxHashMap<K, V>>;
69 impl<K: Eq, V> ShardedHashMap<K, V> {
70 pub fn len(&self) -> usize {
71 self.lock_shards().iter().map(|shard| shard.len()).sum()
75 impl<K: Eq + Hash + Copy> ShardedHashMap<K, ()> {
77 pub fn intern_ref<Q: ?Sized>(&self, value: &Q, make: impl FnOnce() -> K) -> K
82 let hash = make_hash(value);
83 let mut shard = self.get_shard_by_hash(hash).lock();
84 let entry = shard.raw_entry_mut().from_key_hashed_nocheck(hash, value);
87 RawEntryMut::Occupied(e) => *e.key(),
88 RawEntryMut::Vacant(e) => {
90 e.insert_hashed_nocheck(hash, v, ());
97 pub fn intern<Q>(&self, value: Q, make: impl FnOnce(Q) -> K) -> K
102 let hash = make_hash(&value);
103 let mut shard = self.get_shard_by_hash(hash).lock();
104 let entry = shard.raw_entry_mut().from_key_hashed_nocheck(hash, &value);
107 RawEntryMut::Occupied(e) => *e.key(),
108 RawEntryMut::Vacant(e) => {
110 e.insert_hashed_nocheck(hash, v, ());
117 pub trait IntoPointer {
118 /// Returns a pointer which outlives `self`.
119 fn into_pointer(&self) -> *const ();
122 impl<K: Eq + Hash + Copy + IntoPointer> ShardedHashMap<K, ()> {
123 pub fn contains_pointer_to<T: Hash + IntoPointer>(&self, value: &T) -> bool {
124 let hash = make_hash(&value);
125 let shard = self.get_shard_by_hash(hash).lock();
126 let value = value.into_pointer();
127 shard.raw_entry().from_hash(hash, |entry| entry.into_pointer() == value).is_some()
132 fn make_hash<K: Hash + ?Sized>(val: &K) -> u64 {
133 let mut state = FxHasher::default();
134 val.hash(&mut state);
138 /// Get a shard with a pre-computed hash value. If `get_shard_by_value` is
139 /// ever used in combination with `get_shard_by_hash` on a single `Sharded`
140 /// instance, then `hash` must be computed with `FxHasher`. Otherwise,
141 /// `hash` can be computed with any hasher, so long as that hasher is used
142 /// consistently for each `Sharded` instance.
144 pub fn get_shard_index_by_hash(hash: u64) -> usize {
145 let hash_len = mem::size_of::<usize>();
146 // Ignore the top 7 bits as hashbrown uses these and get the next SHARD_BITS highest bits.
147 // hashbrown also uses the lowest bits, so we can't use those
148 let bits = (hash >> (hash_len * 8 - 7 - SHARD_BITS)) as usize;