Deterministic Buckets With DefaultHasher
Hash keys into shards with DefaultHasher for stable in-process bucketing, remembering that the output is not portable across releases.
Code
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
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.