bloom-bitset 11.1.0

Zero-dependency probabilistic data structures: 512-bit cache-line-blocked Bloom filter, 4-bit saturating Counting Bloom filter, and HyperLogLog cardinality estimator.
Documentation
use super::*;

/// Core insertion, deletion, and membership methods for [`CountingBloomFilter`].
impl CountingBloomFilter {
    /// Constructs a [`CountingBloomFilter`] sized for `expected_items` and target `false_positive_rate`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Expected number of active elements (`>= 1`).
    /// - `f64` - Target false positive probability in `(0.0, 1.0)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Sized 4-bit counting Bloom filter.
    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)
    }

    /// Constructs a [`CountingBloomFilter`] with explicit `slot_count` and `hash_count`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Total 4-bit counter slots (`>= 2`).
    /// - `u32` - Number of probes per element (`1..=16`).
    ///
    /// # Returns
    ///
    /// - `Self` - Empty counting Bloom filter.
    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),
        }
    }

    /// Reads the 4-bit counter at `slot`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Counter index in `0..slot_count`.
    ///
    /// # Returns
    ///
    /// - `u8` - Counter value in `0..=15`.
    #[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
        }
    }

    /// Writes a 4-bit counter `val` (`0..=15`) into `slot`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Counter index in `0..slot_count`.
    /// - `u8` - New 4-bit value (`0..=15`).
    #[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);
        }
    }

    /// Inserts `item`, saturating any counter that reaches `15` to prevent overflow wrap.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Element bytes to insert.
    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);
            }
        }
    }

    /// Removes one occurrence of `item` when all its counters are non-zero.
    ///
    /// Saturated counters (`15`) remain saturated to avoid introducing false negatives.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Element bytes to remove.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the item appeared present and counters were decremented.
    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
    }

    /// Tests whether `item` may be present in the counting Bloom filter.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Element bytes to query.
    ///
    /// # Returns
    ///
    /// - `bool` - `false` if definitely absent, `true` if probably present.
    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
    }

    /// Resets all counters to zero.
    pub fn clear(&mut self) {
        let Self { nibbles, .. } = self;
        nibbles.fill(0);
    }

    /// Returns total number of 4-bit counter slots.
    ///
    /// # Returns
    ///
    /// - `usize` - Counter slot count.
    #[inline(always)]
    pub fn slot_len(&self) -> usize {
        let Self { slot_count, .. } = self;
        *slot_count
    }

    /// Returns configured hash probe count.
    ///
    /// # Returns
    ///
    /// - `u32` - Probe count `k`.
    #[inline(always)]
    pub fn hash_count(&self) -> u32 {
        let Self { hash_count, .. } = self;
        *hash_count
    }
}