1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use std::sync::RwLock;

/// bitmap size = 1024 * 8 bit
pub const DEFAULT_SIZE: usize = 1 << 10;
pub const DEFAULT_HASH_LOOP: usize = 10;
pub struct BloomConfig {
    pub size: Option<usize>,
    pub hash_loop: Option<usize>,
}
/// BloomFilter
pub struct BloomFilter {
    size: usize,
    hash_loop: usize,
    bitmap: RwLock<Box<Vec<u8>>>,
}

impl BloomFilter {
    /// create bloomfilter
    /// # example
    /// ```
    /// use bloom_filter::*;
    ///
    /// fn main() {
    ///     let mut filter = BloomFilter::new(BloomConfig {
    ///         size: Some(DEFAULT_SIZE),
    ///         hash_loop: Some(20),
    ///     });
    ///     filter.insert("key");
    ///     println!("{}", filter.contains("key"));
    ///     println!("{}", filter.contains("key1"));
    /// }
    ///
    /// ```
    pub fn new(c: BloomConfig) -> Self {
        let size = match c.size {
            Some(size) => {
                if size <= 0 {
                    DEFAULT_SIZE
                } else {
                    size
                }
            }
            None => DEFAULT_SIZE,
        };
        let hash_loop = match c.hash_loop {
            Some(hash_loop) => {
                if size <= 0 {
                    DEFAULT_HASH_LOOP
                } else {
                    hash_loop
                }
            }
            None => DEFAULT_HASH_LOOP,
        };
        let bitmap: Vec<u8> = vec![0; size];
        Self {
            size: size,
            hash_loop: hash_loop,
            bitmap: RwLock::new(Box::new(bitmap)),
        }
    }

    /// add key to bloomfilter
    /// # example
    /// ```
    /// use bloom_filter::*;
    ///
    /// fn main() {
    ///     let mut filter = BloomFilter::new(BloomConfig {
    ///         size: Some(DEFAULT_SIZE),
    ///         hash_loop: Some(20),
    ///     });
    ///     filter.insert("key");
    ///     println!("{}", filter.contains("key"));
    ///     println!("{}", filter.contains("key1"));
    /// }
    ///
    /// ```
    pub fn insert(&mut self, key: &str) {
        let indexs = self.hash(key);
        self.insert_bitmap(indexs);
    }


    /// Check whether the bloomfilter has key
    /// # example
    /// ```
    /// use bloom_filter::*;
    ///
    /// fn main() {
    ///     let mut filter = BloomFilter::new(BloomConfig {
    ///         size: Some(DEFAULT_SIZE),
    ///         hash_loop: Some(20),
    ///     });
    ///     filter.insert("key");
    ///     println!("{}", filter.contains("key"));
    ///     println!("{}", filter.contains("key1"));
    /// }
    ///
    /// ```
    pub fn contains(&self, key: &str) -> bool {
        let indexs = self.hash(key);
        self.contains_bitmap(indexs)
    }
    /// Binary print bitmap
    /// # example
    /// ```
    /// use bloom_filter::*;
    ///
    /// fn main() {
    ///     let mut filter = BloomFilter::new(BloomConfig {
    ///         size: Some(DEFAULT_SIZE),
    ///         hash_loop: Some(20),
    ///     });
    ///     filter.debug();
    ///     filter.insert("key");
    ///     filter.debug();
    /// }
    ///
    /// ```
    pub fn debug(&self) {
        match self.bitmap.read() {
            Ok(bitmap) => {
                for (index, _) in bitmap.iter().enumerate() {
                    print!("{:0>8}", format!("{:02b}", bitmap[index]));
                }
            }
            Err(_) => {}
        };
    }

    fn insert_bitmap(&mut self, indexs: Vec<usize>) {
        match self.bitmap.get_mut() {
            Ok(bitmap) => {
                for index in indexs {
                    //let m = 1 << (indexs[*index] % 8);
                    bitmap[index] |= 1 << (index % 8);
                }
            }
            Err(_) => {}
        };
    }

    fn contains_bitmap(&self, indexs: Vec<usize>) -> bool {
        match self.bitmap.read() {
            Ok(bitmap) => {
                for index in indexs {
                    //let m = 1 << (indexs[*index] % 8);
                    //bitmap[index] |= 1 << (index % 8);
                    // if b.data[indexs[i]]&(1<<(indexs[i]%8)) != byte(match) {
                    //     return false
                    // }
                    if bitmap[index] & (1 << (index % 8)) != 1 << (index % 8) {
                        return false;
                    }
                }
            }
            Err(_) => {}
        };
        true
    }

    fn hash(&self, key: &str) -> Vec<usize> {
        let mut result: Vec<usize> = vec![0];
        let mut hasher1 = DefaultHasher::new();
        for i in 0..self.hash_loop {
            hasher1.write(key.as_bytes());
            hasher1.write_usize(i);
            result.push(hasher1.finish() as usize % self.size);
        }
        result
    }
}