Deterministic Buckets With DefaultHasher

Hash keys into shards with DefaultHasher for stable in-process bucketing, remembering that the output is not portable across releases.

RustConfig Management

Code

rustsnippet
26 lines
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

fn bucket_of<T: Hash>(value: &T, buckets: u64) -> u64 {
    // DefaultHasher::new 使用固定初始状态:同一构建内结果稳定
    let mut hasher = DefaultHasher::new();
    value.hash(&mut hasher);
    hasher.finish() % buckets
}

fn main() {
    let keys = ["user:1", "user:2", "user:3", "order:9", "order:10"];
    for key in keys {
        println!("{key} -> shard {}", bucket_of(&key, 4));
    }

    // 相同输入得到相同分片,元组也能直接哈希
    let a = bucket_of(&("tenant", 42u32), 8);
    let b = bucket_of(&("tenant", 42u32), 8);
    println!("stable: {a} == {b}");

    // 桶数变化会整体重映射,扩容需要迁移数据
    let four = bucket_of(&"user:1", 4);
    let eight = bucket_of(&"user:1", 8);
    println!("4 buckets={four} 8 buckets={eight}");
}

How it works

Count the functions bucket_of and main as the entire surface area of Deterministic Buckets With DefaultHasher.

The one repetition in this snippet is the loop for key in keys.

Applying it

Look for the stable:, 4 buckets= prefixes when the file runs; they tie each line to its step.

The entry point wires bucket_of together — run it once and the whole demo flows.

Statements that matter

fn bucket_of<T: Hash>(value: &T, buckets: u64) -> u64 {
    // DefaultHasher::new 使用固定初始状态:同一构建内结果稳定
    let mut hasher = DefaultHasher::new();
    value.hash(&mut hasher);
    hasher.finish() % buckets
}

Interactive Tools for This Topic

FAQ

What does Deterministic Buckets With DefaultHasher print when run?
No setup needed: run the file and look for labeled lines like `stable:`, `4 buckets=` in the output.