Skip to main content

vector_core/
fasthash.rs

1//! Hash maps for keys a peer can choose (edition and event ids, npubs) that live within one
2//! computation, as a fold's do: foldhash's speed, seeded with a secret from the OS. foldhash seeds
3//! itself from addresses and the clock, which a wasm build leaves fixed, so a precomputed set of
4//! colliding ids would slow every reader.
5
6use std::hash::BuildHasher;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::OnceLock;
9
10use foldhash::fast::{FoldHasher, SeedableRandomState};
11use foldhash::SharedSeed;
12
13static SECRET: OnceLock<SharedSeed> = OnceLock::new();
14static NEXT: AtomicU64 = AtomicU64::new(0);
15
16/// A map's hasher: the process's secret, and a seed of the map's own.
17#[derive(Clone, Debug)]
18pub struct Seeded(SeedableRandomState);
19
20impl Default for Seeded {
21    fn default() -> Self {
22        let secret = SECRET.get_or_init(|| SharedSeed::from_u64(rand::RngCore::next_u64(&mut rand::rngs::OsRng)));
23        Seeded(SeedableRandomState::with_seed(NEXT.fetch_add(1, Ordering::Relaxed), secret))
24    }
25}
26
27impl BuildHasher for Seeded {
28    type Hasher = FoldHasher<'static>;
29
30    fn build_hasher(&self) -> Self::Hasher {
31        self.0.build_hasher()
32    }
33}
34
35pub type FastMap<K, V> = std::collections::HashMap<K, V, Seeded>;
36pub type FastSet<K> = std::collections::HashSet<K, Seeded>;
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use std::hash::BuildHasher;
42
43    #[test]
44    fn every_map_hashes_its_own_way_and_each_hashes_alike_throughout() {
45        let (a, b) = (Seeded::default(), Seeded::default());
46        let key = [7u8; 32];
47        assert_eq!(a.hash_one(key), a.hash_one(key));
48        assert_ne!(a.hash_one(key), b.hash_one(key), "a fresh seed per map");
49        let mut m: FastMap<[u8; 32], u32> = FastMap::default();
50        m.insert(key, 1);
51        assert_eq!(m.get(&key), Some(&1));
52    }
53}