1 use crate::FxHasher; 2 3 /// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. 4 #[cfg(feature = "std")] 5 pub type FxHashMapSeed<K, V> = std::collections::HashMap<K, V, FxSeededState>; 6 7 /// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`]. 8 #[cfg(feature = "std")] 9 pub type FxHashSetSeed<V> = std::collections::HashSet<V, FxSeededState>; 10 11 /// [`FxSeededState`] is an alternative state for `HashMap` types, allowing to use [`FxHasher`] with a set seed. 12 /// 13 /// ``` 14 /// # use std::collections::HashMap; 15 /// use rustc_hash::FxSeededState; 16 /// 17 /// let mut map = HashMap::with_hasher(FxSeededState::with_seed(12)); 18 /// map.insert(15, 610); 19 /// assert_eq!(map[&15], 610); 20 /// ``` 21 #[derive(Clone)] 22 pub struct FxSeededState { 23 seed: usize, 24 } 25 26 impl FxSeededState { 27 /// Constructs a new `FxSeededState` that is initialized with a `seed`. with_seed(seed: usize) -> FxSeededState28 pub const fn with_seed(seed: usize) -> FxSeededState { 29 Self { seed } 30 } 31 } 32 33 impl core::hash::BuildHasher for FxSeededState { 34 type Hasher = FxHasher; 35 build_hasher(&self) -> Self::Hasher36 fn build_hasher(&self) -> Self::Hasher { 37 FxHasher::with_seed(self.seed) 38 } 39 } 40 41 #[cfg(test)] 42 mod tests { 43 use core::hash::BuildHasher; 44 45 use crate::FxSeededState; 46 47 #[test] cloned_seeded_states_are_equal()48 fn cloned_seeded_states_are_equal() { 49 let seed = 2; 50 let a = FxSeededState::with_seed(seed); 51 let b = a.clone(); 52 53 assert_eq!(a.seed, b.seed); 54 assert_eq!(a.seed, seed); 55 56 assert_eq!(a.build_hasher().hash, b.build_hasher().hash); 57 } 58 59 #[test] same_seed_produces_same_hasher()60 fn same_seed_produces_same_hasher() { 61 let seed = 1; 62 let a = FxSeededState::with_seed(seed); 63 let b = FxSeededState::with_seed(seed); 64 65 // The hashers should be the same, as they have the same seed. 66 assert_eq!(a.build_hasher().hash, b.build_hasher().hash); 67 } 68 69 #[test] different_states_are_different()70 fn different_states_are_different() { 71 let a = FxSeededState::with_seed(1); 72 let b = FxSeededState::with_seed(2); 73 74 assert_ne!(a.build_hasher().hash, b.build_hasher().hash); 75 } 76 } 77