Skip to main content

bloom_bitset/blocked/
impl.rs

1use super::*;
2
3/// Core operations for [`BlockedBloomFilter`].
4impl BlockedBloomFilter {
5    /// Constructs an optimally sized [`BlockedBloomFilter`] for `expected_items` and target `false_positive_rate`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Expected number of distinct elements to insert (`>= 1`).
10    /// - `f64` - Target false positive probability in `(0.0, 1.0)` (clamped to `[1e-9, 0.5]`).
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Sized cache-line-blocked Bloom filter.
15    pub fn with_rate(expected_items: usize, false_positive_rate: f64) -> Self {
16        let items: f64 = (expected_items.max(1)) as f64;
17        let fpr: f64 = false_positive_rate.clamp(1e-9, 0.5);
18        let ln2_sq: f64 = LN_2 * LN_2;
19        let bits: f64 = (-items * fpr.ln() / ln2_sq).ceil();
20        let block_count: usize =
21            ((bits as usize).saturating_add(BLOCK_BITS - 1) / BLOCK_BITS).max(1);
22        let actual_bits: f64 = (block_count * BLOCK_BITS) as f64;
23        let k: u32 = ((actual_bits / items) * LN_2).round().clamp(1.0, 16.0) as u32;
24        Self::with_blocks(block_count, k)
25    }
26
27    /// Constructs a [`BlockedBloomFilter`] with explicit `block_count` and per-block probe count `hash_count`.
28    ///
29    /// # Arguments
30    ///
31    /// - `usize` - Number of 512-bit cache-line blocks (`>= 1`).
32    /// - `u32` - Number of bit probes per element (`1..=16`).
33    ///
34    /// # Returns
35    ///
36    /// - `Self` - Fresh empty blocked Bloom filter.
37    pub fn with_blocks(block_count: usize, hash_count: u32) -> Self {
38        let count: usize = block_count.max(1);
39        let k: u32 = hash_count.clamp(1, 16);
40        Self {
41            blocks: vec![BloomBlock::default(); count],
42            hash_count: k,
43        }
44    }
45
46    /// Inserts `item` into the filter and returns `true` if at least one bit changed from `0` to `1`.
47    ///
48    /// # Arguments
49    ///
50    /// - `&[u8]` - Element bytes to insert.
51    ///
52    /// # Returns
53    ///
54    /// - `bool` - `true` when `item` was definitely not previously present.
55    #[inline]
56    pub fn insert(&mut self, item: &[u8]) -> bool {
57        let (h1, h2): (u64, u64) = hash_pair(item);
58        let Self { blocks, hash_count } = self;
59        let block_idx: usize = (h1 as usize) % blocks.len();
60        let block: &mut BloomBlock = &mut blocks[block_idx];
61        let mut changed: bool = false;
62        let mut probe: u64 = h2;
63        for _ in 0..*hash_count {
64            let bit: usize = (probe as usize) & (BLOCK_BITS - 1);
65            let word_idx: usize = bit >> 6;
66            let mask: u64 = 1u64 << (bit & 63);
67            if (block.words[word_idx] & mask) == 0 {
68                block.words[word_idx] |= mask;
69                changed = true;
70            }
71            probe = probe.wrapping_add(h1.rotate_left(17) | 1);
72        }
73        changed
74    }
75
76    /// Tests whether `item` may be present in the filter (zero false negatives).
77    ///
78    /// # Arguments
79    ///
80    /// - `&[u8]` - Element bytes to query.
81    ///
82    /// # Returns
83    ///
84    /// - `bool` - `false` if definitely absent, `true` if probably present.
85    #[inline]
86    pub fn contains(&self, item: &[u8]) -> bool {
87        let (h1, h2): (u64, u64) = hash_pair(item);
88        let Self { blocks, hash_count } = self;
89        let block_idx: usize = (h1 as usize) % blocks.len();
90        let block: &BloomBlock = &blocks[block_idx];
91        let mut probe: u64 = h2;
92        for _ in 0..*hash_count {
93            let bit: usize = (probe as usize) & (BLOCK_BITS - 1);
94            let word_idx: usize = bit >> 6;
95            let mask: u64 = 1u64 << (bit & 63);
96            if (block.words[word_idx] & mask) == 0 {
97                return false;
98            }
99            probe = probe.wrapping_add(h1.rotate_left(17) | 1);
100        }
101        true
102    }
103
104    /// Clears all bits to zero while keeping allocated capacity.
105    pub fn clear(&mut self) {
106        let Self { blocks, .. } = self;
107        for block in blocks.iter_mut() {
108            block.words = [0u64; BLOCK_WORDS];
109        }
110    }
111
112    /// Returns total bit capacity (`block_count * 512`).
113    ///
114    /// # Returns
115    ///
116    /// - `usize` - Total bits stored.
117    #[inline(always)]
118    pub fn bit_len(&self) -> usize {
119        let Self { blocks, .. } = self;
120        blocks.len() * BLOCK_BITS
121    }
122
123    /// Returns the number of configured hash probes per element.
124    ///
125    /// # Returns
126    ///
127    /// - `u32` - Probe count `k`.
128    #[inline(always)]
129    pub fn hash_count(&self) -> u32 {
130        let Self { hash_count, .. } = self;
131        *hash_count
132    }
133
134    /// Counts total set bits across all blocks.
135    ///
136    /// # Returns
137    ///
138    /// - `usize` - Number of `1` bits currently set.
139    pub fn count_ones(&self) -> usize {
140        let Self { blocks, .. } = self;
141        let mut ones: usize = 0;
142        for block in blocks {
143            for &word in &block.words {
144                ones += word.count_ones() as usize;
145            }
146        }
147        ones
148    }
149
150    /// Estimates the number of distinct inserted elements from bit density.
151    ///
152    /// # Returns
153    ///
154    /// - `f64` - Estimated cardinality.
155    pub fn estimated_count(&self) -> f64 {
156        let m: f64 = self.bit_len() as f64;
157        let x: f64 = self.count_ones() as f64;
158        if x == 0.0 || x >= m {
159            return x;
160        }
161        let k: f64 = f64::from(self.hash_count());
162        -(m / k) * (1.0 - x / m).ln()
163    }
164
165    /// Computes bitwise union (`self |= other`) when dimensions and hash counts match.
166    ///
167    /// # Arguments
168    ///
169    /// - `&Self` - Other filter with identical dimensions.
170    ///
171    /// # Returns
172    ///
173    /// - `bool` - `true` if merged, `false` if dimensions or hash counts differed.
174    pub fn union_with(&mut self, other: &Self) -> bool {
175        let Self { blocks, hash_count } = self;
176        let Self {
177            blocks: other_blocks,
178            hash_count: other_k,
179        } = other;
180        if blocks.len() != other_blocks.len() || *hash_count != *other_k {
181            return false;
182        }
183        for (dst, src) in blocks.iter_mut().zip(other_blocks.iter()) {
184            for (d, s) in dst.words.iter_mut().zip(src.words.iter()) {
185                *d |= *s;
186            }
187        }
188        true
189    }
190}