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) }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.