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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use std::collections::hash_map::DefaultHasher;
use std::error::Error;
use std::fmt;
use std::fs::OpenOptions;
use std::hash::Hasher;
use std::io::{Read, Write};
use std::path::Path;
use std::sync::RwLock;
#[derive(Debug)]
struct FilterError(String);
impl fmt::Display for FilterError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "filter error: {}", self.0)
}
}
pub const DEFAULT_SIZE: usize = 1 << 10;
pub const DEFAULT_HASH_LOOP: usize = 10;
pub struct BloomFilter {
size: usize,
hash_loop: usize,
is_null: bool,
bitmap: RwLock<Box<Vec<u8>>>,
}
impl BloomFilter {
pub fn new() -> Self {
let bitmap: Vec<u8> = vec![0; DEFAULT_SIZE];
Self {
size: DEFAULT_SIZE,
hash_loop: DEFAULT_HASH_LOOP,
is_null: true,
bitmap: RwLock::new(Box::new(bitmap)),
}
}
pub fn set_size(mut self, size: usize) -> Self {
if self.is_null {
self.size = size;
self.bitmap = RwLock::new(Box::new(vec![0; size]));
} else {
println!(
"{}",
"The modification is invalid because the bitmap already has data"
);
}
self
}
pub fn set_hash_loop(mut self, hash_loop: usize) -> Self {
if self.is_null {
self.hash_loop = hash_loop;
} else {
println!(
"{}",
"The modification is invalid because the bitmap already has data"
);
}
self
}
pub fn load_file<P: AsRef<Path>>(mut self, filename: P) -> Result<Self, Box<dyn Error>> {
if !self.is_null {
FilterError("filter not null".into());
}
let mut load_file = OpenOptions::new().read(true).create(false).open(filename)?;
let mut data: Vec<u8> = Vec::new();
load_file.read_to_end(&mut data)?;
if data.len() >= 8 {
let loops = data[data.len() - 8..].as_ptr();
let loops = loops as *const usize;
let loops = unsafe { *loops };
self.size = data.len() - 8;
self.hash_loop = loops;
self.bitmap = RwLock::new(Box::new(data[..data.len() - 8].to_vec()));
} else {
FilterError("file error".into());
}
Ok(self)
}
pub fn save_to_file<P: AsRef<Path>>(self, filename: P) -> Result<(), Box<dyn Error>> {
let mut load_file = OpenOptions::new()
.write(true)
.create(false)
.open(filename)?;
match self.bitmap.read() {
Ok(bitmap) => {
let mut loops = self.hash_loop.to_ne_bytes().to_vec();
let mut bitmap_tmp = bitmap.clone();
bitmap_tmp.append(&mut loops);
load_file.write_all(bitmap_tmp.as_slice())?;
}
Err(_) => {
FilterError("get bitmap err".into());
}
}
Ok(())
}
pub fn insert(&mut self, key: &str) {
self.is_null = false;
let indexs = self.hash(key);
self.insert_bitmap(indexs);
}
pub fn contains(&self, key: &str) -> bool {
let indexs = self.hash(key);
self.contains_bitmap(indexs)
}
pub fn debug(&self) {
match self.bitmap.read() {
Ok(bitmap) => {
for (index, _) in bitmap.iter().enumerate() {
print!("{:0>8}", format!("{:02b}", bitmap[index]));
}
}
Err(_) => {}
};
}
pub fn clear(&mut self) {
self.bitmap = RwLock::new(Box::new(vec![0; self.size]));
self.is_null = true;
}
fn insert_bitmap(&mut self, indexs: Vec<usize>) {
match self.bitmap.get_mut() {
Ok(bitmap) => {
for index in indexs {
bitmap[index] |= 1 << (index % 8);
}
}
Err(_) => {}
};
}
fn contains_bitmap(&self, indexs: Vec<usize>) -> bool {
match self.bitmap.read() {
Ok(bitmap) => {
for index in indexs {
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
}
}