Advertisement
theultraman20

bloom_filter.rs

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