use std::hash::{BuildHasherDefault, Hasher};
const K: u64 = 0x51_7c_c1_b7_27_22_0a_95;
#[derive(Default)]
pub struct FxHasher {
hash: u64,
}
impl FxHasher {
#[inline]
fn add(&mut self, i: u64) {
self.hash = (self.hash.rotate_left(5) ^ i).wrapping_mul(K);
}
}
impl Hasher for FxHasher {
#[inline]
fn write(&mut self, mut bytes: &[u8]) {
while bytes.len() >= 8 {
let mut buf = [0u8; 8];
buf.copy_from_slice(&bytes[..8]);
self.add(u64::from_ne_bytes(buf));
bytes = &bytes[8..];
}
if !bytes.is_empty() {
let mut buf = [0u8; 8];
buf[..bytes.len()].copy_from_slice(bytes);
self.add(u64::from_ne_bytes(buf));
}
}
#[inline]
fn write_u8(&mut self, i: u8) {
self.add(i as u64);
}
#[inline]
fn write_usize(&mut self, i: usize) {
self.add(i as u64);
}
#[inline]
fn finish(&self) -> u64 {
self.hash.wrapping_mul(K).rotate_left(26)
}
}
pub type FxBuildHasher = BuildHasherDefault<FxHasher>;
pub type FastMap<K, V> = std::collections::HashMap<K, V, FxBuildHasher>;
#[cfg(test)]
mod tests {
use super::*;
use std::hash::BuildHasher;
#[test]
fn distinct_keys_hash_distinctly_enough() {
let bh = FxBuildHasher::default();
let names = ["PATH", "IFS", "HOME", "x", "_p9k__x", "PWD", "a", "bb"];
let hashes: Vec<u64> = names
.iter()
.map(|n| {
let mut h = bh.build_hasher();
h.write(n.as_bytes());
h.finish()
})
.collect();
for i in 0..hashes.len() {
for j in i + 1..hashes.len() {
assert_ne!(hashes[i], hashes[j], "{} vs {}", names[i], names[j]);
}
}
}
#[test]
fn fastmap_roundtrips() {
let mut m: FastMap<String, i32> = FastMap::default();
m.insert("PATH".into(), 1);
m.insert("HOME".into(), 2);
assert_eq!(m.get("PATH"), Some(&1));
assert_eq!(m.get("HOME"), Some(&2));
assert_eq!(m.get("nope"), None);
assert_eq!(m.len(), 2);
}
}