Skip to content

Commit 382ae2f

Browse files
committed
Add associated functions/methods for exposing/loading bitmap data in BloomFilter
1 parent 30ebb82 commit 382ae2f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/filters/bloomfilter.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,20 @@ where
179179
Self::with_params_and_hash(m, k, bh)
180180
}
181181

182+
/// Create BloomFilter with internal parameters and existing bitmap.
183+
///
184+
/// - `k` is the number of hash functions
185+
/// - `m` is the number of bits used to store state
186+
/// - `bitmap` is the bitmap from an existing bloom filter
187+
pub fn with_params_and_bitmap<I: IntoIterator<Item = u32>>(
188+
m: usize,
189+
k: usize,
190+
bitmap: I,
191+
) -> Self {
192+
let bh = BuildHasherDefault::<DefaultHasher>::default();
193+
Self::with_params_and_hash_and_bitmap(m, k, bh, bitmap)
194+
}
195+
182196
/// Create new, empty BloomFilter with given properties.
183197
///
184198
/// - `n` number of unique elements the BloomFilter is expected to hold, must be `> 0`
@@ -207,6 +221,21 @@ where
207221
}
208222
}
209223

224+
/// Same as `with_params_and_bitmap` but with specific `BuildHasher`.
225+
pub fn with_params_and_hash_and_bitmap<I: IntoIterator<Item = u32>>(
226+
m: usize,
227+
k: usize,
228+
buildhasher: B,
229+
bitmap: I,
230+
) -> Self {
231+
Self {
232+
bs: FixedBitSet::with_capacity_and_blocks(m, bitmap),
233+
k,
234+
builder: HashIterBuilder::new(m, k, buildhasher),
235+
phantom: PhantomData,
236+
}
237+
}
238+
210239
/// Same as `with_properties` but with specific `BuildHasher`.
211240
pub fn with_properties_and_hash(n: usize, p: f64, buildhasher: B) -> Self {
212241
assert!(n > 0, "n must be greater than 0");
@@ -237,6 +266,11 @@ where
237266
pub fn buildhasher(&self) -> &B {
238267
self.builder.buildhasher()
239268
}
269+
270+
/// Get bitmap data.
271+
pub fn bitmap(&self) -> &[u32] {
272+
self.bs.as_slice()
273+
}
240274
}
241275

242276
impl<T, B> Filter<T> for BloomFilter<T, B>
@@ -529,4 +563,22 @@ mod tests {
529563
let bf = BloomFilter::<NotSend>::with_params(100, 2);
530564
assert_send(&bf);
531565
}
566+
567+
#[test]
568+
fn bitmap_save_load() {
569+
let mut bf = BloomFilter::with_params(100, 2);
570+
571+
assert!(bf.insert(&1).unwrap());
572+
assert!(bf.insert(&7).unwrap());
573+
assert!(bf.insert(&52).unwrap());
574+
575+
let bitmap = bf.bitmap().to_vec();
576+
577+
let loaded_bf = BloomFilter::with_params_and_bitmap(100, 2, bitmap);
578+
579+
assert!(loaded_bf.query(&1));
580+
assert!(loaded_bf.query(&7));
581+
assert!(loaded_bf.query(&52));
582+
assert!(!loaded_bf.query(&15));
583+
}
532584
}

0 commit comments

Comments
 (0)