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 u128).wrapping_mul(blocks.len() as u128)) >> 64) as usize;
60        let block: &mut BloomBlock = unsafe { blocks.get_unchecked_mut(block_idx) };
61        let step: u64 = h1.rotate_left(17) | 1;
62        let mut changed: bool = false;
63        let mut probe: u64 = h2;
64        for _ in 0..*hash_count {
65            let bit: usize = (probe as usize) & (BLOCK_BITS - 1);
66            let word: &mut u64 = unsafe { block.words.get_unchecked_mut(bit >> 6) };
67            let mask: u64 = 1u64 << (bit & 63);
68            let prev: u64 = *word;
69            *word = prev | mask;
70            changed |= (prev & mask) == 0;
71            probe = probe.wrapping_add(step);
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 u128).wrapping_mul(blocks.len() as u128)) >> 64) as usize;
90        let block: &BloomBlock = unsafe { blocks.get_unchecked(block_idx) };
91        let step: u64 = h1.rotate_left(17) | 1;
92        let mut probe: u64 = h2;
93        for _ in 0..*hash_count {
94            let bit: usize = (probe as usize) & (BLOCK_BITS - 1);
95            let word: u64 = unsafe { *block.words.get_unchecked(bit >> 6) };
96            let mask: u64 = 1u64 << (bit & 63);
97            if (word & mask) == 0 {
98                return false;
99            }
100            probe = probe.wrapping_add(step);
101        }
102        true
103    }
104
105    /// Clears all bits to zero while keeping allocated capacity.
106    pub fn clear(&mut self) {
107        let Self { blocks, .. } = self;
108        for block in blocks.iter_mut() {
109            block.words = [0u64; BLOCK_WORDS];
110        }
111    }
112
113    /// Returns total bit capacity (`block_count * 512`).
114    ///
115    /// # Returns
116    ///
117    /// - `usize` - Total bits stored.
118    #[inline(always)]
119    pub fn bit_len(&self) -> usize {
120        let Self { blocks, .. } = self;
121        blocks.len() * BLOCK_BITS
122    }
123
124    /// Returns the number of configured hash probes per element.
125    ///
126    /// # Returns
127    ///
128    /// - `u32` - Probe count `k`.
129    #[inline(always)]
130    pub fn hash_count(&self) -> u32 {
131        let Self { hash_count, .. } = self;
132        *hash_count
133    }
134
135    /// Counts total set bits across all blocks.
136    ///
137    /// # Returns
138    ///
139    /// - `usize` - Number of `1` bits currently set.
140    pub fn count_ones(&self) -> usize {
141        let Self { blocks, .. } = self;
142        let mut ones: usize = 0;
143        for block in blocks {
144            for &word in &block.words {
145                ones += word.count_ones() as usize;
146            }
147        }
148        ones
149    }
150
151    /// Estimates the number of distinct inserted elements from bit density.
152    ///
153    /// # Returns
154    ///
155    /// - `f64` - Estimated cardinality.
156    pub fn estimated_count(&self) -> f64 {
157        let m: f64 = self.bit_len() as f64;
158        let x: f64 = self.count_ones() as f64;
159        if x == 0.0 || x >= m {
160            return x;
161        }
162        let k: f64 = f64::from(self.hash_count());
163        -(m / k) * (1.0 - x / m).ln()
164    }
165
166    /// Computes bitwise union (`self |= other`) when dimensions and hash counts match.
167    ///
168    /// # Arguments
169    ///
170    /// - `&Self` - Other filter with identical dimensions.
171    ///
172    /// # Returns
173    ///
174    /// - `bool` - `true` if merged, `false` if dimensions or hash counts differed.
175    pub fn union_with(&mut self, other: &Self) -> bool {
176        let Self { blocks, hash_count } = self;
177        let Self {
178            blocks: other_blocks,
179            hash_count: other_k,
180        } = other;
181        if blocks.len() != other_blocks.len() || *hash_count != *other_k {
182            return false;
183        }
184        for (dst, src) in blocks.iter_mut().zip(other_blocks.iter()) {
185            for (d, s) in dst.words.iter_mut().zip(src.words.iter()) {
186                *d |= *s;
187            }
188        }
189        true
190    }
191}