Advertisement
theultraman20

bloom_filter.rs

Jul 26th, 2024
458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.85 KB | None | 0 0
  1. use std::hash::{DefaultHasher, Hash, Hasher};
  2.  
  3. //T = element type, M = num bits
  4. struct BloomFilter<const M: usize> {
  5.     bit_array: [bool; M],
  6.     num_hashes: usize, 
  7. }
  8.  
  9. impl<T, const M: usize> BloomFilter<M>
  10. where
  11.     T: Hash,
  12. {
  13.  
  14.     fn new(num_hashes: usize) -> Self {
  15.         BloomFilter::<M> {
  16.             bit_array: [false; M],
  17.             num_hashes: num_hashes,
  18.         }
  19.     }
  20.  
  21.     fn insert(&mut self, elem: &T) {
  22.         for i in 0..self.num_hashes {
  23.             let mut hasher = DefaultHasher::new();
  24.             elem.hash(&mut hasher);
  25.             hasher.write_usize(i);
  26.  
  27.             self.bit_array[hasher.finish() as usize % M] = true;
  28.         }
  29.     }
  30.  
  31.     fn must_contain(&self, elem: &T) -> bool {
  32.         for i in 0..self.num_hashes {
  33.             let mut hasher = DefaultHasher::new();
  34.             elem.hash(&mut hasher);
  35.             hasher.write_usize(i);
  36.  
  37.             if !self.bit_array[hasher.finish() as usize % M] { return false; }
  38.         }
  39.  
  40.         true
  41.     }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement