Advertisement
theultraman20

Untitled

Jul 29th, 2024
402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.14 KB | None | 0 0
  1.  
  2. use std::hash::{DefaultHasher, Hash, Hasher};
  3. use std::marker::PhantomData;
  4. use bit_set::BitSet;
  5.  
  6. pub struct BloomFilter<T, const M: usize> {
  7.     const NUM_BYTES: usize = (M+1)/8,
  8.     bit_array: [u8; NUM_BYTES],
  9.     num_hashes: usize, 
  10.     //necessary to enforce homogenuity
  11.     phantom_data: PhantomData<T>
  12. }
  13.  
  14. impl<T: Hash, const M: usize> BloomFilter<T, M> {
  15.  
  16.     pub fn new(num_hashes: usize) -> Self {
  17.         BloomFilter::<T, M> {
  18.             bit_array: [0; NUM_BYTES],
  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] |= (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] & (1 >> idx%8)) { return false; }
  43.         }
  44.  
  45.         true
  46.     }
  47.  
  48.     pub fn reset(&mut self) {
  49.         self.bit_array = [0; NUM_BYTES];
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement