Plug A Fixed Hasher Into HashMap

Implement a Hasher with FNV-1a and hand BuildHasherDefault to HashMap so two identical builds share one bucket layout instead of seeded per instance.

RustData Integrity

Code

rustsnippet
58 lines
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};

// FNV-1a 64:固定初值与质数,哈希只取决于输入字节
struct FnvHasher(u64);

impl Default for FnvHasher {
    fn default() -> Self {
        Self(0xcbf2_9ce4_8422_2325)
    }
}

impl Hasher for FnvHasher {
    fn write(&mut self, bytes: &[u8]) {
        let mut hash = self.0;
        for byte in bytes {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
        self.0 = hash;
    }

    fn finish(&self) -> u64 {
        self.0
    }
}

type FixedMap = HashMap<&'static str, u32, BuildHasherDefault<FnvHasher>>;

fn build() -> FixedMap {
    let mut map = FixedMap::default();
    for (key, value) in [("alpha", 1u32), ("bravo", 2), ("charlie", 3), ("delta", 4)] {
        map.insert(key, value);
    }
    map
}

fn order(map: &FixedMap) -> Vec<&'static str> {
    map.keys().copied().collect()
}

fn main() {
    // 两次相同构建:哈希器固定,桶布局一致,遍历顺序逐项相同
    println!("fixed orders match: {}", order(&build()) == order(&build()));
    println!("lookup: {:?}", build().get("charlie"));

    // 默认 RandomState 每个实例各自播种,顺序不保证一致
    let a: HashMap<&str, u32> = [("alpha", 1), ("bravo", 2), ("charlie", 3), ("delta", 4)]
        .into_iter()
        .collect();
    let b: HashMap<&str, u32> = [("alpha", 1), ("bravo", 2), ("charlie", 3), ("delta", 4)]
        .into_iter()
        .collect();
    let keys_a: Vec<&str> = a.keys().copied().collect();
    let keys_b: Vec<&str> = b.keys().copied().collect();
    println!("default orders match: {}", keys_a == keys_b);
    println!("fixed key order: {:?}", order(&build()));
}

What the code does

Count the functions default, write, finish and build as the entire surface area of Plug A Fixed Hasher Into HashMap.

Iteration happens inside for byte in bytes — everything outside it runs once.

Applying it

Signature: fn default() -> Self

Output lines are prefixed (fixed orders match:, lookup:, default orders match:), making each step’s effect easy to spot.

Treat main as the orchestrator calling order and build in a fixed order.

Statements that matter

let keys_a: Vec<&str> = a.keys().copied().collect();
let keys_b: Vec<&str> = b.keys().copied().collect();
fn order(map: &FixedMap) -> Vec<&'static str> {
    map.keys().copied().collect()
}

Interactive Tools for This Topic

FAQ

What does Plug A Fixed Hasher Into HashMap print when run?
Running the file directly is enough — expect labeled output lines such as `fixed orders match:`, `lookup:`, `default orders match:`.