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 = nibbles[slot >> 1];
57        if (slot & 1) == 0 {
58            byte & MAX_NIBBLE
59        } else {
60            byte >> 4
61        }
62    }
63
64    /// Writes a 4-bit counter `val` (`0..=15`) into `slot`.
65    ///
66    /// # Arguments
67    ///
68    /// - `usize` - Counter index in `0..slot_count`.
69    /// - `u8` - New 4-bit value (`0..=15`).
70    #[inline(always)]
71    fn set_counter(&mut self, slot: usize, val: u8) {
72        let Self { nibbles, .. } = self;
73        let clamped: u8 = val & MAX_NIBBLE;
74        let byte: &mut u8 = &mut nibbles[slot >> 1];
75        if (slot & 1) == 0 {
76            *byte = (*byte & 0xf0) | clamped;
77        } else {
78            *byte = (*byte & MAX_NIBBLE) | (clamped << 4);
79        }
80    }
81
82    /// Inserts `item`, saturating any counter that reaches `15` to prevent overflow wrap.
83    ///
84    /// # Arguments
85    ///
86    /// - `&[u8]` - Element bytes to insert.
87    pub fn insert(&mut self, item: &[u8]) {
88        let (h1, h2): (u64, u64) = hash_pair(item);
89        let slots: usize = self.slot_len();
90        let k: u32 = self.hash_count();
91        for i in 0..k {
92            let idx: usize = (h1.wrapping_add(u64::from(i).wrapping_mul(h2)) as usize) % slots;
93            let cur: u8 = self.get_counter(idx);
94            if cur < MAX_NIBBLE {
95                self.set_counter(idx, cur + 1);
96            }
97        }
98    }
99
100    /// Removes one occurrence of `item` when all its counters are non-zero.
101    ///
102    /// Saturated counters (`15`) remain saturated to avoid introducing false negatives.
103    ///
104    /// # Arguments
105    ///
106    /// - `&[u8]` - Element bytes to remove.
107    ///
108    /// # Returns
109    ///
110    /// - `bool` - `true` if the item appeared present and counters were decremented.
111    pub fn remove(&mut self, item: &[u8]) -> bool {
112        if !self.contains(item) {
113            return false;
114        }
115        let (h1, h2): (u64, u64) = hash_pair(item);
116        let slots: usize = self.slot_len();
117        let k: u32 = self.hash_count();
118        for i in 0..k {
119            let idx: usize = (h1.wrapping_add(u64::from(i).wrapping_mul(h2)) as usize) % slots;
120            let cur: u8 = self.get_counter(idx);
121            if cur > 0 && cur < MAX_NIBBLE {
122                self.set_counter(idx, cur - 1);
123            }
124        }
125        true
126    }
127
128    /// Tests whether `item` may be present in the counting Bloom filter.
129    ///
130    /// # Arguments
131    ///
132    /// - `&[u8]` - Element bytes to query.
133    ///
134    /// # Returns
135    ///
136    /// - `bool` - `false` if definitely absent, `true` if probably present.
137    pub fn contains(&self, item: &[u8]) -> bool {
138        let (h1, h2): (u64, u64) = hash_pair(item);
139        let slots: usize = self.slot_len();
140        let k: u32 = self.hash_count();
141        for i in 0..k {
142            let idx: usize = (h1.wrapping_add(u64::from(i).wrapping_mul(h2)) as usize) % slots;
143            if self.get_counter(idx) == 0 {
144                return false;
145            }
146        }
147        true
148    }
149
150    /// Resets all counters to zero.
151    pub fn clear(&mut self) {
152        let Self { nibbles, .. } = self;
153        nibbles.fill(0);
154    }
155
156    /// Returns total number of 4-bit counter slots.
157    ///
158    /// # Returns
159    ///
160    /// - `usize` - Counter slot count.
161    #[inline(always)]
162    pub fn slot_len(&self) -> usize {
163        let Self { slot_count, .. } = self;
164        *slot_count
165    }
166
167    /// Returns configured hash probe count.
168    ///
169    /// # Returns
170    ///
171    /// - `u32` - Probe count `k`.
172    #[inline(always)]
173    pub fn hash_count(&self) -> u32 {
174        let Self { hash_count, .. } = self;
175        *hash_count
176    }
177}