Skip to main content

solverforge_core/
fast_hash.rs

1/* Deterministic fast hashing for engine-internal index keys.
2
3Index keys are minted by the engine itself (`RowHandle` slots, source
4indexes, descriptor ids, group coordinates); they are never adversarial
5input, so the DoS-resistant seeded default buys nothing on the event
6path and costs a full SipHash round per probe. The default also
7randomises bucket order per process, which an engine advertising a
8reproducible environment mode cannot want.
9
10Integer writes take a multiply-xor round; opaque keys such as `String`
11codes fall back to byte-wise FNV-1a.
12*/
13
14use std::collections::{HashMap, HashSet};
15use std::hash::{BuildHasherDefault, Hasher};
16
17pub type FastMap<K, V> = HashMap<K, V, BuildHasherDefault<FastHasher>>;
18pub type FastSet<T> = HashSet<T, BuildHasherDefault<FastHasher>>;
19
20#[derive(Default)]
21pub struct FastHasher(u64);
22
23impl FastHasher {
24    #[inline]
25    fn mix(&mut self, value: u64) {
26        self.0 = (self.0 ^ value).wrapping_mul(0x9e37_79b9_7f4a_7c15);
27        self.0 ^= self.0 >> 29;
28    }
29}
30
31impl Hasher for FastHasher {
32    #[inline]
33    fn finish(&self) -> u64 {
34        self.0
35    }
36
37    #[inline]
38    fn write(&mut self, bytes: &[u8]) {
39        for &byte in bytes {
40            self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
41        }
42    }
43
44    #[inline]
45    fn write_u8(&mut self, value: u8) {
46        self.mix(u64::from(value));
47    }
48
49    #[inline]
50    fn write_u16(&mut self, value: u16) {
51        self.mix(u64::from(value));
52    }
53
54    #[inline]
55    fn write_u32(&mut self, value: u32) {
56        self.mix(u64::from(value));
57    }
58
59    #[inline]
60    fn write_u64(&mut self, value: u64) {
61        self.mix(value);
62    }
63
64    #[inline]
65    fn write_usize(&mut self, value: usize) {
66        self.mix(value as u64);
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use std::hash::Hash;
74
75    fn hash_of<T: Hash>(value: T) -> u64 {
76        let mut hasher = FastHasher::default();
77        value.hash(&mut hasher);
78        hasher.finish()
79    }
80
81    #[test]
82    fn hashes_integers_deterministically() {
83        assert_eq!(hash_of(7usize), hash_of(7usize));
84        assert_ne!(hash_of(7usize), hash_of(8usize));
85    }
86
87    #[test]
88    fn hashes_tuples_and_byte_keys() {
89        assert_ne!(hash_of((1usize, 2usize)), hash_of((2usize, 1usize)));
90        assert_ne!(hash_of("alpha"), hash_of("beta"));
91    }
92
93    #[test]
94    fn fast_maps_use_the_fast_hasher() {
95        let mut map = FastMap::<usize, usize>::default();
96        map.insert(1, 2);
97        assert_eq!(map.get(&1), Some(&2));
98        let mut set = FastSet::<usize>::default();
99        set.insert(3);
100        assert!(set.contains(&3));
101    }
102}