Sub topic 15
Hashing and Custom Hashers
This chapter assumes you can use HashMap, including the entry API. It also assumes you know how to derive Eq and Hash for a key type and have a working grasp of traits and generics. Here you will see what happens between map.insert(key, value) and the moment the entry lands in memory. You will also learn when to replace the default hasher and how to write your own.
How a HashMap turns a key into a bucket
A HashMap<K, V, S> has three type parameters. The third, S, is the hash builder. If you write HashMap<K, V>, S defaults to RandomState.
Three traits cooperate:
Hashis implemented by the key type. It describes which parts of the key take part in hashing by feeding them into a hasher.Hasheris the algorithm. It accumulates bytes through methods such aswriteandwrite_u8, andfinishreturns au64.BuildHasheris a factory. The map calls it to create a freshHasherfor every operation.
The map never calls finish and stops there. It uses the u64 to choose where to look, then compares candidates with ==. The hash narrows the search and Eq makes the final decision.
The contract between Eq and Hash
The standard library requires one rule: if a == b, then hash(a) must equal hash(b). The reverse does not need to hold. Different keys may collide, and Eq sorts them out.
Breaking the rule does not cause undefined behavior, but the map will give wrong answers. Equal keys land in different buckets, so lookups miss and duplicates appear. Deriving both traits together keeps the rule intact. The risk appears when you write one of them by hand.
This type compares keys without regard to ASCII case. Its Hash implementation therefore lowercases each byte before hashing:
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[derive(Debug)]
struct CaseInsensitive(String);
impl PartialEq for CaseInsensitive {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(&other.0)
}
}
impl Eq for CaseInsensitive {}
impl Hash for CaseInsensitive {
fn hash<H: Hasher>(&self, state: &mut H) {
for b in self.0.bytes() {
state.write_u8(b.to_ascii_lowercase());
}
}
}
fn main() {
let mut map = HashMap::new();
map.insert(CaseInsensitive(String::from("Rust")), 1);
let old = map.insert(CaseInsensitive(String::from("RUST")), 2);
println!("{:?}", old); // Some(1)
println!("{}", map.len()); // 1
println!("{:?}", map.get(&CaseInsensitive(String::from("rUsT")))); // Some(2)
}Note that the second insert replaces the value but keeps the original key, "Rust". If the Hash implementation hashed the raw bytes instead, "Rust" and "RUST" would usually land in different buckets. The map would then hold two entries that compare equal.
Two more rules follow from this contract:
f32andf64do not implementEqorHash, becauseNaN != NaN. To use a float as a key, wrap its bits (f.to_bits()) in a type of your own and decide how to treatNaNand-0.0.- A key must not change in a way that alters its hash or equality while it sits in the map. Safe Rust prevents this for ordinary types. Interior mutability such as
RefCellorCellinside a key can still break it. The result is a lost entry, not a crash.
Hashing a value by hand
You can drive a hasher yourself. This is useful for checksums in tests, for sharding, and for seeing what the map sees.
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(&"abc") == hash_of(&"abc")); // true
println!("{}", hash_of(&(1, 2)) == hash_of(&(2, 1))); // false (almost certainly)
}DefaultHasher::new() always starts from the same state, so the result is the same inside one build. The standard library does not promise that the algorithm stays the same across Rust releases. Never write these hashes to disk or send them to another program and expect them to match later.
Why the default is SipHash with random keys
RandomState builds hashers that use SipHash, seeded with random keys. The seed is chosen when the RandomState is created, and each new HashMap gets its own. This has two effects:
- Iteration order differs between runs and between maps. This is why the word-count example sorts its output.
- An attacker cannot predict which keys collide. Without a random seed, someone who controls the keys, such as query-string parameters or JSON field names, could craft thousands that share a bucket. Each lookup would then scan a long chain, which turns a fast map into a slow one. This is a hash-flooding denial of service.
The cost is speed. SipHash is built for security, not for the smallest per-call overhead. For short keys such as integers, the hashing can take longer than the rest of the lookup.
Writing a custom hasher
When keys come from your own program and not from an attacker, a faster, simpler hasher can speed up a hot map. The example below implements FNV-1a, a short algorithm that processes one byte at a time.
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
struct Fnv1a(u64);
impl Default for Fnv1a {
fn default() -> Self {
Fnv1a(0xcbf29ce484222325)
}
}
impl Hasher for Fnv1a {
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<Fnv1a>>;
fn main() {
let mut stock: FnvMap<&str, u32> = FnvMap::default();
stock.insert("apple", 3);
stock.insert("pear", 8);
println!("{:?}", stock.get("apple")); // Some(3)
println!("{:?}", stock.get("plum")); // None
}A few points about this code:
Hasherhas only two required methods,writeandfinish. The other methods, such aswrite_u32, have default bodies that callwrite.BuildHasherDefault<H>is a ready-madeBuildHasherfor any hasher that implementsDefault. It saves you from writing a factory type.HashMap::new()exists only forRandomState. For other hashers, useHashMap::default()orHashMap::with_hasher(builder).- The map's type now includes the hasher. A function that accepts
HashMap<K, V>will not accept anFnvMap. Use a type alias, as above, or make the function generic overS: BuildHasher.
Most projects do not write a hasher themselves. They use a published one, such as the fnv, rustc-hash or ahash crates, and set the type alias once.
Choosing a hasher
| Hasher | Strengths | Weaknesses | Use it when |
|---|---|---|---|
| `RandomState` (SipHash) | Resists hash flooding, needs no setup | Slower on short keys | Keys may come from untrusted input |
| FNV | Tiny, fast on short keys | Predictable, weak on long keys | Small trusted keys, simple code |
| `rustc-hash` (Fx) | Very fast on integers | Predictable, poor distribution on some key patterns | Trusted internal data, such as compiler-style workloads |
| `ahash` | Fast, with a random seed by default | An extra dependency | You want speed without giving up all collision resistance |
Measure before you switch. A profiler may show that hashing is a small part of your run time. If so, the default is the better choice, because it is safe against bad input.
Common mistakes
- Deriving
Hashbut writingPartialEqby hand. The derived hash covers all fields, while youreqmay ignore some. Equal keys then hash differently. Write both by hand, or derive both. - Depending on iteration order. With
RandomStatethe order is unspecified and changes between runs. Sort the output or use aBTreeMapwhen order matters. - Persisting
DefaultHasheroutput. The algorithm may change in a future release. Use a documented algorithm from a crate when you need stable values. - Using a hasher that ignores part of the input. A
finishthat returns a constant still gives correct results, but every key collides and lookups become linear scans.
Exercise
A teammate derives Hash on a struct User { id: u32, name: String } but implements PartialEq so that two users are equal when their id values match. Which problem can this cause in a HashMap<User, Data>, and how would you fix it?
Show answer
Two users with the same id but different name values compare equal but produce different hashes, which breaks the rule that equal keys must hash equally. The map may place them in different buckets, so get can miss an entry that is "equal" and insert can store duplicates. To fix it, implement Hash by hand so that it hashes only id, which makes it agree with eq.
Exercise
Why does HashMap::new() not work for a map that uses BuildHasherDefault<Fnv1a>, and what do you call instead?
Show answer
new is defined only for maps whose hash builder is RandomState. For any other hasher, call HashMap::default(), which works whenever the builder implements Default, or call HashMap::with_hasher(builder) with a builder value.