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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
extern crate bit_vec;
extern crate rand;
extern crate siphasher;
use std::error::Error;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use bit_vec::BitVec;
use siphasher::sip::SipHasher24;
#[derive(Debug)]
pub enum BloomError {
NoParameterSet,
}
impl fmt::Display for BloomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BloomError::NoParameterSet => {
write!(f,
"Must set either the desired size or false positive ratio to create a \
bloom filter")
}
}
}
}
impl Error for BloomError {
fn description(&self) -> &str {
match *self {
BloomError::NoParameterSet => {
"Must set either the desired size or false positive ratio to create a \
bloom filter"
}
}
}
}
#[derive(Debug)]
enum BloomParameter {
Empty,
Size(u64),
FPR(f64),
}
#[derive(Debug)]
pub struct BloomBuilder {
elements: u64,
parameter: BloomParameter,
}
impl BloomBuilder {
pub fn new(elements: u64) -> BloomBuilder {
BloomBuilder {
elements: elements,
parameter: BloomParameter::Empty,
}
}
pub fn with_size(mut self, size: u64) -> BloomBuilder {
self.parameter = BloomParameter::Size(size);
self
}
pub fn with_fpr(mut self, p: f64) -> BloomBuilder {
self.parameter = BloomParameter::FPR(p);
self
}
pub fn finish<T>(&self) -> Result<Bloom<T>, BloomError>
where T: Hash
{
match self.parameter {
BloomParameter::Empty => Err(BloomError::NoParameterSet),
BloomParameter::Size(size) => {
let hash_count = BloomBuilder::optimal_hash_count(self.elements, size);
let bloom = Bloom::new(size, hash_count);
Ok(bloom)
}
BloomParameter::FPR(p) => {
let min_size = BloomBuilder::min_size(self.elements, p);
let hash_count = BloomBuilder::optimal_hash_count(self.elements, min_size);
let bloom: Bloom<T> = Bloom::new(min_size, hash_count);
Ok(bloom)
}
}
}
fn min_size(num_elements: u64, p: f64) -> u64 {
let n = num_elements as f64;
let m = -1f64 * n * p.ln() / (2f64.ln().powf(2f64));
m.ceil() as u64
}
fn optimal_hash_count(num_elements: u64, num_bits: u64) -> u32 {
let m = num_bits as f64;
let n = num_elements as f64;
let k = 2f64.ln() * m / n;
k.ceil() as u32
}
}
#[derive(Debug)]
pub struct Bloom<T: Hash> {
bits: BitVec,
k: u32,
hashers: [SipHasher24; 2],
marker: PhantomData<T>,
}
impl<T: Hash> Bloom<T> {
fn new(size: u64, k: u32) -> Self {
Bloom {
bits: BitVec::from_elem(size as usize, false),
k: k,
hashers: [Bloom::<T>::get_hasher(), Bloom::<T>::get_hasher()],
marker: PhantomData,
}
}
fn get_hasher() -> SipHasher24 {
let mut rng = rand::thread_rng();
SipHasher24::new_with_keys(rand::Rand::rand(&mut rng), rand::Rand::rand(&mut rng))
}
pub fn insert(&mut self, key: T) {
let mut hashes = [0u64, 0u64];
for i in 0..self.k {
let index = self.get_hash(&mut hashes, &key, i) % self.bits.len();
self.bits.set(index, true);
}
}
pub fn lookup(&self, item: T) -> bool {
let mut hashes = [0u64, 0u64];
for i in 0..self.k {
let index = self.get_hash(&mut hashes, &item, i) % self.bits.len();
if !self.bits[index] {
return false;
}
}
true
}
pub fn lookup_and_insert(&mut self, key: T) -> bool {
let mut hashes = [0u64, 0u64];
let mut found = true;
for i in 0..self.k {
let index = self.get_hash(&mut hashes, &key, i) % self.bits.len();
if !self.bits[index] {
found = false;
self.bits.set(index, true);
}
}
found
}
fn get_hash(&self, hashes: &mut [u64; 2], key: &T, i: u32) -> usize {
if i < 2 {
let hasher = &mut self.hashers[i as usize].clone();
key.hash(hasher);
let hash = hasher.finish();
hashes[i as usize] = hash;
hash as usize
} else {
hashes[0]
.wrapping_add((i as u64).wrapping_mul(hashes[1]) %
self.bits.len() as u64) as usize
}
}
}
#[cfg(test)]
mod tests {
use super::BloomBuilder;
#[test]
fn test_with_size() {
let size = 2u64.pow(20);
let b = BloomBuilder::new(size / 2).with_size(size).finish::<i64>().unwrap();
assert_eq!(b.bits.len() as u64, size);
assert_eq!(b.k, 2);
}
#[test]
fn test_with_fpr() {
let elements = 2u64.pow(20);
let fpr = 0.01;
let b = BloomBuilder::new(elements).with_fpr(fpr).finish::<i64>().unwrap();
println!("{:?}", b.bits.len());
assert_eq!(b.k, 7);
}
#[test]
fn test_operations() {
let elements = 2u64.pow(20);
let fpr = 0.01;
let mut b = BloomBuilder::new(elements).with_fpr(fpr).finish::<i64>().unwrap();
assert!(!b.lookup(3));
assert!(!b.lookup(23));
assert!(!b.lookup(51));
b.insert(3);
b.insert(23);
b.insert(51);
assert!(b.lookup(3));
assert!(b.lookup(23));
assert!(b.lookup(51));
assert!(b.lookup_and_insert(3));
assert!(b.lookup_and_insert(23));
assert!(b.lookup_and_insert(51));
}
}