1use std::hash::{BuildHasherDefault, Hasher};
16
17const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
19
20#[derive(Default, Clone, Copy)]
25pub struct FxHasher {
26 hash: u64,
28}
29
30impl FxHasher {
31 #[inline]
33 fn add(&mut self, word: u64) {
34 self.hash = (self.hash.rotate_left(5) ^ word).wrapping_mul(SEED);
35 }
36}
37
38impl Hasher for FxHasher {
39 #[inline]
40 fn finish(&self) -> u64 {
41 let mut hash = self.hash;
51 hash ^= hash >> 33;
52 hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
53 hash ^= hash >> 33;
54 hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
55 hash ^= hash >> 33;
56 hash
57 }
58
59 #[inline]
60 fn write(&mut self, bytes: &[u8]) {
61 let mut rest = bytes;
62
63 while let Some((word, tail)) = rest.split_at_checked(8) {
64 if let Ok(word) = <[u8; 8]>::try_from(word) {
66 self.add(u64::from_le_bytes(word));
67 }
68 rest = tail;
69 }
70
71 if !rest.is_empty() {
72 let mut last = [0u8; 8];
73 last[..rest.len()].copy_from_slice(rest);
74 self.add(u64::from_le_bytes(last));
75 }
76 }
77
78 #[inline]
79 fn write_u8(&mut self, value: u8) {
80 self.add(u64::from(value));
81 }
82
83 #[inline]
84 fn write_usize(&mut self, value: usize) {
85 self.add(value as u64);
86 }
87}
88
89pub type FxBuildHasher = BuildHasherDefault<FxHasher>;
91
92pub type FxHashMap<K, V> = std::collections::HashMap<K, V, FxBuildHasher>;
94
95#[inline]
97#[must_use]
98pub fn hash_bytes(bytes: &[u8]) -> u64 {
99 let mut hasher = FxHasher::default();
100 hasher.write(bytes);
101 hasher.finish()
102}
103
104#[cfg(test)]
105mod tests {
106 use super::{FxHashMap, hash_bytes};
107
108 #[test]
109 fn distinct_inputs_hash_differently() {
110 let samples: Vec<[u8; 8]> = (0u64..4096).map(u64::to_le_bytes).collect();
112 let mut hashes = samples.iter().map(|s| hash_bytes(s)).collect::<Vec<_>>();
113 hashes.sort_unstable();
114 let before = hashes.len();
115 hashes.dedup();
116 assert_eq!(
117 hashes.len(),
118 before,
119 "collisions among 4096 sequential keys"
120 );
121 }
122
123 #[test]
124 fn hashing_is_stable_and_length_sensitive() {
125 assert_eq!(hash_bytes(b"12345678"), hash_bytes(b"12345678"));
126 assert_ne!(hash_bytes(b"12345678"), hash_bytes(b"12345679"));
127
128 assert_ne!(hash_bytes(b"1234"), hash_bytes(b"12345"));
130 assert_ne!(hash_bytes(b""), hash_bytes(b"1"));
131 assert_eq!(hash_bytes(b"123456789"), hash_bytes(b"123456789"));
132 }
133
134 #[test]
140 fn low_bits_spread_for_high_order_variation() {
141 const KEYS: u64 = 4096;
142 const MASK: u64 = 0xFFF;
143
144 let mut buckets = (0..KEYS)
147 .map(|key| hash_bytes(&key.to_be_bytes()) & MASK)
148 .collect::<Vec<_>>();
149 buckets.sort_unstable();
150 buckets.dedup();
151
152 assert!(
154 buckets.len() as u64 > KEYS / 2,
155 "only {} distinct bucket indices for {KEYS} keys",
156 buckets.len()
157 );
158 }
159
160 #[test]
162 fn map_of_high_order_keys_is_not_quadratic() {
163 const KEYS: u64 = 200_000;
164
165 let start = std::time::Instant::now();
166 let mut map: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
167 for key in 0..KEYS {
168 map.insert(key.to_be_bytes().to_vec(), key);
169 }
170 for key in 0..KEYS {
171 assert_eq!(map.get(key.to_be_bytes().as_slice()), Some(&key));
172 }
173 let elapsed = start.elapsed();
174
175 assert_eq!(map.len() as u64, KEYS);
176 assert!(
177 elapsed.as_secs() < 20,
178 "filling and probing {KEYS} keys took {elapsed:?}, which suggests clustering"
179 );
180 }
181
182 #[test]
183 fn works_as_a_map_hasher() {
184 let mut map: FxHashMap<Vec<u8>, usize> = FxHashMap::default();
185 for index in 0..1000usize {
186 map.insert(index.to_le_bytes().to_vec(), index);
187 }
188
189 assert_eq!(map.len(), 1000);
190 for index in 0..1000usize {
191 assert_eq!(map.get(index.to_le_bytes().as_slice()), Some(&index));
192 }
193 assert_eq!(map.get(b"missing".as_slice()), None);
194 }
195}