rustc_hash/
seeded_state.rs

1use crate::FxHasher;
2
3/// Type alias for a hashmap using the `fx` hash algorithm with [`FxSeededState`].
4#[cfg(feature = "std")]
5pub 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")]
9pub type FxHashSetSeed<V> = std::collections::HashSet<V, FxSeededState>;
10
11/// [`FxSetState`] 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/// ```
21pub struct FxSeededState {
22    seed: usize,
23}
24
25impl FxSeededState {
26    /// Constructs a new `FxSeededState` that is initialized with a `seed`.
27    pub const fn with_seed(seed: usize) -> FxSeededState {
28        Self { seed }
29    }
30}
31
32impl core::hash::BuildHasher for FxSeededState {
33    type Hasher = FxHasher;
34
35    fn build_hasher(&self) -> Self::Hasher {
36        FxHasher::with_seed(self.seed)
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use core::hash::BuildHasher;
43
44    use crate::FxSeededState;
45
46    #[test]
47    fn different_states_are_different() {
48        let a = FxSeededState::with_seed(1);
49        let b = FxSeededState::with_seed(2);
50
51        assert_ne!(a.build_hasher().hash, b.build_hasher().hash);
52    }
53}