Skip to main content

bloom_bitset/counting/
impl.rs

1use super::*;
2
3/// Core insertion, deletion, and membership methods for [`CountingBloomFilter`].
4impl CountingBloomFilter {
5    /// Constructs a [`CountingBloomFilter`] sized for `expected_items` and target `false_positive_rate`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Expected number of active elements (`>= 1`).
10    /// - `f64` - Target false positive probability in `(0.0, 1.0)`.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Sized 4-bit counting 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 slots: usize = ((-items * fpr.ln() / ln2_sq).ceil() as usize).max(64);
20        let k: u32 = ((slots as f64 / items) * LN_2).round().clamp(1.0, 16.0) as u32;
21        Self::with_slots(slots, k)
22    }
23
24    /// Constructs a [`CountingBloomFilter`] with explicit `slot_count` and `hash_count`.
25    ///
26    /// # Arguments
27    ///
28    /// - `usize` - Total 4-bit counter slots (`>= 2`).
29    /// - `u32` - Number of probes per element (`1..=16`).
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Empty counting Bloom filter.
34    pub fn with_slots(slot_count: usize, hash_count: u32) -> Self {
35        let slots: usize = slot_count.max(2);
36        let byte_len: usize = slots.div_ceil(2);
37        Self {
38            nibbles: vec![0u8; byte_len],
39            slot_count: slots,
40            hash_count: hash_count.clamp(1, 16),
41        }
42    }
43
44    /// Reads the 4-bit counter at `slot`.
45    ///
46    /// # Arguments
47    ///
48    /// - `usize` - Counter index in `0..slot_count`.
49    ///
50    /// # Returns
51    ///
52    /// - `u8` - Counter value in `0..=15`.
53    #[inline(always)]
54    fn get_counter(&self, slot: usize) -> u8 {
55        let Self { nibbles, .. } = self;
56        let byte: u8 = unsafe { *nibbles.get_unchecked(slot >> 1) };
57        let shift: u32 = ((slot & 1) as u32) << 2;
58        (byte >> shift) & MAX_NIBBLE
59    }
60
61    /// Writes a 4-bit counter `val` (`0..=15`) into `slot`.
62    ///
63    /// # Arguments
64    ///
65    /// - `usize` - Counter index in `0..slot_count`.
66    /// - `u8` - New 4-bit value (`0..=15`).
67    #[inline(always)]
68    fn set_counter(&mut self, slot: usize, val: u8) {
69        let Self { nibbles, .. } = self;
70        let shift: u32 = ((slot & 1) as u32) << 2;
71        let byte: &mut u8 = unsafe { nibbles.get_unchecked_mut(slot >> 1) };
72        *byte = (*byte & !(MAX_NIBBLE << shift)) | ((val & MAX_NIBBLE) << shift);
73    }
74
75    /// Inserts `item`, saturating any counter that reaches `15` to prevent overflow wrap.
76    ///
77    /// # Arguments
78    ///
79    /// - `&[u8]` - Element bytes to insert.
80    #[inline]
81    pub fn insert(&mut self, item: &[u8]) {
82        let (h1, h2): (u64, u64) = hash_pair(item);
83        let slots: u128 = self.slot_len() as u128;
84        let k: u32 = self.hash_count();
85        let mut probe: u64 = h1;
86        for _ in 0..k {
87            let idx: usize = (((probe as u128).wrapping_mul(slots)) >> 64) as usize;
88            let cur: u8 = self.get_counter(idx);
89            if cur < MAX_NIBBLE {
90                self.set_counter(idx, cur + 1);
91            }
92            probe = probe.wrapping_add(h2);
93        }
94    }
95
96    /// Removes one occurrence of `item` when all its counters are non-zero.
97    ///
98    /// Saturated counters (`15`) remain saturated to avoid introducing false negatives.
99    ///
100    /// # Arguments
101    ///
102    /// - `&[u8]` - Element bytes to remove.
103    ///
104    /// # Returns
105    ///
106    /// - `bool` - `true` if the item appeared present and counters were decremented.
107    #[inline]
108    pub fn remove(&mut self, item: &[u8]) -> bool {
109        let (h1, h2): (u64, u64) = hash_pair(item);
110        let slots: u128 = self.slot_len() as u128;
111        let k: usize = self.hash_count() as usize;
112        let mut cached_slots: [usize; 16] = [0usize; 16];
113        let mut probe: u64 = h1;
114        let mut i: usize = 0;
115        while i < k {
116            let idx: usize = (((probe as u128).wrapping_mul(slots)) >> 64) as usize;
117            if self.get_counter(idx) == 0 {
118                return false;
119            }
120            cached_slots[i] = idx;
121            probe = probe.wrapping_add(h2);
122            i += 1;
123        }
124        let mut j: usize = 0;
125        while j < k {
126            let idx: usize = cached_slots[j];
127            let cur: u8 = self.get_counter(idx);
128            if cur > 0 && cur < MAX_NIBBLE {
129                self.set_counter(idx, cur - 1);
130            }
131            j += 1;
132        }
133        true
134    }
135
136    /// Tests whether `item` may be present in the counting Bloom filter.
137    ///
138    /// # Arguments
139    ///
140    /// - `&[u8]` - Element bytes to query.
141    ///
142    /// # Returns
143    ///
144    /// - `bool` - `false` if definitely absent, `true` if probably present.
145    #[inline]
146    pub fn contains(&self, item: &[u8]) -> bool {
147        let (h1, h2): (u64, u64) = hash_pair(item);
148        let slots: u128 = self.slot_len() as u128;
149        let k: u32 = self.hash_count();
150        let mut probe: u64 = h1;
151        for _ in 0..k {
152            let idx: usize = (((probe as u128).wrapping_mul(slots)) >> 64) as usize;
153            if self.get_counter(idx) == 0 {
154                return false;
155            }
156            probe = probe.wrapping_add(h2);
157        }
158        true
159    }
160
161    /// Resets all counters to zero.
162    pub fn clear(&mut self) {
163        let Self { nibbles, .. } = self;
164        nibbles.fill(0);
165    }
166
167    /// Returns total number of 4-bit counter slots.
168    ///
169    /// # Returns
170    ///
171    /// - `usize` - Counter slot count.
172    #[inline(always)]
173    pub fn slot_len(&self) -> usize {
174        let Self { slot_count, .. } = self;
175        *slot_count
176    }
177
178    /// Returns configured hash probe count.
179    ///
180    /// # Returns
181    ///
182    /// - `u32` - Probe count `k`.
183    #[inline(always)]
184    pub fn hash_count(&self) -> u32 {
185        let Self { hash_count, .. } = self;
186        *hash_count
187    }
188}