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.

RustData Integrity

Code

rustsnippet
39 lines
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

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.