Skip to main content

brepkit_math/
det_hash.rs

1//! Deterministic hashing primitives.
2//!
3//! The standard-library `HashMap`/`HashSet` seed their hasher from a
4//! process-global source, so iteration order — and therefore any algorithm
5//! whose output depends on the order it visits map entries — varies between
6//! runs (and even between successive map instances within one process, since
7//! the seed counter advances per instance). For geometry kernels this surfaces
8//! as nondeterministic mesh welding and triangulation: the same input can
9//! produce different vertex merges and face counts run-to-run.
10//!
11//! [`DetHashMap`] / [`DetHashSet`] use a fixed-seed FNV-1a hasher so iteration
12//! order is fully reproducible for a given set of keys. Use them anywhere map
13//! iteration order feeds geometry construction (vertex welds, triangulation,
14//! shell assembly).
15//!
16//! # Security
17//!
18//! This is a deterministic, fixed-seed FNV-1a hasher. It is **not**
19//! DoS-resistant: an adversary who controls the keys can trivially force
20//! collisions. Use it only for internal geometry processing where keys are
21//! derived from trusted topology, never for attacker-controlled input.
22
23use std::hash::{BuildHasher, Hasher};
24
25const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
26const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
27
28/// Fixed-seed FNV-1a hasher. Deterministic across processes and instances.
29///
30/// Not DoS-resistant — see the [module docs](self#security). For internal
31/// geometry processing only.
32#[derive(Clone)]
33pub struct DetHasher(u64);
34
35impl DetHasher {
36    /// Create a hasher seeded with the FNV-1a offset basis.
37    #[must_use]
38    pub const fn new() -> Self {
39        Self(FNV_OFFSET)
40    }
41}
42
43impl Default for DetHasher {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl Hasher for DetHasher {
50    fn finish(&self) -> u64 {
51        self.0
52    }
53
54    fn write(&mut self, bytes: &[u8]) {
55        let mut h = self.0;
56        for &b in bytes {
57            h ^= u64::from(b);
58            h = h.wrapping_mul(FNV_PRIME);
59        }
60        self.0 = h;
61    }
62}
63
64/// `BuildHasher` for [`DetHasher`], seeding each hasher at the FNV-1a offset.
65#[derive(Default, Clone)]
66pub struct DetState;
67
68impl BuildHasher for DetState {
69    type Hasher = DetHasher;
70
71    fn build_hasher(&self) -> Self::Hasher {
72        DetHasher::new()
73    }
74}
75
76/// A `HashMap` with deterministic, reproducible iteration order.
77pub type DetHashMap<K, V> = std::collections::HashMap<K, V, DetState>;
78
79/// A `HashSet` with deterministic, reproducible iteration order.
80pub type DetHashSet<K> = std::collections::HashSet<K, DetState>;
81
82const WORD_MULTIPLIER: u64 = 0xf135_7aea_2e62_a9c5;
83
84/// Fixed-seed hasher that folds in a whole word at each step.
85///
86/// It takes one add and one multiply for each integer, against eight
87/// multiplies for each `u64` in [`DetHasher`]. It is deterministic across
88/// processes and instances, like [`DetHasher`], but its values (and so the
89/// iteration order of its maps) differ from those of [`DetHasher`].
90///
91/// Not DoS-resistant — see the [module docs](self#security). For keys made
92/// of integers, such as grid cells and ids.
93#[derive(Clone, Default)]
94pub struct WordHasher(u64);
95
96impl WordHasher {
97    #[inline]
98    const fn add(&mut self, word: u64) {
99        self.0 = self.0.wrapping_add(word).wrapping_mul(WORD_MULTIPLIER);
100    }
101}
102
103impl Hasher for WordHasher {
104    #[inline]
105    fn finish(&self) -> u64 {
106        // The multiply leaves its best mixed bits at the top, and a hash
107        // table indexes with the bottom ones.
108        self.0.rotate_left(26)
109    }
110
111    fn write(&mut self, bytes: &[u8]) {
112        let mut chunks = bytes.chunks_exact(8);
113        for chunk in &mut chunks {
114            let mut word = [0u8; 8];
115            word.copy_from_slice(chunk);
116            self.add(u64::from_le_bytes(word));
117        }
118        let rest = chunks.remainder();
119        if !rest.is_empty() {
120            let mut word = [0u8; 8];
121            word[..rest.len()].copy_from_slice(rest);
122            self.add(u64::from_le_bytes(word) ^ ((rest.len() as u64) << 59));
123        }
124    }
125
126    #[inline]
127    fn write_u8(&mut self, i: u8) {
128        self.add(u64::from(i));
129    }
130
131    #[inline]
132    fn write_u16(&mut self, i: u16) {
133        self.add(u64::from(i));
134    }
135
136    #[inline]
137    fn write_u32(&mut self, i: u32) {
138        self.add(u64::from(i));
139    }
140
141    #[inline]
142    fn write_u64(&mut self, i: u64) {
143        self.add(i);
144    }
145
146    #[inline]
147    #[allow(clippy::cast_possible_truncation)]
148    fn write_u128(&mut self, i: u128) {
149        self.add(i as u64);
150        self.add((i >> 64) as u64);
151    }
152
153    #[inline]
154    fn write_usize(&mut self, i: usize) {
155        self.add(i as u64);
156    }
157
158    #[inline]
159    #[allow(clippy::cast_sign_loss)]
160    fn write_i8(&mut self, i: i8) {
161        self.add(i as u64);
162    }
163
164    #[inline]
165    #[allow(clippy::cast_sign_loss)]
166    fn write_i16(&mut self, i: i16) {
167        self.add(i as u64);
168    }
169
170    #[inline]
171    #[allow(clippy::cast_sign_loss)]
172    fn write_i32(&mut self, i: i32) {
173        self.add(i as u64);
174    }
175
176    #[inline]
177    #[allow(clippy::cast_sign_loss)]
178    fn write_i64(&mut self, i: i64) {
179        self.add(i as u64);
180    }
181
182    #[inline]
183    #[allow(clippy::cast_sign_loss)]
184    fn write_i128(&mut self, i: i128) {
185        self.write_u128(i as u128);
186    }
187
188    #[inline]
189    #[allow(clippy::cast_sign_loss)]
190    fn write_isize(&mut self, i: isize) {
191        self.add(i as u64);
192    }
193}
194
195/// `BuildHasher` for [`WordHasher`].
196#[derive(Default, Clone)]
197pub struct WordState;
198
199impl BuildHasher for WordState {
200    type Hasher = WordHasher;
201
202    #[inline]
203    fn build_hasher(&self) -> Self::Hasher {
204        WordHasher::default()
205    }
206}
207
208/// A `HashMap` over [`WordHasher`]: deterministic, and quick on integer keys.
209pub type WordHashMap<K, V> = std::collections::HashMap<K, V, WordState>;
210
211/// A `HashSet` over [`WordHasher`]: deterministic, and quick on integer keys.
212pub type WordHashSet<K> = std::collections::HashSet<K, WordState>;
213
214#[cfg(test)]
215mod tests {
216    #![allow(clippy::unwrap_used, clippy::expect_used)]
217    use super::*;
218
219    fn hash_writes(writes: &[&[u8]]) -> u64 {
220        let mut h = DetHasher::new();
221        for w in writes {
222            h.write(w);
223        }
224        h.finish()
225    }
226
227    #[test]
228    fn empty_hash_is_offset_basis() {
229        assert_eq!(DetHasher::new().finish(), FNV_OFFSET);
230    }
231
232    #[test]
233    fn distinct_sequences_differ() {
234        assert_ne!(hash_writes(&[b"abc"]), hash_writes(&[b"abd"]));
235    }
236
237    #[test]
238    fn write_is_order_sensitive() {
239        assert_ne!(hash_writes(&[b"ab", b"cd"]), hash_writes(&[b"cd", b"ab"]),);
240    }
241
242    #[test]
243    fn zero_state_does_not_restart() {
244        // A running state that reaches exactly zero must keep folding in
245        // subsequent bytes rather than silently reverting to the offset
246        // basis. Find a single byte that drives the state to 0, then verify
247        // that appending more bytes keeps the two distinct streams distinct.
248        let target = (0u16..=u16::from(u8::MAX)).map(|b| b as u8).find(|&b| {
249            let mut h = DetHasher::new();
250            h.write(&[b]);
251            h.finish() == 0
252        });
253        if let Some(zeroing) = target {
254            let mut a = DetHasher::new();
255            a.write(&[zeroing]);
256            a.write(&[0x01]);
257
258            // A hasher that began life at zero would, under the old buggy
259            // logic, hash [0x01] identically. Build that comparison stream.
260            let mut b = DetHasher::new();
261            b.write(&[0x01]);
262            assert_ne!(a.finish(), b.finish());
263        }
264
265        // Regardless of whether a zeroing byte exists for this FNV constant,
266        // assert the invariant that distinct streams stay distinct even when
267        // one of them is the empty (offset-basis) stream.
268        assert_ne!(hash_writes(&[]), hash_writes(&[b"x"]));
269    }
270
271    fn word_hash<T: std::hash::Hash>(value: &T) -> u64 {
272        WordState.hash_one(value)
273    }
274
275    #[test]
276    fn word_hash_is_fixed_and_tells_keys_apart() {
277        assert_eq!(
278            word_hash(&(1_i64, -2_i64, 3_i64)),
279            word_hash(&(1_i64, -2_i64, 3_i64))
280        );
281        assert_ne!(
282            word_hash(&(1_i64, 2_i64, 3_i64)),
283            word_hash(&(3_i64, 2_i64, 1_i64))
284        );
285        assert_ne!(word_hash(&(0_u32, 1_u32)), word_hash(&(1_u32, 0_u32)));
286        let mut short = WordHasher::default();
287        short.write(&[0]);
288        let mut empty = WordHasher::default();
289        empty.write(&[]);
290        assert_ne!(short.finish(), empty.finish());
291    }
292
293    /// Neighbouring grid cells spread over the buckets of a small table: the
294    /// bottom bits of their hashes, which index the table, all differ.
295    #[test]
296    fn neighbouring_cells_take_distinct_low_bits() {
297        let mut low = std::collections::HashSet::new();
298        for x in -4_i64..4 {
299            for y in -4_i64..4 {
300                for z in -2_i64..2 {
301                    low.insert(word_hash(&(x, y, z)) & 0xffff);
302                }
303            }
304        }
305        assert!(low.len() > 250, "{}", low.len());
306    }
307}