Advertisement
theultraman20

Untitled

Jul 29th, 2024
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.11 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: [u8; 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.     //const NUM_BYTES: usize = (M+1)/8;
  15.  
  16.     pub fn new(num_hashes: usize) -> Self {
  17.         BloomFilter::<T, M> {
  18.             bit_array: [0; M],
  19.             num_hashes: num_hashes,
  20.             phantom_data: PhantomData,
  21.         }
  22.     }
  23.  
  24.     pub fn insert(&mut self, elem: &T) {
  25.         for i in 0..self.num_hashes {
  26.             let mut hasher = DefaultHasher::new();
  27.             elem.hash(&mut hasher);
  28.             hasher.write_usize(i);
  29.             let idx = hasher.finish() as usize;
  30.  
  31.             self.bit_array[idx/8 % M] |= 1 >> idx%8;
  32.         }
  33.     }
  34.  
  35.     pub fn search(&self, elem: &T) -> bool {
  36.         for i in 0..self.num_hashes {
  37.             let mut hasher = DefaultHasher::new();
  38.             elem.hash(&mut hasher);
  39.             hasher.write_usize(i);
  40.             let idx = hasher.finish() as usize;
  41.  
  42.             if self.bit_array[idx/8 % M] & (1 >> idx%8) != 0 { return false; }
  43.         }
  44.  
  45.         true
  46.     }
  47.  
  48.     pub fn reset(&mut self) {
  49.         self.bit_array = [0; M];
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement