Sub topic 15
Hashing and custom hashers
This chapter assumes you can already insert into and read from a HashMap, and that you know what #[derive(Hash)] does for a key type. It covers what happens between a key and the bucket that holds it, and how to swap in a different hash function.
Hash and Hasher are separate
Two traits split the work:
Hashbelongs to the key type. It decides which fields are fed into the hash, in what order.Hasherbelongs to the algorithm. It receives bytes throughwriteand produces au64fromfinish.
A third trait, BuildHasher, creates a fresh Hasher for each lookup. A HashMap<K, V, S> stores one BuildHasher in its S parameter.
The map uses the hash to find a bucket and then uses Eq to confirm a match. Equal keys must produce equal hashes. If a == b, then hash(a) == hash(b) must hold. Derive both traits together, or write both by hand so they agree.
The default hasher
The default S is RandomState. It builds SipHash 1-3 hashers with random keys chosen per map. That makes it hard for an attacker to craft keys that all collide, an attack known as HashDoS. The cost is speed: SipHash is slower than simple hashes on short keys such as integers.
Do not rely on hash values being stable. DefaultHasher::new() gives the same output within one program, but the standard library does not promise the same output across Rust versions.
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn hash_of<T: Hash>(value: &T) -> u64 {
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
hasher.finish()
}
fn main() {
println!("{}", hash_of(&"rust") == hash_of(&"rust")); // true
println!("{}", hash_of(&1u32) == hash_of(&2u32)); // false
}Writing a custom hasher
You might choose a faster hasher when keys are small and come from a trusted source. This FNV-1a hasher uses only the standard library:
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
struct Fnv(u64);
impl Default for Fnv {
fn default() -> Self {
Fnv(0xcbf29ce484222325)
}
}
impl Hasher for Fnv {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 ^= *b as u64;
self.0 = self.0.wrapping_mul(0x100000001b3);
}
}
}
type FnvMap<K, V> = HashMap<K, V, BuildHasherDefault<Fnv>>;
fn main() {
let mut ages: FnvMap<&str, u32> = FnvMap::default();
ages.insert("Ana", 30);
ages.insert("Bo", 25);
println!("{:?}", ages.get("Bo")); // Some(25)
}BuildHasherDefault<Fnv> is a ready-made BuildHasher for any hasher that implements Default. You must create the map with default() or with_hasher(...). HashMap::new() exists only for RandomState, so calling it here would not compile.
Gotchas
- A fast hasher without random keys is open to HashDoS if keys come from untrusted input such as network requests. Keep
RandomStatethere. - Changing the hasher changes iteration order, which was never specified anyway. Do not depend on it.
- Never persist hash values to disk or send them between programs and expect them to match.
- In real projects, use a maintained crate such as
rustc-hashorahashinstead of writing your own. They are tested and tuned.
Exercise
Why does FnvMap::new() fail to compile, and what do you call instead?
Show answer
HashMap::new is defined only for maps that use RandomState. For a map with BuildHasherDefault<Fnv>, call FnvMap::default() or HashMap::with_hasher(BuildHasherDefault::<Fnv>::default()).
Exercise
A key type implements Eq by comparing only the id field, but derives Hash over all fields. What can go wrong?
Show answer
Two keys with the same id compare equal but can hash differently. The map may look in the wrong bucket and fail to find a key that is present, which breaks the rule that equal keys must have equal hashes.