Manual Hash Skips Volatile Fields
Hand-write Hash so only identity fields feed the Hasher; a volatile timestamp stays in Eq but out of the digest, keeping buckets stable across checks.
Code
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[derive(Debug, PartialEq, Eq)]
struct Doc {
path: String,
revision: u32,
checked_at: u64,
}
// manual Hash skips volatile fields: feeds only identity fields
impl Hash for Doc {
fn hash<H: Hasher>(&self, state: &mut H) {
self.path.hash(state);
self.revision.hash(state);
}
}
fn hash_of(doc: &Doc) -> u64 {
let mut h = DefaultHasher::new();
doc.hash(&mut h);
h.finish()
}
fn main() {
let a = Doc { path: String::from("main.rs"), revision: 3, checked_at: 100 };
let b = Doc { path: String::from("main.rs"), revision: 3, checked_at: 999 };
// Eq sees two distinct keys while Hash matches: unequal keys may share a bucket, the contract holds
println!("a != b: {}", a != b);
println!("same digest: {}", hash_of(&a) == hash_of(&b));
let mut index = HashMap::new();
index.insert(a, 120);
index.insert(b, 88);
let probe = Doc { path: String::from("main.rs"), revision: 3, checked_at: 100 };
println!("bytes for a: {}", index[&probe]);
}What the demo skips
Doc carries path, revision and the volatile checked_at, but the hand-written Hash feeds only path and revision into the Hasher. Two docs identical except for checked_at therefore produce the same digest, which is why the printed same digest line is true.
Eq still compares all fields, so a != b prints true: unequal keys are allowed to share a bucket, which is exactly the Hash and Eq contract. The HashMap demo shows the consequence: inserting both docs works, and probing with a third instance of a returns the stored 120.
Points to remember
- hash must stay consistent with the equality PartialEq defines.
- DefaultHasher::new is fixed-seed, so digest values are reproducible.
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Why exclude checked_at from the hash?
- It is volatile bookkeeping; feeding it would reshuffle buckets on every check. Keeping it out makes lookups stable while Eq still treats unequal timestamps as different keys.
Report a problem with this exampleOpens a pre-filled issue on GitHub.