probabilistic_machines 0.1.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,26 +1,33 @@
1
1
  //! Frequency estimation for a stream nobody wants to store.
2
2
 
3
3
  use crate::hash::{hash64, mix64, u32_low_u8, u64_low_u16, usize_low_u8};
4
- use crate::{CodecError, TAG_COUNTMIN, read8};
4
+ use crate::{Refusal, TAG_COUNTMIN, open_frame};
5
5
 
6
+ /// Tag, width bits, depth, the eight-byte total, then one reserved byte: the
7
+ /// byte that once flagged a saturated counter. No counter saturates any more,
8
+ /// so it is written as zero and a frame carrying anything else (one an earlier
9
+ /// release wrote after a counter stopped at `u32::MAX`) is refused.
6
10
  const HEADER_LEN: usize = 12;
7
11
  const COUNTER_LEN: usize = 4;
8
12
 
9
13
  /// Counts how often each item appeared, in `W * D` counters.
10
14
  ///
11
15
  /// `W` is the row width, a power of two up to 65536; `D` is the number of rows.
12
- /// An estimate is never below the true count while [`saturated`](Self::saturated)
13
- /// is false, and overshoots it by more than
16
+ /// An estimate is never below the true count, and overshoots it by more than
14
17
  /// `e * total / W` with probability at most `e^-D`, where `total` is the sum of
15
18
  /// every count added. 2048 columns over 5 rows hold the overshoot under 0.14%
16
19
  /// of the total with probability 0.993.
17
20
  ///
21
+ /// A counter is a `u32`. An addition or a merge that would carry one past
22
+ /// [`u32::MAX`] is refused with [`Refusal::Overflow`] and changes nothing, so
23
+ /// no counter ever saturates and the lower bound above always holds.
24
+ ///
18
25
  /// ```
19
26
  /// use probabilistic_machines::CountMinSketch;
20
27
  ///
21
28
  /// let mut hits = CountMinSketch::<1024, 4>::new();
22
- /// hits.add_count(b"/login", 900);
23
- /// hits.add(b"/health");
29
+ /// assert_eq!(hits.add_count(b"/login", 900), Ok(()));
30
+ /// assert_eq!(hits.add(b"/health"), Ok(()));
24
31
  ///
25
32
  /// assert!(hits.estimate(b"/login") >= 900);
26
33
  /// assert_eq!(hits.estimate(b"/never-seen"), 0);
@@ -29,8 +36,6 @@ const COUNTER_LEN: usize = 4;
29
36
  #[derive(Debug, Clone, PartialEq, Eq)]
30
37
  pub struct CountMinSketch<const W: usize, const D: usize> {
31
38
  rows: [[u32; W]; D],
32
- saturated: bool,
33
- total: u64,
34
39
  }
35
40
 
