man rust/hashmap
How Rust's HashMap works: hashbrown, Swiss tables and SipHash
Why does a Rust HashMap list its keys in a different order every run, and
in a different order again for a second map built from the same keys? And
how much does its default hash function cost for integer keys?
use std::collections::HashMap;
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in text.split_ascii_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
This article reads the standard library at the 1.100.1 tag and the hashbrown
crate at v0.17.1, the version that tag’s library/Cargo.lock pins. I
checked what the source says with small programs built with
rustc --edition 2024 -C opt-level=3 on an Apple M2 Pro. Every number below
comes from that source, the release notes, or one of those programs.
The short version
std::collections::HashMap is a thin wrapper. Its only field is
base: base::HashMap<K, V, S, A>, where base is hashbrown::hash_map, and
the hasher S lives inside that. hashbrown is an open-addressing table with one
control byte per slot. A full slot’s control byte holds 7 bits of the
key’s hash, so a lookup can compare a whole group of control bytes at once
with SIMD and look at actual keys only where those 7 bits match. That is the
design of Google’s SwissTable, which the documentation names: “The hash table
implementation is a Rust port of Google’s SwissTable”. The default hasher,
RandomState, is SipHash-1-3 with two 64-bit keys that are random per
thread and change for every map.
Control bytes
A control byte is one of three things (tag.rs L8-L49):
EMPTY 1111_1111 free, and ends a search
DELETED 1000_0000 free, but a search goes on past it
full 0hhh_hhhh top 7 bits of the key's 64-bit hash
The top bit tells special from full. Tag::full takes hash >> 57, the top
seven bits. The other end of the hash picks the slot. h1 is just
hash as usize, and the first position probed is h1(hash) & bucket_mask
(raw.rs L60-L63,
L2448-L2455).
So the low bits choose where to look and the high bits are what the control
byte remembers.
The table is one allocation. The comment on RawTableInner draws it
(raw.rs L571-L573):
[Padding], T_n, ..., T1, T0, C0, C1, ...
^ ctrl points here
The (key, value) pairs sit before the control bytes in reverse order, so
slot i’s control byte is ctrl[i] and its element is just below ctrl.
There are buckets + Group::WIDTH control bytes
(L223):
set_ctrl copies the first Group::WIDTH control bytes after the end
(L2565-L2573),
so a group load that starts near the end never needs to wrap around.
Groups: 8 bytes on Apple silicon, 16 on x86
Group is chosen at compile time
(group/mod.rs L8-L46):
SSE2 on x86 and x86-64, NEON on little-endian aarch64, LSX on LoongArch with
the nightly feature, and a portable “generic” version otherwise. Its width
is the size of the vector type. On x86 that is __m128i, 16 bytes
(sse2.rs L20-L26).
On aarch64 it is uint8x8_t, 8 bytes
(neon.rs L16-L21).
Matching a tag is one compare of eight bytes against a broadcast copy of the
tag
(L68-L73):
let cmp = neon::vceq_u8(self.0, neon::vdup_n_u8(tag.0));
BitMask(neon::vget_lane_u64(neon::vreinterpret_u64_u8(cmp), 0))
The result is a 64-bit word with 0xFF in each matching byte. rustc --print cfg on this Mac lists target_feature="neon", and the compiled programs
contain the instruction for that compare:
$ objdump -d --no-show-raw-insn hashers | grep -m1 'cmeq\.8b'
100000fec: cmeq.8b v2, v1, v0
The comment above the selection still says the opposite: “I attempted an
implementation on ARM using NEON instructions, but it turns out that most
NEON instructions have multi-cycle latency, which in the end outweighs any
gains over the generic implementation”
(L14-L16).
Eighteen lines further down, the same file picks mod neon for aarch64.
A lookup
find_inner is short
(raw.rs L2008-L2046).
Stripped of its safety comments:
let tag_hash = Tag::full(hash);
let mut probe_seq = self.probe_seq(hash);
loop {
let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) };
for bit in group.match_tag(tag_hash) {
let index = (probe_seq.pos + bit) & self.bucket_mask;
if likely(eq(index)) {
return Some(index);
}
}
if likely(group.match_empty().any_bit_set()) {
return None;
}
probe_seq.move_next(self.bucket_mask);
}
Load a group, compare keys only in the slots whose 7 bits match, stop at the
first group that has an EMPTY byte. That rule decides what removal
writes. erase writes EMPTY when there is an EMPTY byte within one group
width before or after the slot, since a search would stop there anyway, and
DELETED otherwise, so that searches still reach keys further along
(L3242-L3279).
If the group has no empty
slot, move_next jumps ahead by one more group each time: 1 group, then 2,
then 3. The doc comment calls this a “probe sequence based on triangular
numbers” and links a proof that, with a power-of-two table, it visits every
group exactly once
(L65-L93).
std’s own documentation sums it up as “quadratic probing and SIMD lookup”.
Size and growth
The number of slots is always a power of two. Tables of at least 16 slots may
be seven-eighths full, since bucket_mask_to_capacity returns
((bucket_mask + 1) / 8) * 7, while tables of 8 slots or fewer keep one slot
empty
(L182-L191).
For small capacities, capacity_to_buckets picks 4, 8 or 16 slots, and it
raises the minimum for tiny element types so the table isn’t mostly padding
(L104-L164).
When the table is full and an insert needs room, it resizes to at least one
more than its current capacity
(L2786),
which rounds up to the next power of two. Printing capacity() whenever it
changes while inserting i64 keys:
$ rustc --edition 2024 -C opt-level=3 growth.rs && ./growth
empty: capacity 0
len 1: capacity 3
len 4: capacity 7
len 8: capacity 14
len 15: capacity 28
len 29: capacity 56
...
len 28673: capacity 57344
len 57345: capacity 114688
size_of::<HashMap<i64, usize>>() = 48
size_of::<std::hash::RandomState>() = 16
57,344 is 7/8 of 65,536. An empty map allocates nothing. Its control
pointer points at a static group of EMPTY bytes.
The entry API
HashMap::entry calls hashbrown’s rustc_entry
(rustc_entry.rs L35-L54).
It hashes the key once and searches. If the key is missing, it calls
self.reserve(1) right away and returns a vacant entry that keeps the hash,
so or_insert can place the pair with insert_no_grow and no second hash.
The comment explains why the reservation can’t wait: “Ideally we would put
this in VacantEntry::insert, but Entry is not generic over the BuildHasher”.
The vacant entry has no hasher with which to rehash a growing table. One
consequence is that looking alone can grow a map:
let mut m: HashMap<i64, usize> = HashMap::new();
for n in 0..3 {
m.insert(n, 0);
}
println!("len {}, capacity {}", m.len(), m.capacity());
let _ = m.entry(99); // look, but insert nothing
println!("len {}, capacity {}", m.len(), m.capacity());
$ ./entrygrow
len 3, capacity 3
len 3, capacity 7
The keys: per thread, plus one per map
RandomState holds two u64 keys, k0 and k1. Its constructor is
(random.rs L55-L76):
thread_local!(static KEYS: Cell<(u64, u64)> = {
Cell::new(hashmap_random_keys())
});
KEYS.with(|keys| {
let (k0, k1) = keys.get();
keys.set((k0.wrapping_add(1), k1));
RandomState { k0, k1 }
})
The keys come from the system once per thread. The comment above it gives
the history. Drawing fresh keys for every map made creating many maps slow
(issue #31356), so the keys were cached per thread. Then a deterministic
iteration order turned out to allow “a form of DOS attack” (#36481), so
every new RandomState adds 1 to k0. On Apple platforms the 16 bytes come
from CCRandomGenerateBytes
(sys/random/mod.rs L123-L129,
apple.rs L12-L15).
HashMap::new() calls RandomState::new() through Default, so two maps
get different keys and different slot positions. A clone copies the keys and
the table, so it keeps the order:
let a: HashMap<i64, i64> = (1..=10).map(|n| (n, n * n)).collect();
let b: HashMap<i64, i64> = (1..=10).map(|n| (n, n * n)).collect();
let c = a.clone();
println!("a: {:?}", a.keys().collect::<Vec<_>>());
println!("b: {:?}", b.keys().collect::<Vec<_>>());
println!("c: {:?}", c.keys().collect::<Vec<_>>());
println!("a == b: {}", a == b);
$ ./order && ./order
a: [5, 6, 8, 7, 10, 9, 4, 1, 2, 3]
b: [9, 10, 7, 3, 5, 4, 1, 8, 6, 2]
c: [5, 6, 8, 7, 10, 9, 4, 1, 2, 3]
a == b: true
a: [3, 10, 4, 8, 1, 2, 6, 9, 5, 7]
b: [8, 10, 4, 3, 1, 2, 5, 9, 6, 7]
c: [3, 10, 4, 8, 1, 2, 6, 9, 5, 7]
a == b: true
For a fixed order, use BuildHasherDefault<DefaultHasher>. DefaultHasher::new()
is SipHash-1-3 with both keys 0
(L106-L108).
The HashMap docs warn that such a map “is not resistant
to HashDoS attacks!”
SipHash-1-3, and what it costs for integers
build_hasher returns DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
(L83-L85).
In core/src/hash/sip.rs, Sip13Rounds runs one SipRound per 8-byte word
and three in finish
(L358-L371).
An i64 key goes through write_i64, which calls write_u64, which calls
write(&i.to_ne_bytes())
(hash/mod.rs L380-L382,
L417-L419).
SipHasher keeps those defaults on purpose. A comment says integer methods
“would greatly speed up integer hashing by those hashers, at the cost of
slightly slowing down compile speeds on some benchmarks”
(sip.rs L246-L254).
Following the code for one 8-byte key, the byte loop runs once (one
SipRound), finish adds the length byte (one more) and then runs three.
That is five SipRounds, each made of four adds, six rotates and four XORs
on four 64-bit words
(L75-L94).
The documentation is frank about the trade. SipHash 1-3’s “performance is
very competitive for medium sized keys, other hashing algorithms will
outperform it for small keys such as integers”
(map.rs L26-L31).
To see how much, I counted 10 million i64 keys (1 million distinct) with
three hashers: the default, a multiplicative one that multiplies by
0x9E3779B97F4A7C15 and XORs the high half into the low half, and the key
itself as its hash. Best of five, timed inside the program:
$ rustc --edition 2024 -C opt-level=3 hashers.rs && ./hashers
SipHash 224.3 ms (999962 keys)
multiply 74.2 ms (999962 keys)
identity 65.7 ms (999962 keys)
SipHash is three times slower here. The identity hash wins even though every key below 2⁵⁷ gets the same 7-bit tag, 0, so every full slot in a group “matches”. The keys are below a million and the table has 2²¹ slots, so each key lands in its own slot, and the first match is the right one. Make the low bits useless and it falls apart. The same three hashers on 100,000 keys that are all multiples of 2²⁰ (10,000 distinct):
$ ./shifted
SipHash 1.1 ms (9998 keys)
multiply 0.3 ms (9998 keys)
identity 427.6 ms (9998 keys)
Every key’s low 20 bits are zero, so with the identity hash every key starts probing at slot 0, and each insert walks past all the keys before it. That is the attack that keyed hashing exists to stop, only here the input does it by accident.
Curious facts
entry()on a missing key reserves room even if you never insert. A map of 3 keys went from capacity 3 to 7 afterlet _ = m.entry(99);.- The comment that explains why hashbrown has no NEON version sits eighteen lines above the code that selects the NEON version.
HashMap<i64, usize>is 48 bytes on the stack, 16 of them the two SipHash keys of itsRandomState.- Two maps with equal contents, built the same way in the same thread, list
their keys in different orders, because each
RandomState::new()adds 1 tok0. DefaultHasheris documented as “not specified”, and its hashes “should not be relied upon over releases” (random.rs L88-L94).
History
- Rust 1.7.0 (2016-03-03):
RandomStateandBuildHasherbecome stable (the#[stable(since = "1.7.0")]attributes inrandom.rs). - Rust 1.11.0 (2016-08-18): “The default
HashMaphasher is SipHash 1-3 instead of SipHash 2-4”. - Rust 1.13.0 (2016-11-10):
SipHasheris deprecated in favour ofDefaultHasher. - Rust 1.36.0 (2019-07-04): “
HashMap’s implementation has been replaced withhashbrown::HashMapimplementation.”
Sources
- hashbrown v0.17.1: control/tag.rs L8-L49, control/group/mod.rs L8-L46, control/group/neon.rs L16-L73, control/group/sse2.rs L20-L26, raw.rs: h1 L60-L63, probe sequence L65-L93, capacity_to_buckets L104-L164, load factor L182-L191, layout L223, table diagram L571-L573, find_inner L2008-L2046, probe_seq L2448-L2455, erase L3242-L3279, resize L2786, rustc_entry.rs L35-L54
- rust-lang/rust at 1.100.1: library/Cargo.lock L134-L137, std/src/collections/hash/map.rs L15-L31, L59, map.rs wrapper field L251, std/src/hash/random.rs L55-L108, std/src/sys/random/mod.rs L123-L129, std/src/sys/random/apple.rs L12-L15, core/src/hash/sip.rs L246-L254, sip.rs rounds L358-L371, core/src/hash/mod.rs L380-L419
- RELEASES.md at 1.100.1: 1.36.0 (L8794), 1.11.0 (L12948), 1.13.0 (L12514)
- SwissTable announcement,
linked from the
HashMapdocs
grep -rl /lib/rust/hashmap/
ls rust/
- draft How Rust sorts: driftsort, ipnsort and select_nth_unstableWhat slice::sort, sort_unstable and select_nth_unstable do in Rust 1.100.1: driftsort and ipnsort since 1.81, insertion sort up to 20 elements, when the stable sort allocates, an O(n) selection with a median-of-medians fallback, and why a bad comparison can now panic.