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 operations for [`BlockedBloomFilter`].
impl BlockedBloomFilter {
    /// Constructs an optimally sized [`BlockedBloomFilter`] for `expected_items` and target `false_positive_rate`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Expected number of distinct elements to insert (`>= 1`).
    /// - `f64` - Target false positive probability in `(0.0, 1.0)` (clamped to `[1e-9, 0.5]`).
    ///
    /// # Returns
    ///
    /// - `Self` - Sized cache-line-blocked 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 bits: f64 = (-items * fpr.ln() / ln2_sq).ceil();
        let block_count: usize =
            ((bits as usize).saturating_add(BLOCK_BITS - 1) / BLOCK_BITS).max(1);
        let actual_bits: f64 = (block_count * BLOCK_BITS) as f64;
        let k: u32 = ((actual_bits / items) * LN_2).round().clamp(1.0, 16.0) as u32;
        Self::with_blocks(block_count, k)
    }

    /// Constructs a [`BlockedBloomFilter`] with explicit `block_count` and per-block probe count `hash_count`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of 512-bit cache-line blocks (`>= 1`).
    /// - `u32` - Number of bit probes per element (`1..=16`).
    ///
    /// # Returns
    ///
    /// - `Self` - Fresh empty blocked Bloom filter.
    pub fn with_blocks(block_count: usize, hash_count: u32) -> Self {
        let count: usize = block_count.max(1);
        let k: u32 = hash_count.clamp(1, 16);
        Self {
            blocks: vec![BloomBlock::default(); count],
            hash_count: k,
        }
    }

    /// Inserts `item` into the filter and returns `true` if at least one bit changed from `0` to `1`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Element bytes to insert.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `item` was definitely not previously present.
    #[inline]
    pub fn insert(&mut self, item: &[u8]) -> bool {
        let (h1, h2): (u64, u64) = hash_pair(item);
        let Self { blocks, hash_count } = self;
        let block_idx: usize = (h1 as usize) % blocks.len();
        let block: &mut BloomBlock = &mut blocks[block_idx];
        let mut changed: bool = false;
        let mut probe: u64 = h2;
        for _ in 0..*hash_count {
            let bit: usize = (probe as usize) & (BLOCK_BITS - 1);
            let word_idx: usize = bit >> 6;
            let mask: u64 = 1u64 << (bit & 63);
            if (block.words[word_idx] & mask) == 0 {
                block.words[word_idx] |= mask;
                changed = true;
            }
            probe = probe.wrapping_add(h1.rotate_left(17) | 1);
        }
        changed
    }

    /// Tests whether `item` may be present in the filter (zero false negatives).
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Element bytes to query.
    ///
    /// # Returns
    ///
    /// - `bool` - `false` if definitely absent, `true` if probably present.
    #[inline]
    pub fn contains(&self, item: &[u8]) -> bool {
        let (h1, h2): (u64, u64) = hash_pair(item);
        let Self { blocks, hash_count } = self;
        let block_idx: usize = (h1 as usize) % blocks.len();
        let block: &BloomBlock = &blocks[block_idx];
        let mut probe: u64 = h2;
        for _ in 0..*hash_count {
            let bit: usize = (probe as usize) & (BLOCK_BITS - 1);
            let word_idx: usize = bit >> 6;
            let mask: u64 = 1u64 << (bit & 63);
            if (block.words[word_idx] & mask) == 0 {
                return false;
            }
            probe = probe.wrapping_add(h1.rotate_left(17) | 1);
        }
        true
    }

    /// Clears all bits to zero while keeping allocated capacity.
    pub fn clear(&mut self) {
        let Self { blocks, .. } = self;
        for block in blocks.iter_mut() {
            block.words = [0u64; BLOCK_WORDS];
        }
    }

    /// Returns total bit capacity (`block_count * 512`).
    ///
    /// # Returns
    ///
    /// - `usize` - Total bits stored.
    #[inline(always)]
    pub fn bit_len(&self) -> usize {
        let Self { blocks, .. } = self;
        blocks.len() * BLOCK_BITS
    }

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

    /// Counts total set bits across all blocks.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of `1` bits currently set.
    pub fn count_ones(&self) -> usize {
        let Self { blocks, .. } = self;
        let mut ones: usize = 0;
        for block in blocks {
            for &word in &block.words {
                ones += word.count_ones() as usize;
            }
        }
        ones
    }

    /// Estimates the number of distinct inserted elements from bit density.
    ///
    /// # Returns
    ///
    /// - `f64` - Estimated cardinality.
    pub fn estimated_count(&self) -> f64 {
        let m: f64 = self.bit_len() as f64;
        let x: f64 = self.count_ones() as f64;
        if x == 0.0 || x >= m {
            return x;
        }
        let k: f64 = f64::from(self.hash_count());
        -(m / k) * (1.0 - x / m).ln()
    }

    /// Computes bitwise union (`self |= other`) when dimensions and hash counts match.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Other filter with identical dimensions.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if merged, `false` if dimensions or hash counts differed.
    pub fn union_with(&mut self, other: &Self) -> bool {
        let Self { blocks, hash_count } = self;
        let Self {
            blocks: other_blocks,
            hash_count: other_k,
        } = other;
        if blocks.len() != other_blocks.len() || *hash_count != *other_k {
            return false;
        }
        for (dst, src) in blocks.iter_mut().zip(other_blocks.iter()) {
            for (d, s) in dst.words.iter_mut().zip(src.words.iter()) {
                *d |= *s;
            }
        }
        true
    }
}