use super::*;
impl CountingBloomFilter {
pub fn with_rate(expected_items: usize, false_positive_rate: f64) -> Self {
let items: f64 = (expected_items.max(1)) as f64;
let fpr: f64 = false_positive_rate.clamp(1e-9, 0.5);
let ln2_sq: f64 = LN_2 * LN_2;
let slots: usize = ((-items * fpr.ln() / ln2_sq).ceil() as usize).max(64);
let k: u32 = ((slots as f64 / items) * LN_2).round().clamp(1.0, 16.0) as u32;
Self::with_slots(slots, k)
}
pub fn with_slots(slot_count: usize, hash_count: u32) -> Self {
let slots: usize = slot_count.max(2);
let byte_len: usize = slots.div_ceil(2);
Self {
nibbles: vec![0u8; byte_len],
slot_count: slots,
hash_count: hash_count.clamp(1, 16),
}
}
#[inline(always)]
fn get_counter(&self, slot: usize) -> u8 {
let Self { nibbles, .. } = self;
let byte: u8 = unsafe { *nibbles.get_unchecked(slot >> 1) };
let shift: u32 = ((slot & 1) as u32) << 2;
(byte >> shift) & MAX_NIBBLE
}
#[inline(always)]
fn set_counter(&mut self, slot: usize, val: u8) {
let Self { nibbles, .. } = self;
let shift: u32 = ((slot & 1) as u32) << 2;
let byte: &mut u8 = unsafe { nibbles.get_unchecked_mut(slot >> 1) };
*byte = (*byte & !(MAX_NIBBLE << shift)) | ((val & MAX_NIBBLE) << shift);
}
#[inline]
pub fn insert(&mut self, item: &[u8]) {
let (h1, h2): (u64, u64) = hash_pair(item);
let slots: u128 = self.slot_len() as u128;
let k: u32 = self.hash_count();
let mut probe: u64 = h1;
for _ in 0..k {
let idx: usize = (((probe as u128).wrapping_mul(slots)) >> 64) as usize;
let cur: u8 = self.get_counter(idx);
if cur < MAX_NIBBLE {
self.set_counter(idx, cur + 1);
}
probe = probe.wrapping_add(h2);
}
}
#[inline]
pub fn remove(&mut self, item: &[u8]) -> bool {
let (h1, h2): (u64, u64) = hash_pair(item);
let slots: u128 = self.slot_len() as u128;
let k: usize = self.hash_count() as usize;
let mut cached_slots: [usize; 16] = [0usize; 16];
let mut probe: u64 = h1;
let mut i: usize = 0;
while i < k {
let idx: usize = (((probe as u128).wrapping_mul(slots)) >> 64) as usize;
if self.get_counter(idx) == 0 {
return false;
}
cached_slots[i] = idx;
probe = probe.wrapping_add(h2);
i += 1;
}
let mut j: usize = 0;
while j < k {
let idx: usize = cached_slots[j];
let cur: u8 = self.get_counter(idx);
if cur > 0 && cur < MAX_NIBBLE {
self.set_counter(idx, cur - 1);
}
j += 1;
}
true
}
#[inline]
pub fn contains(&self, item: &[u8]) -> bool {
let (h1, h2): (u64, u64) = hash_pair(item);
let slots: u128 = self.slot_len() as u128;
let k: u32 = self.hash_count();
let mut probe: u64 = h1;
for _ in 0..k {
let idx: usize = (((probe as u128).wrapping_mul(slots)) >> 64) as usize;
if self.get_counter(idx) == 0 {
return false;
}
probe = probe.wrapping_add(h2);
}
true
}
pub fn clear(&mut self) {
let Self { nibbles, .. } = self;
nibbles.fill(0);
}
#[inline(always)]
pub fn slot_len(&self) -> usize {
let Self { slot_count, .. } = self;
*slot_count
}
#[inline(always)]
pub fn hash_count(&self) -> u32 {
let Self { hash_count, .. } = self;
*hash_count
}
}