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 = nibbles[slot >> 1];
if (slot & 1) == 0 {
byte & MAX_NIBBLE
} else {
byte >> 4
}
}
#[inline(always)]
fn set_counter(&mut self, slot: usize, val: u8) {
let Self { nibbles, .. } = self;
let clamped: u8 = val & MAX_NIBBLE;
let byte: &mut u8 = &mut nibbles[slot >> 1];
if (slot & 1) == 0 {
*byte = (*byte & 0xf0) | clamped;
} else {
*byte = (*byte & MAX_NIBBLE) | (clamped << 4);
}
}
pub fn insert(&mut self, item: &[u8]) {
let (h1, h2): (u64, u64) = hash_pair(item);
let slots: usize = self.slot_len();
let k: u32 = self.hash_count();
for i in 0..k {
let idx: usize = (h1.wrapping_add(u64::from(i).wrapping_mul(h2)) as usize) % slots;
let cur: u8 = self.get_counter(idx);
if cur < MAX_NIBBLE {
self.set_counter(idx, cur + 1);
}
}
}
pub fn remove(&mut self, item: &[u8]) -> bool {
if !self.contains(item) {
return false;
}
let (h1, h2): (u64, u64) = hash_pair(item);
let slots: usize = self.slot_len();
let k: u32 = self.hash_count();
for i in 0..k {
let idx: usize = (h1.wrapping_add(u64::from(i).wrapping_mul(h2)) as usize) % slots;
let cur: u8 = self.get_counter(idx);
if cur > 0 && cur < MAX_NIBBLE {
self.set_counter(idx, cur - 1);
}
}
true
}
pub fn contains(&self, item: &[u8]) -> bool {
let (h1, h2): (u64, u64) = hash_pair(item);
let slots: usize = self.slot_len();
let k: u32 = self.hash_count();
for i in 0..k {
let idx: usize = (h1.wrapping_add(u64::from(i).wrapping_mul(h2)) as usize) % slots;
if self.get_counter(idx) == 0 {
return false;
}
}
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
}
}