36
41
  impl<const W: usize, const D: usize> CountMinSketch<W, D> {
@@ -46,47 +51,76 @@ impl<const W: usize, const D: usize> CountMinSketch<W, D> {
46
51
  /// Length of the [`encode`](Self::encode) frame.
47
52
  pub const ENCODED_LEN: usize = HEADER_LEN + W * D * COUNTER_LEN;
48
53
 
54
+ /// An empty sketch: every counter zero.
49
55
  #[must_use]
50
56
  pub const fn new() -> Self {
51
- Self {
52
- rows: [[0; W]; D],
53
- total: 0,
54
- saturated: false,
55
- }
56
- }
57
-
58
- /// Sum of every count added, saturating at [`u64::MAX`].
59
- #[must_use]
60
- pub const fn total(&self) -> u64 {
61
- self.total
57
+ Self { rows: [[0; W]; D] }
62
58
  }
63
59
 
64
- /// True once a counter has hit [`u32::MAX`], after which an estimate can
65
- /// fall below the true count.
60
+ /// Sum of every count added.
61
+ ///
62
+ /// Every row takes every count, so each sums to the total exactly; this
63
+ /// reads it off the first. `W` counters below `2^32` sum below `2^48`, so
64
+ /// the total needs no overflow check of its own: an addition whose
65
+ /// counters fit has a total that fits.
66
66
  #[must_use]
67
- pub const fn saturated(&self) -> bool {
68
- self.saturated
67
+ pub fn total(&self) -> u64 {
68
+ self.rows
69
+ .iter()
70
+ .take(1)
71
+ .flatten()
72
+ .copied()
73
+ .map(u64::from)
74
+ .sum()
69
75
  }
70
76
 
71
- pub fn add(&mut self, item: &[u8]) {
72
- self.add_count(item, 1);
77
+ /// Adds one occurrence of `item`.
78
+ ///
79
+ /// # Errors
80
+ ///
81
+ /// As [`add_hash_count`](Self::add_hash_count).
82
+ pub fn add(&mut self, item: &[u8]) -> Result<(), Refusal> {
83
+ self.add_count(item, 1)
73
84
  }
74
85
 
75
- pub fn add_count(&mut self, item: &[u8], count: u32) {
76
- self.add_hash_count(hash64(item), count);
86
+ /// Adds `count` occurrences of `item`.
87
+ ///
88
+ /// # Errors
89
+ ///
90
+ /// As [`add_hash_count`](Self::add_hash_count).
91
+ pub fn add_count(&mut self, item: &[u8], count: u32) -> Result<(), Refusal> {
92
+ self.add_hash_count(hash64(item), count)
77
93
  }
78
94
 
79
95
  /// Adds to an item the caller already hashed.
80
- pub fn add_hash_count(&mut self, hash: u64, count: u32) {
96
+ ///
97
+ /// # Errors
98
+ ///
99
+ /// [`Refusal::ZeroCount`] when `count` is zero, [`Refusal::Overflow`] when
100
+ /// one of the item's counters would pass [`u32::MAX`]. The sketch is
101
+ /// unchanged either way.
102
+ pub fn add_hash_count(&mut self, hash: u64, count: u32) -> Result<(), Refusal> {
103
+ if count == 0 {
104
+ return Err(Refusal::ZeroCount);
105
+ }
106
+ let mut raised: [Option<(&mut u32, u32)>; D] = [const { None }; D];
81
107
  let mut cursor = hash;
82
- for row in &mut self.rows {
108
+ for (row, target) in self.rows.iter_mut().zip(&mut raised) {
83
109
  cursor = mix64(cursor);
84
110
  let column = usize::from(u64_low_u16(cursor)) & Self::COLUMN_MASK;
85
- let (sum, overflowed) = row[column].overflowing_add(count);
86
- self.saturated |= overflowed;
87
- row[column] = if overflowed { u32::MAX } else { sum };
111
+ let Some(counter) = row.get_mut(column) else {
112
+ debug_assert!(false, "a column is masked below W");
113
+ return Err(Refusal::Overflow);
114
+ };
115
+ let Some(sum) = counter.checked_add(count) else {
116
+ return Err(Refusal::Overflow);
117
+ };
118
+ *target = Some((counter, sum));
119
+ }
120
+ for (counter, sum) in raised.into_iter().flatten() {
121
+ *counter = sum;
88
122
  }
89
- self.total = self.total.saturating_add(u64::from(count));
123
+ Ok(())
90
124
  }
91
125
 
92
126
  /// Upper bound on how often `item` was added.
@@ -103,8 +137,11 @@ impl<const W: usize, const D: usize> CountMinSketch<W, D> {
103
137
  for row in &self.rows {
104
138
  cursor = mix64(cursor);
105
139
  let column = usize::from(u64_low_u16(cursor)) & Self::COLUMN_MASK;
106
- if row[column] < smallest {
107
- smallest = row[column];
140
+ // The column is masked below `W`, so the lookup always lands.
141
+ if let Some(&held) = row.get(column)
142
+ && held < smallest
143
+ {
144
+ smallest = held;
108
145
  }
109
146
  }
110
147
  smallest
@@ -112,52 +149,42 @@ impl<const W: usize, const D: usize> CountMinSketch<W, D> {
112
149
 
113
150
  /// Adds another sketch's counters to this one, which is exact for sketches
114
151
  /// of the same shape: the result equals one sketch fed both streams.
115
- pub fn merge(&mut self, other: &Self) {
116
- let mut saturated = self.saturated || other.saturated;
117
- for (mine, theirs) in self.rows.iter_mut().zip(&other.rows) {
118
- for (counter, addend) in mine.iter_mut().zip(theirs) {
119
- let (sum, overflowed) = counter.overflowing_add(*addend);
120
- saturated |= overflowed;
121
- *counter = if overflowed { u32::MAX } else { sum };
122
- }
123
- }
124
- self.saturated = saturated;
125
- self.total = self.total.saturating_add(other.total);
126
- }
127
-
128
- /// Writes the sketch into `out`, returning the number of bytes written.
129
152
  ///
130
153
  /// # Errors
131
154
  ///
132
- /// [`CodecError::Truncated`] when `out` is shorter than
133
- /// [`ENCODED_LEN`](Self::ENCODED_LEN).
134
- pub fn encode(&self, out: &mut [u8]) -> Result<usize, CodecError> {
135
- let Some(frame) = out.get_mut(..Self::ENCODED_LEN) else {
136
- return Err(CodecError::Truncated);
137
- };
138
- self.write_frame(frame);
139
- Ok(Self::ENCODED_LEN)
155
+ /// [`Refusal::Overflow`] when any counter's sum would pass [`u32::MAX`].
156
+ /// Every sum is checked before the first is stored, so a refused merge
157
+ /// leaves the sketch as it was.
158
+ pub fn merge(&mut self, other: &Self) -> Result<(), Refusal> {
159
+ let mine = self.rows.iter().flatten();
160
+ let theirs = other.rows.iter().flatten();
161
+ if mine
162
+ .zip(theirs)
163
+ .any(|(counter, addend)| counter.checked_add(*addend).is_none())
164
+ {
165
+ return Err(Refusal::Overflow);
166
+ }
167
+ let mine = self.rows.iter_mut().flatten();
168
+ for (counter, addend) in mine.zip(other.rows.iter().flatten()) {
169
+ // Every sum was checked above, so none of these saturates.
170
+ *counter = counter.saturating_add(*addend);
171
+ }
172
+ Ok(())
140
173
  }
141
174
 
142
- /// The sketch's frame, exactly [`ENCODED_LEN`](Self::ENCODED_LEN) bytes.
143
- #[cfg(feature = "alloc")]
144
- #[must_use]
145
- pub fn encoded(&self) -> alloc::boxed::Box<[u8]> {
146
- let mut frame = alloc::vec![0_u8; Self::ENCODED_LEN].into_boxed_slice();
147
- self.write_frame(&mut frame);
148
- frame
149
- }
175
+ encoders!("sketch");
150
176
 
151
177
  /// Fills a frame of exactly [`ENCODED_LEN`](Self::ENCODED_LEN) bytes.
152
- fn write_frame(&self, frame: &mut [u8]) {
153
- frame[0] = TAG_COUNTMIN;
154
- frame[1] = u32_low_u8(W.trailing_zeros());
155
- frame[2] = usize_low_u8(D);
156
- frame[3..11].copy_from_slice(&self.total.to_le_bytes());
157
- frame[11] = u8::from(self.saturated);
178
+ fn write_frame(&self, header: &mut [u8; HEADER_LEN], body: &mut [u8]) {
179
+ let [tag, bits, depth, total @ .., reserved] = header;
180
+ *tag = TAG_COUNTMIN;
181
+ *bits = u32_low_u8(W.trailing_zeros());
182
+ *depth = usize_low_u8(D);
183
+ *total = self.total().to_le_bytes();
184
+ *reserved = 0;
158
185
 
159
186
  let counters = self.rows.iter().flatten();
160
- let (slots, _) = frame[HEADER_LEN..].as_chunks_mut::<COUNTER_LEN>();
187
+ let (slots, _) = body.as_chunks_mut::<COUNTER_LEN>();
161
188
  for (slot, counter) in slots.iter_mut().zip(counters) {
162
189
  *slot = counter.to_le_bytes();
163
190
  }
@@ -167,10 +194,13 @@ impl<const W: usize, const D: usize> CountMinSketch<W, D> {
167
194
  ///
168
195
  /// # Errors
169
196
  ///
170
- /// [`CodecError::Truncated`] when `bytes` is too short, [`CodecError::Tag`]
171
- /// when it holds another structure, [`CodecError::Parameters`] when its
172
- /// shape differs from `W` by `D` or its counters contradict its total.
173
- pub fn decode(bytes: &[u8]) -> Result<Self, CodecError> {
197
+ /// [`Refusal::Truncated`] when `bytes` is too short,
198
+ /// [`Refusal::WrongStructure`] when it holds another structure,
199
+ /// [`Refusal::WrongShape`] when its shape differs from `W` by `D`,
200
+ /// [`Refusal::Malformed`] when its counters contradict its total or it
201
+ /// carries the saturation flag of an earlier release, whose counters no
202
+ /// longer bound the true counts from above.
203
+ pub fn decode(bytes: &[u8]) -> Result<Self, Refusal> {
174
204
  let mut sketch = Self::new();
175
205
  sketch.decode_into(bytes)?;
176
206
  Ok(sketch)
@@ -184,26 +214,19 @@ impl<const W: usize, const D: usize> CountMinSketch<W, D> {
184
214
  /// # Errors
185
215
  ///
186
216
  /// The same as [`decode`](Self::decode).
187
- pub fn decode_into(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
188
- let Some(frame) = bytes.get(..Self::ENCODED_LEN) else {
189
- return Err(CodecError::Truncated);
190
- };
191
- if frame[0] != TAG_COUNTMIN {
192
- return Err(CodecError::Tag);
193
- }
194
- if frame[1] != u32_low_u8(W.trailing_zeros()) || frame[2] != usize_low_u8(D) {
195
- return Err(CodecError::Parameters);
217
+ pub fn decode_into(&mut self, bytes: &[u8]) -> Result<(), Refusal> {
218
+ let (header, body) = open_frame::<HEADER_LEN>(bytes, Self::ENCODED_LEN, TAG_COUNTMIN)?;
219
+ let [_, bits, depth, total @ .., reserved] = *header;
220
+ if bits != u32_low_u8(W.trailing_zeros()) || depth != usize_low_u8(D) {
221
+ return Err(Refusal::WrongShape);
196
222
  }
197
223
 
198
- let total = u64::from_le_bytes(read8(&frame[3..11]));
199
- let saturated = frame[11] != 0;
200
- let (slots, _) = frame[HEADER_LEN..].as_chunks::<COUNTER_LEN>();
201
- if !Self::rows_are_coherent(slots, total, saturated) {
202
- return Err(CodecError::Parameters);
224
+ let total = u64::from_le_bytes(total);
225
+ let (slots, _) = body.as_chunks::<COUNTER_LEN>();
226
+ if reserved != 0 || !Self::rows_are_coherent(slots, total) {
227
+ return Err(Refusal::Malformed);
203
228
  }
204
229
 
205
- self.total = total;
206
- self.saturated = saturated;
207
230
  let counters = self.rows.iter_mut().flatten();
208
231
  for (slot, counter) in slots.iter().zip(counters) {
209
232
  *counter = u32::from_le_bytes(*slot);
@@ -213,19 +236,14 @@ impl<const W: usize, const D: usize> CountMinSketch<W, D> {
213
236
 
214
237
  /// Whether the counters carry the total the frame claims, as every sketch
215
238
  /// built by adding items does: each row takes every count added, so it sums
216
- /// to the total exactly. Only a counter stopped at [`u32::MAX`] can leave a
217
- /// row short of it, and such a sketch says so in its saturation flag.
218
- fn rows_are_coherent(slots: &[[u8; COUNTER_LEN]], total: u64, saturated: bool) -> bool {
239
+ /// to the total exactly.
240
+ fn rows_are_coherent(slots: &[[u8; COUNTER_LEN]], total: u64) -> bool {
219
241
  slots.chunks(W).all(|row| {
220
242
  let counted: u64 = row
221
243
  .iter()
222
244
  .map(|slot| u64::from(u32::from_le_bytes(*slot)))
223
245
  .sum();
224
- if saturated {
225
- counted <= total
226
- } else {
227
- counted == total
228
- }
246
+ counted == total
229
247
  })
230
248
  }
231
249
  }
@@ -1,28 +1,28 @@
1
1
  //! Approximate membership with deletions, which a Bloom filter cannot do.
2
2
 
3
3
  use crate::hash::{hash64, mix64, u32_low_u8, u64_low_u8, u64_low_u16};
4
- use crate::{CodecError, TAG_CUCKOO};
4
+ use crate::{Refusal, TAG_CUCKOO, open_frame};
5
5
 
6
6
  const SLOTS: usize = 4;
7
7
  const EMPTY: u8 = 0;
8
8
  const MAX_KICKS: usize = 64;
9
+ /// Tag and bucket-count bits.
10
+ const HEADER_LEN: usize = 2;
9
11
 
10
- /// The filter has no room left for this item.
11
- ///
12
- /// Cuckoo hashing gives up before the table is literally full; expect that
13
- /// past about 95% of [`CuckooFilter::CAPACITY`]. The filter is unchanged when
14
- /// an insert fails.
12
+ /// What [`CuckooFilter::remove`] did. Both answers are honoured, and both are
13
+ /// about the item's fingerprint, which is all the filter stores.
15
14
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
- pub struct Full;
17
-
18
- impl core::fmt::Display for Full {
19
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
20
- f.write_str("cuckoo filter full")
21
- }
15
+ #[must_use]
16
+ pub enum Removing {
17
+ /// One copy of the item's fingerprint was cleared from one of its two
18
+ /// buckets. Not a proof the item was inserted: the fingerprint may have
19
+ /// been another item's. See the caveat on [`CuckooFilter::remove`].
20
+ Cleared,
21
+ /// Neither of the item's buckets holds its fingerprint, so the item is not
22
+ /// in the filter: what the call asked for already holds. Nothing changed.
23
+ NotHeld,
22
24
  }
23
25
 
24
- impl core::error::Error for Full {}
25
-
26
26
  /// Answers "have I seen this?" in `B * 4` bytes, and unlike a Bloom filter it
27
27
  /// can forget.
28
28
  ///
@@ -32,19 +32,20 @@ impl core::error::Error for Full {}
32
32
  /// inserted; it says yes to an item that was not with probability at most
33
33
  /// `2 * 4 / 255`, about 3%.
34
34
  ///
35
- /// [`remove`](Self::remove) must only be called for items that were inserted:
36
- /// deleting an item that merely collides with one takes the other item's
37
- /// fingerprint with it.
35
+ /// The filter is a multiset of fingerprints: inserting an item twice stores
36
+ /// two copies, and it takes two removals to forget it. It cannot tell a repeat
37
+ /// from a collision, so an insert is never answered as a duplicate.
38
38
  ///
39
39
  /// ```
40
- /// use probabilistic_machines::CuckooFilter;
40
+ /// use probabilistic_machines::{CuckooFilter, Removing};
41
41
  ///
42
42
  /// let mut seen = CuckooFilter::<1024>::new();
43
43
  /// assert_eq!(seen.insert(b"device-9"), Ok(()));
44
44
  /// assert!(seen.contains(b"device-9"));
45
45
  ///
46
- /// assert!(seen.remove(b"device-9"));
46
+ /// assert_eq!(seen.remove(b"device-9"), Removing::Cleared);
47
47
  /// assert!(!seen.contains(b"device-9"));
48
+ /// assert_eq!(seen.remove(b"device-9"), Removing::NotHeld);
48
49
  /// ```
49
50
  #[derive(Debug, Clone, PartialEq, Eq)]
50
51
  pub struct CuckooFilter<const B: usize> {
@@ -64,8 +65,9 @@ impl<const B: usize> CuckooFilter<B> {
64
65
  pub const CAPACITY: usize = B * SLOTS;
65
66
 
66
67
  /// Length of the [`encode`](Self::encode) frame.
67
- pub const ENCODED_LEN: usize = 2 + B * SLOTS;
68
+ pub const ENCODED_LEN: usize = HEADER_LEN + B * SLOTS;
68
69
 
70
+ /// An empty filter.
69
71
  #[must_use]
70
72
  pub const fn new() -> Self {
71
73
  Self {
@@ -80,16 +82,20 @@ impl<const B: usize> CuckooFilter<B> {
80
82
  self.items
81
83
  }
82
84
 
85
+ /// Whether the filter holds no item.
83
86
  #[must_use]
84
87
  pub const fn is_empty(&self) -> bool {
85
88
  self.items == 0
86
89
  }
87
90
 
91
+ /// Stores one copy of the item's fingerprint.
92
+ ///
88
93
  /// # Errors
89
94
  ///
90
- /// [`Full`] when the item's two buckets and 64 evictions all failed to
91
- /// find a slot. The filter is left as it was.
92
- pub fn insert(&mut self, item: &[u8]) -> Result<(), Full> {
95
+ /// [`Refusal::Full`] when the item's two buckets and 64 evictions all
96
+ /// failed to find a slot: expect that past about 95% of
97
+ /// [`CAPACITY`](Self::CAPACITY). The filter is left as it was.
98
+ pub fn insert(&mut self, item: &[u8]) -> Result<(), Refusal> {
93
99
  self.insert_hash(hash64(item))
94
100
  }
95
101
 
@@ -97,9 +103,9 @@ impl<const B: usize> CuckooFilter<B> {
97
103
  ///
98
104
  /// # Errors
99
105
  ///
100
- /// [`Full`] when the item's two buckets and 64 evictions all failed to
101
- /// find a slot. The filter is left as it was.
102
- pub fn insert_hash(&mut self, hash: u64) -> Result<(), Full> {
106
+ /// [`Refusal::Full`] when the item's two buckets and 64 evictions all
107
+ /// failed to find a slot. The filter is left as it was.
108
+ pub fn insert_hash(&mut self, hash: u64) -> Result<(), Refusal> {
103
109
  let fingerprint = fingerprint(hash);
104
110
  let primary = Self::bucket(hash);
105
111
  if self.place(primary, fingerprint) {
@@ -110,7 +116,8 @@ impl<const B: usize> CuckooFilter<B> {
110
116
  return Ok(());
111
117
  }
112
118
 
113
- let mut path = [0_usize; MAX_KICKS];
119
+ let mut path = [(0_usize, 0_usize); MAX_KICKS];
120
+ let mut kicked = 0;
114
121
  let mut index = alternate;
115
122
  let mut carried = fingerprint;
116
123
  let mut walk = mix64(hash);
@@ -118,20 +125,31 @@ impl<const B: usize> CuckooFilter<B> {
118
125
  for step in &mut path {
119
126
  walk = mix64(walk);
120
127
  let slot = usize::from(u64_low_u16(walk)) % SLOTS;
121
- core::mem::swap(&mut carried, &mut self.buckets[index][slot]);
122
- *step = index * SLOTS + slot;
128
+ let Some(cell) = self.cell_mut(index, slot) else {
129
+ debug_assert!(false, "a bucket is masked below B and a slot below SLOTS");
130
+ // Undone below with the kicks before it: refused, unchanged.
131
+ break;
132
+ };
133
+ core::mem::swap(&mut carried, cell);
134
+ *step = (index, slot);
135
+ kicked += 1;
123
136
  index = Self::alternate(index, carried);
124
137
  if self.place(index, carried) {
125
138
  return Ok(());
126
139
  }
127
140
  }
128
141
 
129
- for step in path.iter().rev() {
130
- core::mem::swap(&mut carried, &mut self.buckets[step / SLOTS][step % SLOTS]);
142
+ // Every cell on the path was found on the way out, so each is found
143
+ // again on the way back.
144
+ for &(index, slot) in path.iter().take(kicked).rev() {
145
+ if let Some(cell) = self.cell_mut(index, slot) {
146
+ core::mem::swap(&mut carried, cell);
147
+ }
131
148
  }
132
- Err(Full)
149
+ Err(Refusal::Full)
133
150
  }
134
151
 
152
+ /// Whether `item` may be held: no false negatives, rare false positives.
135
153
  #[must_use]
136
154
  pub fn contains(&self, item: &[u8]) -> bool {
137
155
  self.contains_hash(hash64(item))
@@ -143,53 +161,49 @@ impl<const B: usize> CuckooFilter<B> {
143
161
  let fingerprint = fingerprint(hash);
144
162
  let primary = Self::bucket(hash);
145
163
  let alternate = Self::alternate(primary, fingerprint);
146
- self.buckets[primary].contains(&fingerprint)
147
- || self.buckets[alternate].contains(&fingerprint)
164
+ // Both buckets are masked below `B`, so both lookups land.
165
+ let holds = |index: usize| {
166
+ self.buckets
167
+ .get(index)
168
+ .is_some_and(|bucket| bucket.contains(&fingerprint))
169
+ };
170
+ holds(primary) || holds(alternate)
148
171
  }
149
172
 
150
- /// Drops one copy of an item, reporting whether a fingerprint was cleared.
151
- pub fn remove(&mut self, item: &[u8]) -> bool {
173
+ /// Drops one copy of an item.
174
+ ///
175
+ /// [`Removing::NotHeld`] is a proof: a filter has no false negatives, so
176
+ /// an item whose fingerprint is in neither of its buckets was not there,
177
+ /// and nothing changed. [`Removing::Cleared`] is not one. A fingerprint is
178
+ /// eight bits, so about 3% of items that were never inserted match a
179
+ /// stored one (the same false positive [`contains`](Self::contains) has),
180
+ /// and removing such an item clears the fingerprint of the item it
181
+ /// collides with, which the filter then denies having seen. Only remove
182
+ /// what was inserted.
183
+ pub fn remove(&mut self, item: &[u8]) -> Removing {
152
184
  self.remove_hash(hash64(item))
153
185
  }
154
186
 
155
- /// Drops an item the caller already hashed.
156
- pub fn remove_hash(&mut self, hash: u64) -> bool {
187
+ /// Drops an item the caller already hashed. As [`remove`](Self::remove).
188
+ pub fn remove_hash(&mut self, hash: u64) -> Removing {
157
189
  let fingerprint = fingerprint(hash);
158
190
  let primary = Self::bucket(hash);
159
191
  let alternate = Self::alternate(primary, fingerprint);
160
- self.clear(primary, fingerprint) || self.clear(alternate, fingerprint)
161
- }
162
-
163
- /// Writes the filter into `out`, returning the number of bytes written.
164
- ///
165
- /// # Errors
166
- ///
167
- /// [`CodecError::Truncated`] when `out` is shorter than
168
- /// [`ENCODED_LEN`](Self::ENCODED_LEN).
169
- pub fn encode(&self, out: &mut [u8]) -> Result<usize, CodecError> {
170
- let Some(frame) = out.get_mut(..Self::ENCODED_LEN) else {
171
- return Err(CodecError::Truncated);
172
- };
173
- self.write_frame(frame);
174
- Ok(Self::ENCODED_LEN)
192
+ if self.clear(primary, fingerprint) || self.clear(alternate, fingerprint) {
193
+ Removing::Cleared
194
+ } else {
195
+ Removing::NotHeld
196
+ }
175
197
  }
176
198
 
177
- /// The filter's frame, exactly [`ENCODED_LEN`](Self::ENCODED_LEN) bytes.
178
- #[cfg(feature = "alloc")]
179
- #[must_use]
180
- pub fn encoded(&self) -> alloc::boxed::Box<[u8]> {
181
- let mut frame = alloc::vec![0_u8; Self::ENCODED_LEN].into_boxed_slice();
182
- self.write_frame(&mut frame);
183
- frame
184
- }
199
+ encoders!("filter");
185
200
 
186
201
  /// Fills a frame of exactly [`ENCODED_LEN`](Self::ENCODED_LEN) bytes.
187
- fn write_frame(&self, frame: &mut [u8]) {
188
- frame[0] = TAG_CUCKOO;
189
- frame[1] = u32_low_u8(B.trailing_zeros());
202
+ fn write_frame(&self, header: &mut [u8; HEADER_LEN], body: &mut [u8]) {
203
+ *header = [TAG_CUCKOO, u32_low_u8(B.trailing_zeros())];
190
204
 
191
205
  let fingerprints = self.buckets.iter().flatten();
192
- for (slot, value) in frame[2..].iter_mut().zip(fingerprints) {
206
+ for (slot, value) in body.iter_mut().zip(fingerprints) {
193
207
  *slot = *value;
194
208
  }
195
209
  }
@@ -198,10 +212,12 @@ impl<const B: usize> CuckooFilter<B> {
198
212
  ///
199
213
  /// # Errors
200
214
  ///
201
- /// [`CodecError::Truncated`] when `bytes` is too short, [`CodecError::Tag`]
202
- /// when it holds another structure, [`CodecError::Parameters`] when it was
203
- /// written with a different bucket count.
204
- pub fn decode(bytes: &[u8]) -> Result<Self, CodecError> {
215
+ /// [`Refusal::Truncated`] when `bytes` is too short,
216
+ /// [`Refusal::WrongStructure`] when it holds another structure,
217
+ /// [`Refusal::WrongShape`] when it was written with a different bucket
218
+ /// count. Every table of fingerprints is one some inserts could leave, so
219
+ /// this decoder never answers [`Refusal::Malformed`].
220
+ pub fn decode(bytes: &[u8]) -> Result<Self, Refusal> {
205
221
  let mut filter = Self::new();
206
222
  filter.decode_into(bytes)?;
207
223
  Ok(filter)
@@ -215,20 +231,15 @@ impl<const B: usize> CuckooFilter<B> {
215
231
  /// # Errors
216
232
  ///
217
233
  /// The same as [`decode`](Self::decode).
218
- pub fn decode_into(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
219
- let Some(frame) = bytes.get(..Self::ENCODED_LEN) else {
220
- return Err(CodecError::Truncated);
221
- };
222
- if frame[0] != TAG_CUCKOO {
223
- return Err(CodecError::Tag);
224
- }
225
- if frame[1] != u32_low_u8(B.trailing_zeros()) {
226
- return Err(CodecError::Parameters);
234
+ pub fn decode_into(&mut self, bytes: &[u8]) -> Result<(), Refusal> {
235
+ let (&[_, bits], body) = open_frame::<HEADER_LEN>(bytes, Self::ENCODED_LEN, TAG_CUCKOO)?;
236
+ if bits != u32_low_u8(B.trailing_zeros()) {
237
+ return Err(Refusal::WrongShape);
227
238
  }
228
239
 
229
240
  self.items = 0;
230
241
  let fingerprints = self.buckets.iter_mut().flatten();
231
- for (value, byte) in fingerprints.zip(&frame[2..]) {
242
+ for (value, byte) in fingerprints.zip(body) {
232
243
  *value = *byte;
233
244
  if *byte != EMPTY {
234
245
  self.items += 1;
@@ -246,8 +257,18 @@ impl<const B: usize> CuckooFilter<B> {
246
257
  index ^ twist
247
258
  }
248
259
 
260
+ /// Slot `slot` of bucket `index`; `None` past `B` or `SLOTS`.
261
+ fn cell_mut(&mut self, index: usize, slot: usize) -> Option<&mut u8> {
262
+ self.buckets.get_mut(index)?.get_mut(slot)
263
+ }
264
+
265
+ /// Fills the first empty slot of bucket `index`. Every bucket index is
266
+ /// masked below `B`, so the bucket is always found.
249
267
  fn place(&mut self, index: usize, fingerprint: u8) -> bool {
250
- for slot in &mut self.buckets[index] {
268
+ let Some(bucket) = self.buckets.get_mut(index) else {
269
+ return false;
270
+ };
271
+ for slot in bucket {
251
272
  if *slot == EMPTY {
252
273
  *slot = fingerprint;
253
274
  self.items += 1;
@@ -257,10 +278,17 @@ impl<const B: usize> CuckooFilter<B> {
257
278
  false
258
279
  }
259
280
 
281
+ /// Clears one copy of `fingerprint` from bucket `index`, found as in
282
+ /// [`place`](Self::place).
260
283
  fn clear(&mut self, index: usize, fingerprint: u8) -> bool {
261
- for slot in &mut self.buckets[index] {
284
+ let Some(bucket) = self.buckets.get_mut(index) else {
285
+ return false;
286
+ };
287
+ for slot in bucket {
262
288
  if *slot == fingerprint {
263
289
  *slot = EMPTY;
290
+ // `items` counts the non-empty slots and this one held a
291
+ // fingerprint (never `EMPTY`), so it is at least one.
264
292
  self.items -= 1;
265
293
  return true;
266
294
  }