Rust Reference ยท Collections
Rust Hash, Hasher and RandomState
Reference for hashing in Rust: the Hash trait and derive, Hasher and BuildHasher, DefaultHasher, RandomState, writing a custom hasher for HashMap.
Hashing in Rust is split into three roles. The Hash trait describes what to feed into a hash for a value (usually via #[derive(Hash)]). A Hasher is the state machine that consumes those bytes and produces a u64. A BuildHasher is a factory that creates fresh hashers; HashMap and HashSet hold one as their third type parameter.
The default factory is RandomState, which creates SipHash 1-3 hashers seeded with random keys, so hashes differ between maps and between runs. That protects servers from hash-flooding attacks and is why HashMap iteration order is not stable. DefaultHasher is the hasher type that RandomState builds.
use std::hash::{DefaultHasher, Hash, Hasher}; let mut h = DefaultHasher::new(); "hello".hash(&mut h); let digest: u64 = 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
pub trait Hash { fn hash<H: Hasher>(&self, state: &mut H); } pub trait Hasher { fn finish(&self) -> u64; fn write(&mut self, bytes: &[u8]); // provided: write_u8, write_u32, write_u64, write_usize, write_str, ... } pub trait BuildHasher { type Hasher: Hasher; fn build_hasher(&self) -> Self::Hasher; fn hash_one<T: Hash>(&self, x: T) -> u64; } pub struct RandomState; // BuildHasher with random SipHash 1-3 keys pub struct DefaultHasher; // the Hasher built by RandomState; also DefaultHasher::new() pub struct BuildHasherDefault<H>; // BuildHasher for any H: Default + Hasher
| Name | Description |
|---|---|
state |
The hasher that receives the value's data. |
bytes |
Raw bytes to mix into the hash state. |
x |
Any Hash value for BuildHasher::hash_one. |
Returns: finish returns the 64-bit hash; it can be called repeatedly without resetting the state. hash_one creates a hasher, feeds it the value and returns the result.
Errors and panics: none. A wrong Hash/Eq pair does not cause undefined behavior, only incorrect lookups.
Usage notes
- The core law:
a == bmust implyhash(a) == hash(b).#[derive(Hash, PartialEq, Eq)]together always obey it; handwritten implementations must hash exactly the fields used ineq. DefaultHasher::new()is deterministic within one Rust release but its algorithm is not guaranteed across versions. Never store its output on disk or send it across the network.RandomState::new()makes a distinct seed;HashMap::new()uses it. Two maps with the same contents may iterate differently.- Speed vs safety: SipHash is robust, not the fastest. Faster non-cryptographic hashers (FNV, FxHash, ahash) are fine for trusted keys such as internal integers and risky for attacker-controlled keys. They live in crates; the standard library only provides the traits and
BuildHasherDefault. - Prefix freedom:
strand slices hash their length too, so("ab", "c")and("a", "bc")hash differently. - Floats do not implement
Hash(orEq). Hashf.to_bits()yourself if you must, remembering that0.0and-0.0differ andNaNhas many bit patterns. - Not cryptographic. For checksums or signatures use a dedicated crypto library.
- Hash a slice of values with
Hash::hash_slice; for most uses.hash()on the slice itself suffices.