use std::hash::{BuildHasherDefault, Hasher};
const SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
#[derive(Default, Clone, Copy)]
pub struct FxHasher {
hash: u64,
}
impl FxHasher {
#[inline]
fn add(&mut self, word: u64) {
self.hash = (self.hash.rotate_left(5) ^ word).wrapping_mul(SEED);
}
}
impl Hasher for FxHasher {
#[inline]
fn finish(&self) -> u64 {
let mut hash = self.hash;
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
hash ^= hash >> 33;
hash
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
let mut rest = bytes;
while let Some((word, tail)) = rest.split_at_checked(8) {
if let Ok(word) = <[u8; 8]>::try_from(word) {
self.add(u64::from_le_bytes(word));
}
rest = tail;
}
if !rest.is_empty() {
let mut last = [0u8; 8];
last[..rest.len()].copy_from_slice(rest);
self.add(u64::from_le_bytes(last));
}
}
#[inline]
fn write_u8(&mut self, value: u8) {
self.add(u64::from(value));
}
#[inline]
fn write_usize(&mut self, value: usize) {
self.add(value as u64);
}
}
pub type FxBuildHasher = BuildHasherDefault<FxHasher>;
pub type FxHashMap<K, V> = std::collections::HashMap<K, V, FxBuildHasher>;
#[inline]
#[must_use]
pub fn hash_bytes(bytes: &[u8]) -> u64 {
let mut hasher = FxHasher::default();
hasher.write(bytes);
hasher.finish()
}
#[cfg(test)]
mod tests {
use super::{FxHashMap, hash_bytes};
#[test]
fn distinct_inputs_hash_differently() {
let samples: Vec<[u8; 8]> = (0u64..4096).map(u64::to_le_bytes).collect();
let mut hashes = samples.iter().map(|s| hash_bytes(s)).collect::<Vec<_>>();
hashes.sort_unstable();
let before = hashes.len();
hashes.dedup();
assert_eq!(
hashes.len(),
before,
"collisions among 4096 sequential keys"
);
}
#[test]
fn hashing_is_stable_and_length_sensitive() {
assert_eq!(hash_bytes(b"12345678"), hash_bytes(b"12345678"));
assert_ne!(hash_bytes(b"12345678"), hash_bytes(b"12345679"));
assert_ne!(hash_bytes(b"1234"), hash_bytes(b"12345"));
assert_ne!(hash_bytes(b""), hash_bytes(b"1"));
assert_eq!(hash_bytes(b"123456789"), hash_bytes(b"123456789"));
}
#[test]
fn low_bits_spread_for_high_order_variation() {
const KEYS: u64 = 4096;
const MASK: u64 = 0xFFF;
let mut buckets = (0..KEYS)
.map(|key| hash_bytes(&key.to_be_bytes()) & MASK)
.collect::<Vec<_>>();
buckets.sort_unstable();
buckets.dedup();
assert!(
buckets.len() as u64 > KEYS / 2,
"only {} distinct bucket indices for {KEYS} keys",
buckets.len()
);
}
#[test]
fn map_of_high_order_keys_is_not_quadratic() {
const KEYS: u64 = 200_000;
let start = std::time::Instant::now();
let mut map: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
for key in 0..KEYS {
map.insert(key.to_be_bytes().to_vec(), key);
}
for key in 0..KEYS {
assert_eq!(map.get(key.to_be_bytes().as_slice()), Some(&key));
}
let elapsed = start.elapsed();
assert_eq!(map.len() as u64, KEYS);
assert!(
elapsed.as_secs() < 20,
"filling and probing {KEYS} keys took {elapsed:?}, which suggests clustering"
);
}
#[test]
fn works_as_a_map_hasher() {
let mut map: FxHashMap<Vec<u8>, usize> = FxHashMap::default();
for index in 0..1000usize {
map.insert(index.to_le_bytes().to_vec(), index);
}
assert_eq!(map.len(), 1000);
for index in 0..1000usize {
assert_eq!(map.get(index.to_le_bytes().as_slice()), Some(&index));
}
assert_eq!(map.get(b"missing".as_slice()), None);
}
}