Rust Reference ยท Standard Library Modules
The std::hash module
Reference for Rust std::hash: the Hash, Hasher and BuildHasher traits, DefaultHasher, RandomState, BuildHasherDefault and plugging a custom hasher into HashMap.
std::hash defines how Rust turns a value into a number. Three traits split the job. Hash is implemented by the data: it feeds the parts of the value that matter for equality into a hasher. Hasher is the algorithm: it accumulates bytes and produces a u64 with finish(). BuildHasher is a factory that creates fresh hashers, and is what HashMap and HashSet store.
The separation lets one type be hashed by many algorithms, and lets a map choose its algorithm through its third type parameter: HashMap<K, V, S = RandomState>. The default, RandomState, produces DefaultHasher instances (SipHash 1-3) seeded randomly per map, which protects against hash-flooding attacks but is slower than simple hashes.
use std::hash::{DefaultHasher, Hash, Hasher}; let mut h = DefaultHasher::new(); "hello".hash(&mut h); let code = h.finish();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
trait Hash { fn hash<H: Hasher>(&self, state: &mut H); } trait Hasher { fn finish(&self) -> u64; fn write(&mut self, bytes: &[u8]); /* write_u8 ... write_usize */ } trait BuildHasher { type Hasher: Hasher; fn build_hasher(&self) -> Self::Hasher; fn hash_one<T: Hash>(&self, x: T) -> u64; }
| Item | Description |
|---|---|
Hash |
Derivable with #[derive(Hash)]. Required (with Eq) for HashMap keys. |
Hasher |
Implement write and finish; the integer write_* methods have defaults. |
BuildHasher |
Creates hashers; hash_one is a shortcut (stable since 1.71). |
BuildHasherDefault<H> |
A BuildHasher for any H: Default + Hasher. |
DefaultHasher |
std::hash::DefaultHasher (moved here in 1.76; also at std::collections::hash_map::DefaultHasher). |
RandomState |
The default BuildHasher of HashMap; random keys per instance. |
SipHasher |
Deprecated; use DefaultHasher. |
Usage notes
- The golden rule: if
a == bthenhash(a) == hash(b). When you implementPartialEqby hand, implementHashover the same fields. The reverse is not required: different values may collide. DefaultHasher::new()is deterministic within one Rust version (fixed keys) but the algorithm is explicitly unspecified. Do not store its output on disk or send it over a network.RandomState::new()differs from run to run, which is whyHashMapiteration order varies.- Faster hashers (FxHash, AHash, FNV) are available from crates or hand-written like above; they trade away DoS resistance, so use them only on trusted keys.
- Hashing floats is not supported (
f64is notHash); hashx.to_bits()or use an ordered wrapper. - Slices and strings write a length prefix or terminator so that
("ab", "c")and("a", "bc")hash differently. - Borrowed lookup (
map.get("key")on aHashMap<String, V>) relies onStringandstrhashing identically, as the first example shows. Hasher::writemay be called in any chunking: hashing[1u8, 2]as one write or two must not matter to a well-behaved hasher.
Related
HashMap<K, V>,HashSet<T>,std::cmp,std::collections- Lessons: HashMap, Random and hashing