Learning question: How does a collection let you replace one of its algorithms without knowing which one you will pick?
HashMap<K, V> has a third type parameter that you can leave unwritten. This article reads what it is, the trait it must implement, and what changes when you supply your own.
Scope. We read library/std/src/collections/hash/map.rs and library/core/src/hash/mod.rs at Rust 1.100.0 [S3]. We do not cover how hash tables resolve collisions, and we do not recommend a hasher. You need traits at the level of "a set of methods a type promises", and generics at the level of Vec<T>. The pattern's parts are named as in Design Patterns [S1, ch. 5, "Strategy"].
A map with a settled view of its own order
Example 1 puts four entries in a map and prints the keys. It was run three times.
Example 1. Compiles; run three times (compile-fail/run07_strategy_order.rs, first half)
let default: HashMap<&str, u32> =
HashMap::from([("bolts", 40), ("nuts", 12), ("washers", 7), ("rivets", 3)]);
println!("RandomState: {:?}", default.keys().collect::<Vec<_>>());
The map held four keys and printed them in an order. A snapshot test had written that order down and believed in it the way a hen believes in the fence. The map was built again by the same code from the same four pairs. It printed them in a different order, and then, on the third run, in another.
RandomState: ["nuts", "rivets", "washers", "bolts"]
RandomState: ["washers", "bolts", "rivets", "nuts"]
RandomState: ["bolts", "washers", "nuts", "rivets"]Predict
Nothing in Example 1 is random on its face. Before reading on: the output label is a hint. Where could a per-run difference be coming from, and where would you expect to be able to turn it off?
Name the parts
| Role in the pattern [S1] | In std | Where [S3] |
|---|---|---|
| Context | HashMap<K, V, S> |
map.rs line 245 |
| Strategy | trait BuildHasher, which produces a Hasher |
core/src/hash/mod.rs lines 637 and 312 |
| ConcreteStrategy (the default) | RandomState |
named as the default at map.rs line 248 |
| ConcreteStrategy (yours) | any type implementing BuildHasher |
your code |
What is S?
A collection that hard-codes its hash function makes one choice for every caller. Thankfully, HashMap takes the function as a parameter. Take a look at Example 2.
Example 2. The context and the strategy (library/std/src/collections/hash/map.rs lines 245 to 252; library/core/src/hash/mod.rs lines 637 to 656, attributes and doc comments removed; the trait's provided method hash_one, line 695, is not shown [S3])
pub struct HashMap<K, V, S = RandomState, A: Allocator = Global> {
base: base::HashMap<K, V, S, A>,
}
pub trait BuildHasher {
type Hasher: Hasher;
fn build_hasher(&self) -> Self::Hasher;
}
The fourth parameter, A, is the allocator; it carries an unstable attribute at line 249 and this article reads past it. There are two new pieces. S = RandomState is a default type parameter: write HashMap<K, V> and you get RandomState without asking. And BuildHasher is a trait with one required method, which hands back a fresh Hasher each time the map needs to hash a key. The documentation on the struct explains the scene: the default algorithm is randomly seeded, and was selected to resist HashDoS attacks [S3, map.rs lines 17 to 18]. That seed is the per-run difference, and S is where you turn it off.
The second half of the same program names a different strategy in the map's type, and builds the map with
HashMap::default() and extend in place of HashMap::from (compile-fail/run07_strategy_order.rs, lines 9 to 11):
let mut fixed: HashMap<&str, u32, BuildHasherDefault<DefaultHasher>> = HashMap::default();
fixed.extend([("bolts", 40), ("nuts", 12), ("washers", 7), ("rivets", 3)]);
println!("BuildHasherDefault: {:?}", fixed.keys().collect::<Vec<_>>());
BuildHasherDefault: ["washers", "nuts", "rivets", "bolts"]
BuildHasherDefault: ["washers", "nuts", "rivets", "bolts"]
BuildHasherDefault: ["washers", "nuts", "rivets", "bolts"]The same order three times. The four pairs and the keys() call are the same as in the first half.
What transfers, and what does not
Passing a comparison callable to usort is the PHP habit closest to this: the manual's signature is usort(array &$array, callable $callback), a sort whose comparison the caller supplies [S4]. Injecting an interface is the same arrangement with a named type. The roles transfer whole. What does not transfer is when the choice is made. The book's Context holds a reference to a Strategy object and can be given a different one while the program runs [S1]. Here the strategy is a type parameter, so HashMap<&str, u32, RandomState> and HashMap<&str, u32, BuildHasherDefault<DefaultHasher>> are two different types, the compiler generates code for each [S5], and a function that takes one will not accept the other: rustc 1.100.0 reports E0308, mismatched types (evidence/ev07_strategy_type_mismatch.rs and .stderr, beside this article; not yet in compile-fail/). The Rust patterns book describes Strategy in the same terms as the original, a family of interchangeable algorithms each in its own type [S2, ch. 7, "Strategy pattern"].
Should you have turned it off?
So the order is stable and the snapshot test passes. The fixed order is still not a promised order, since std documents keys as visiting the keys in arbitrary order (map.rs line 487) and says of DefaultHasher that its internal algorithm is not specified and should not be relied upon over releases (library/std/src/hash/random.rs lines 90 to 91), and std's documentation warns, in bold, that a map built with a hasher that does not rely on a random seed is not resistant to HashDoS attacks (map.rs lines 221 to 222), so for a map whose keys come from a request you have replaced a flaky test with an exposure, and the test was arguably the thing that was wrong. Did the test need a different hasher, or a sorted Vec, or a BTreeMap?
Practice tier: judgment. The compiler checks that S implements BuildHasher. Whether a given strategy is a good idea is not something it can see.
Testing
The claim is that the map calls the strategy it was given. Example 3 supplies the worst possible one and counts the calls.
Example 3. A hasher that always answers 7 (tests/p07_strategy_hasher.rs, abridged: lines 15 to 22, not shown, define BuildConstant, whose build_hasher adds one to BUILT and returns a Constant)
struct Constant;
impl Hasher for Constant {
fn finish(&self) -> u64 { 7 }
fn write(&mut self, _bytes: &[u8]) {}
}
let mut stock: HashMap<&str, u32, BuildConstant> = HashMap::with_hasher(BuildConstant);
stock.insert("bolts", 40);
stock.insert("nuts", 12);
assert_eq!(stock.get("bolts"), Some(&40));
assert_eq!(stock.get("nuts"), Some(&12));
assert_eq!(stock.get("washers"), None);
assert!(BUILT.load(Ordering::Relaxed) >= 5, "one hasher per insert and lookup");
Every key collides, and the map still answers correctly, because the hash only chooses where to look and equality decides what is found (std requires keys to implement both Eq and Hash, map.rs lines 37 to 38). It passed on rustc 1.100.0. It would fail if the map ignored S.
Retrieve
- What does
HashMap<K, V>use forSwhen you do not say? - Why can't you pass a
HashMap<K, V, BuildConstant>to a function that takesHashMap<K, V>?
The Adapters article returns to "a trait the caller is written against", with the trait on the other side of the call.
TL;DR
HashMap<K, V, S> is a Strategy context: S is a type implementing BuildHasher, and it defaults to RandomState, which is randomly seeded. Supplying another S changes how keys are hashed; in this article's program the constructor changed with it, and the keys() call did not. Because the strategy is a type parameter, it is chosen at compile time, and maps with different strategies are different types.