Bloom Filter Probabilistic Membership (Rust)
Implement a Rust bloom filter with k hash functions for probabilistic membership testing.
Code
struct BloomFilter { bits: Vec<u8>, size: usize, k: usize }
impl BloomFilter {
fn new(size: usize, k: usize) -> Self { Self { bits: vec![0u8; size], size, k } }
fn hash(&self, item: &str, seed: usize) -> usize {
let mut h = seed as u64;
for b in item.bytes() { h = (h.wrapping_mul(31).wrapping_add(b as u64)) % self.size as u64; }
h as usize
}
fn add(&mut self, item: &str) { for i in 0..self.k { self.bits[self.hash(item, i + 1)] = 1; } }
fn contains(&self, item: &str) -> bool { (0..self.k).all(|i| self.bits[self.hash(item, i + 1)] == 1) }
}How it works
Bloom Filter Probabilistic Membership (Rust) keeps everything in the functions new, hash, add and contains.
Repetition is confined to for b in item.bytes() { h = (h.wrapping_mul(31).wrapping_add(b as u64)) % self.size as u64; } — the rest of the file is straight-line.
Using it
The entry-point signature is fn new(size: usize, k: usize) -> Self
new is what another module would consume; nothing else here is load-bearing for callers.
Key statements
fn contains(&self, item: &str) -> bool { (0..self.k).all(|i| self.bits[self.hash(item, i + 1)] == 1) }
fn add(&mut self, item: &str) { for i in 0..self.k { self.bits[self.hash(item, i + 1)] = 1; } }
fn new(size: usize, k: usize) -> Self { Self { bits: vec![0u8; size], size, k } }
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `new`, `hash`, `add` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.