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.
@@ -29,33 +29,25 @@ pub const fn hash64(bytes: &[u8]) -> u64 {
29
29
  #[must_use]
30
30
  pub const fn hash64_with_seed(bytes: &[u8], seed: u64) -> u64 {
31
31
  let mut accumulator = seed ^ PRIME;
32
+ // Counts at most `bytes.len()`, which fits a `u64`.
32
33
  let mut consumed: u64 = 0;
33
- let mut cursor = 0;
34
+ let mut rest = bytes;
34
35
 
35
- while cursor + 8 <= bytes.len() {
36
- let lane = u64::from_le_bytes([
37
- bytes[cursor],
38
- bytes[cursor + 1],
39
- bytes[cursor + 2],
40
- bytes[cursor + 3],
41
- bytes[cursor + 4],
42
- bytes[cursor + 5],
43
- bytes[cursor + 6],
44
- bytes[cursor + 7],
45
- ]);
46
- accumulator = (accumulator ^ mix64(lane))
36
+ while let Some((lane, after)) = rest.split_first_chunk::<8>() {
37
+ accumulator = (accumulator ^ mix64(u64::from_le_bytes(*lane)))
47
38
  .rotate_left(27)
48
39
  .wrapping_mul(PRIME);
49
- cursor += 8;
40
+ rest = after;
50
41
  consumed += 8;
51
42
  }
52
43
 
44
+ // Fewer than eight bytes are left, so `shift` stays below 64.
53
45
  let mut tail: u64 = 0;
54
46
  let mut shift = 0;
55
- while cursor < bytes.len() {
56
- tail |= (bytes[cursor] as u64) << shift;
47
+ while let [byte, after @ ..] = rest {
48
+ tail |= (*byte as u64) << shift;
57
49
  shift += 8;
58
- cursor += 1;
50
+ rest = after;
59
51
  consumed += 1;
60
52
  }
61
53
 
@@ -1,23 +1,23 @@
1
1
  //! Distinct-count estimation in a fixed array of registers.
2
2
 
3
3
  use crate::hash::{hash64, u32_low_u8, u64_low_u16};
4
- use crate::{CodecError, TAG_HYPERLOGLOG};
4
+ use crate::{Refusal, TAG_HYPERLOGLOG, open_frame};
5
+ use sliderule_machines::ln_ratio;
5
6
 
6
- /// Odd terms of `2 * atanh(t) = ln((1 + t) / (1 - t))`, in Horner order.
7
- const ATANH_COEFFICIENTS: [f64; 5] = [2.0, 2.0 / 3.0, 0.4, 2.0 / 7.0, 2.0 / 9.0];
7
+ /// Fraction bits the linear-counting logarithm is taken with.
8
+ const LN_BITS: u32 = sliderule_machines::MAX_FRACTION_BITS;
8
9
 
9
10
  /// Bits of hash a sketch splits into a register index and a leading-zero count.
10
11
  const HASH_BITS: u32 = 64;
11
12
 
12
- const POW2_NEG: [f64; 65] = {
13
- let mut table = [1.0; 65];
14
- let mut exponent = 1;
15
- while exponent < 65 {
16
- table[exponent] = table[exponent - 1] * 0.5;
17
- exponent += 1;
18
- }
19
- table
20
- };
13
+ /// Tag and precision.
14
+ const HEADER_LEN: usize = 2;
15
+
16
+ /// `2^-exponent`, built from its bits: exact for every exponent the sketches
17
+ /// use (at most 64), the same value repeated halving of 1.0 gives.
18
+ const fn pow2_neg(exponent: u32) -> f64 {
19
+ f64::from_bits(((1023 - exponent) as u64) << 52)
20
+ }
21
21
 
22
22
  /// Counts distinct items in `M` bytes of state, however many items it sees.
23
23
  ///
@@ -27,6 +27,10 @@ const POW2_NEG: [f64; 65] = {
27
27
  /// leading-zero count, which fits in a byte, so the sketch is `M` bytes on the
28
28
  /// stack and never touches a heap.
29
29
  ///
30
+ /// Nothing here can refuse: [`add`](Self::add) and [`merge`](Self::merge) only
31
+ /// raise registers, so both are idempotent and neither has a limit to hit.
32
+ /// Only the codec answers a [`Refusal`].
33
+ ///
30
34
  /// ```
31
35
  /// use probabilistic_machines::HyperLogLog;
32
36
  ///
@@ -58,20 +62,29 @@ impl<const M: usize> HyperLogLog<M> {
58
62
  const MAX_RANK: u8 = u32_low_u8(HASH_BITS - Self::PRECISION + 1);
59
63
 
60
64
  /// Length of the [`encode`](Self::encode) frame.
61
- pub const ENCODED_LEN: usize = M + 2;
65
+ pub const ENCODED_LEN: usize = HEADER_LEN + M;
62
66
 
67
+ /// An empty sketch: every register zero.
63
68
  #[must_use]
64
69
  pub const fn new() -> Self {
65
70
  Self { registers: [0; M] }
66
71
  }
67
72
 
68
73
  /// Relative standard error of the estimate, `1.04 / sqrt(M)`.
69
- #[cfg(feature = "std")]
74
+ ///
75
+ /// `M` is a power of two, so the root is a power of two as well, times
76
+ /// `sqrt(2)` when the precision is odd: no `std` square root is needed.
70
77
  #[must_use]
71
- pub fn standard_error() -> f64 {
72
- 1.04 / f64::from(1_u32 << Self::PRECISION).sqrt()
78
+ pub const fn standard_error() -> f64 {
79
+ let halved = 1.04 * pow2_neg(Self::PRECISION / 2);
80
+ if Self::PRECISION % 2 == 1 {
81
+ halved * core::f64::consts::FRAC_1_SQRT_2
82
+ } else {
83
+ halved
84
+ }
73
85
  }
74
86
 
87
+ /// Counts `item`, hashed with [`hash64`].
75
88
  pub fn add(&mut self, item: &[u8]) {
76
89
  self.add_hash(hash64(item));
77
90
  }
@@ -79,13 +92,18 @@ impl<const M: usize> HyperLogLog<M> {
79
92
  /// Records an item the caller already hashed, for keys that never existed
80
93
  /// as bytes.
81
94
  pub fn add_hash(&mut self, hash: u64) {
95
+ // The top `PRECISION` bits of the hash: an index below `M`, so the
96
+ // lookup always lands.
82
97
  let index = usize::from(u64_low_u16(hash >> (HASH_BITS - Self::PRECISION)));
83
98
  let rank = rank(hash, Self::PRECISION);
84
- if self.registers[index] < rank {
85
- self.registers[index] = rank;
99
+ if let Some(register) = self.registers.get_mut(index)
100
+ && *register < rank
101
+ {
102
+ *register = rank;
86
103
  }
87
104
  }
88
105
 
106
+ /// Whether nothing was ever added: every register zero.
89
107
  #[must_use]
90
108
  pub fn is_empty(&self) -> bool {
91
109
  self.registers.iter().all(|&register| register == 0)
@@ -96,20 +114,35 @@ impl<const M: usize> HyperLogLog<M> {
96
114
  /// Under `2.5 * M` the register histogram is sparse enough that linear
97
115
  /// counting over the untouched registers beats the harmonic-mean
98
116
  /// estimator, so this switches to it.
117
+ ///
118
+ /// Linear counting is `M * ln(M / untouched)` over two integers, taken
119
+ /// with `sliderule_machines::ln_ratio` at 58 fraction bits: the logarithm
120
+ /// is within `3 * 2^-58` of the exact one before its one rounding to an
121
+ /// `f64`, and involves no floating-point series, so the same registers
122
+ /// give the same bits on every target. The harmonic-mean branch is sums,
123
+ /// products and one division of `f64`s, each correctly rounded by IEEE 754.
99
124
  #[must_use]
100
125
  pub fn estimate(&self) -> f64 {
126
+ // A register never holds more than `MAX_RANK` (at most 61), so every
127
+ // lookup lands; and `M <= 65536` registers keep each count far from
128
+ // overflow.
101
129
  let mut histogram = [0_u32; 65];
102
130
  for &register in &self.registers {
103
- histogram[usize::from(register)] += 1;
131
+ if let Some(count) = histogram.get_mut(usize::from(register)) {
132
+ *count += 1;
133
+ }
104
134
  }
105
135
 
106
136
  let mut registers = 0.0;
107
137
  let mut harmonic = 0.0;
108
- for (zeros, &count) in histogram.iter().enumerate() {
138
+ // `2^-zeros`, halved per bucket: exact, as every power is.
139
+ let mut weight = 1.0;
140
+ for &count in &histogram {
109
141
  let bucket = f64::from(count);
110
- let weighted = bucket * POW2_NEG[zeros];
142
+ let weighted = bucket * weight;
111
143
  registers += bucket;
112
144
  harmonic += weighted;
145
+ weight *= 0.5;
113
146
  }
114
147
 
115
148
  let alpha = match Self::PRECISION {
@@ -122,7 +155,7 @@ impl<const M: usize> HyperLogLog<M> {
122
155
  let untouched = f64::from(histogram[0]);
123
156
 
124
157
  if untouched > 0.0 && raw <= 2.5 * registers {
125
- registers * ln(registers / untouched)
158
+ linear_count(Self::PRECISION, histogram[0])
126
159
  } else {
127
160
  raw
128
161
  }
@@ -138,45 +171,25 @@ impl<const M: usize> HyperLogLog<M> {
138
171
  }
139
172
  }
140
173
 
141
- /// Writes the sketch into `out`, returning the number of bytes written.
142
- ///
143
- /// # Errors
144
- ///
145
- /// [`CodecError::Truncated`] when `out` is shorter than
146
- /// [`ENCODED_LEN`](Self::ENCODED_LEN).
147
- pub fn encode(&self, out: &mut [u8]) -> Result<usize, CodecError> {
148
- let Some(frame) = out.get_mut(..Self::ENCODED_LEN) else {
149
- return Err(CodecError::Truncated);
150
- };
151
- self.write_frame(frame);
152
- Ok(Self::ENCODED_LEN)
153
- }
154
-
155
- /// The sketch's frame, exactly [`ENCODED_LEN`](Self::ENCODED_LEN) bytes.
156
- #[cfg(feature = "alloc")]
157
- #[must_use]
158
- pub fn encoded(&self) -> alloc::boxed::Box<[u8]> {
159
- let mut frame = alloc::vec![0_u8; Self::ENCODED_LEN].into_boxed_slice();
160
- self.write_frame(&mut frame);
161
- frame
162
- }
174
+ encoders!("sketch");
163
175
 
164
176
  /// Fills a frame of exactly [`ENCODED_LEN`](Self::ENCODED_LEN) bytes.
165
- fn write_frame(&self, frame: &mut [u8]) {
166
- frame[0] = TAG_HYPERLOGLOG;
167
- frame[1] = u32_low_u8(Self::PRECISION);
168
- frame[2..].copy_from_slice(&self.registers);
177
+ fn write_frame(&self, header: &mut [u8; HEADER_LEN], body: &mut [u8]) {
178
+ *header = [TAG_HYPERLOGLOG, u32_low_u8(Self::PRECISION)];
179
+ for (byte, register) in body.iter_mut().zip(&self.registers) {
180
+ *byte = *register;
181
+ }
169
182
  }
170
183
 
171
184
  /// Reads a sketch written by [`encode`](Self::encode).
172
185
  ///
173
186
  /// # Errors
174
187
  ///
175
- /// [`CodecError::Truncated`] when `bytes` is too short, [`CodecError::Tag`]
176
- /// when it holds another structure, [`CodecError::Parameters`] when it was
177
- /// written with a different register count or holds a rank the hash tail
178
- /// its precision leaves cannot reach.
179
- pub fn decode(bytes: &[u8]) -> Result<Self, CodecError> {
188
+ /// [`Refusal::Truncated`] when `bytes` is too short, [`Refusal::WrongStructure`]
189
+ /// when it holds another structure, [`Refusal::WrongShape`] when it was
190
+ /// written with a different register count, [`Refusal::Malformed`] when
191
+ /// it holds a rank the hash tail its precision leaves cannot reach.
192
+ pub fn decode(bytes: &[u8]) -> Result<Self, Refusal> {
180
193
  let mut sketch = Self::new();
181
194
  sketch.decode_into(bytes)?;
182
195
  Ok(sketch)
@@ -190,24 +203,21 @@ impl<const M: usize> HyperLogLog<M> {
190
203
  /// # Errors
191
204
  ///
192
205
  /// The same as [`decode`](Self::decode).
193
- pub fn decode_into(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
194
- let Some(frame) = bytes.get(..Self::ENCODED_LEN) else {
195
- return Err(CodecError::Truncated);
196
- };
197
- if frame[0] != TAG_HYPERLOGLOG {
198
- return Err(CodecError::Tag);
199
- }
200
- if frame[1] != u32_low_u8(Self::PRECISION) {
201
- return Err(CodecError::Parameters);
206
+ pub fn decode_into(&mut self, bytes: &[u8]) -> Result<(), Refusal> {
207
+ let (&[_, precision], body) =
208
+ open_frame::<HEADER_LEN>(bytes, Self::ENCODED_LEN, TAG_HYPERLOGLOG)?;
209
+ if precision != u32_low_u8(Self::PRECISION) {
210
+ return Err(Refusal::WrongShape);
202
211
  }
203
- let mut index = 0;
204
- while index < M {
205
- if frame[2 + index] > Self::MAX_RANK {
206
- return Err(CodecError::Parameters);
207
- }
208
- index += 1;
212
+ // `open_frame` cut exactly `ENCODED_LEN` bytes, so the body is `M`
213
+ // registers long and this never refuses.
214
+ let Some(registers) = body.first_chunk::<M>() else {
215
+ return Err(Refusal::Truncated);
216
+ };
217
+ if registers.iter().any(|&register| register > Self::MAX_RANK) {
218
+ return Err(Refusal::Malformed);
209
219
  }
210
- self.registers.copy_from_slice(&frame[2..]);
220
+ self.registers = *registers;
211
221
  Ok(())
212
222
  }
213
223
  }
@@ -225,29 +235,31 @@ const fn rank(hash: u64, precision: u32) -> u8 {
225
235
  u32_low_u8(tail.leading_zeros() + 1)
226
236
  }
227
237
 
228
- /// Natural logarithm of a positive finite `x`, accurate to a few parts in
229
- /// `10^10`. `f64::ln` lives in `std`, and the linear-counting branch needs this
230
- /// on bare metal.
231
- fn ln(x: f64) -> f64 {
232
- let bits = x.to_bits();
233
- let mut mantissa = f64::from_bits((bits & 0x000F_FFFF_FFFF_FFFF) | 0x3FF0_0000_0000_0000);
234
- let mut exponent = f64::from(u64_low_u16((bits >> 52) & 0x7FF)) - 1023.0;
235
- if mantissa > core::f64::consts::SQRT_2 {
236
- mantissa *= 0.5;
237
- exponent += 1.0;
238
- }
239
-
240
- let t = (mantissa - 1.0) / (mantissa + 1.0);
241
- let square = t * t;
242
- let mut series = 0.0;
243
- for coefficient in ATANH_COEFFICIENTS.iter().rev() {
244
- let higher = series * square;
245
- series = coefficient + higher;
246
- }
247
-
248
- let scaled = exponent * core::f64::consts::LN_2;
249
- let odd = series * t;
250
- scaled + odd
238
+ /// `M * ln(M / untouched)` for `M = 2^precision` registers of which
239
+ /// `untouched` (`1..=M`) still hold zero.
240
+ ///
241
+ /// `ln_ratio` answers an interval around the exact `ln(M) - ln(untouched)`:
242
+ /// each factor's logarithm falls short by less than `3 * 2^-58`, so the
243
+ /// working value sits within `3 * 2^-58` of the exact one and the interval is
244
+ /// that value widened by three units on each side. Its midpoint is the
245
+ /// working value, at most `3 * 2^-58` off.
246
+ ///
247
+ /// The ratio is at least one, so the midpoint is never negative, and below
248
+ /// `ln(65536) * 2^58 < 2^62`, so its low 64 bits are all of it. Those split
249
+ /// into two `u32` halves that convert to `f64` exactly; their sum rounds once
250
+ /// (relative `2^-53`), and scaling by `2^-58` and by the power of two `M` is
251
+ /// exact. The result is within `M * (ln(M / untouched) * 2^-53 + 3 * 2^-58)`
252
+ /// of the real value: under `10^-10` items at 65536 registers, against a
253
+ /// documented error of `1.04 / sqrt(M)` of the estimate.
254
+ fn linear_count(precision: u32, untouched: u32) -> f64 {
255
+ let registers = 1_u64 << precision;
256
+ let ln = ln_ratio::<LN_BITS>(&[registers], &[u64::from(untouched)]);
257
+ let midpoint = i128::midpoint(ln.lo(), ln.hi()).max(0).cast_unsigned();
258
+ let [b0, b1, b2, b3, b4, b5, b6, b7, ..] = midpoint.to_le_bytes();
259
+ let low = f64::from(u32::from_le_bytes([b0, b1, b2, b3]));
260
+ let high = f64::from(u32::from_le_bytes([b4, b5, b6, b7]));
261
+ let scaled = (high * 4_294_967_296.0 + low) * pow2_neg(LN_BITS);
262
+ scaled * f64::from(1_u32 << precision)
251
263
  }
252
264
 
253
265
  #[cfg(test)]
@@ -1,13 +1,53 @@
1
- #![cfg_attr(not(feature = "std"), no_std)]
1
+ //! Sketches that answer questions about a stream in less memory than the
2
+ //! stream: `HyperLogLog`, count-min, cuckoo filter, heavy hitters and t-digest.
3
+ #![no_std]
4
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
2
5
 
3
6
  #[cfg(feature = "alloc")]
4
7
  extern crate alloc;
5
8
 
9
+ #[cfg(test)]
10
+ extern crate std;
11
+
6
12
  /// Compiles and runs the README's examples as doctests.
7
13
  #[cfg(doctest)]
8
14
  #[doc = include_str!("../README.md")]
9
15
  struct ReadmeDoctests;
10
16
 
17
+ /// Defines a fixed-size sketch's `encode` and `encoded` over its private
18
+ /// `write_frame`, which fills the header and body of a frame of exactly
19
+ /// `ENCODED_LEN` bytes. `$noun`
20
+ /// names the sketch in the docs; the `$about` pieces, joined, describe its
21
+ /// frame.
22
+ macro_rules! encoders {
23
+ ($noun:literal $(, $($about:literal),+)?) => {
24
+ #[doc = concat!("Writes the ", $noun, " into `out` and returns the bytes written.")]
25
+ $(
26
+ ///
27
+ #[doc = concat!($($about, " "),+)]
28
+ )?
29
+ ///
30
+ /// # Errors
31
+ ///
32
+ /// [`Refusal::Truncated`] when `out` is shorter than
33
+ /// [`ENCODED_LEN`](Self::ENCODED_LEN).
34
+ pub fn encode(&self, out: &mut [u8]) -> Result<usize, Refusal> {
35
+ $crate::encode_frame(out, Self::ENCODED_LEN, |header, body| {
36
+ self.write_frame(header, body);
37
+ })
38
+ }
39
+
40
+ #[doc = concat!("The ", $noun, "'s frame, [`ENCODED_LEN`](Self::ENCODED_LEN) bytes long.")]
41
+ #[cfg(feature = "alloc")]
42
+ #[must_use]
43
+ pub fn encoded(&self) -> alloc::boxed::Box<[u8]> {
44
+ $crate::encoded_frame(Self::ENCODED_LEN, |header, body| {
45
+ self.write_frame(header, body);
46
+ })
47
+ }
48
+ };
49
+ }
50
+
11
51
  pub mod countmin;
12
52
  pub mod cuckoo;
13
53
  pub mod hash;
@@ -18,36 +58,64 @@ pub mod topk;
18
58
  pub mod tdigest;
19
59
 
20
60
  pub use countmin::CountMinSketch;
21
- pub use cuckoo::CuckooFilter;
61
+ pub use cuckoo::{CuckooFilter, Removing};
22
62
  pub use hash::{hash64, mix64};
23
63
  pub use hyperloglog::HyperLogLog;
24
- pub use topk::HeavyHitters;
64
+ pub use topk::{HeavyHitters, Hitter};
25
65
 
26
66
  #[cfg(feature = "alloc")]
27
- pub use tdigest::TDigest;
67
+ pub use tdigest::{Centroid, MIN_COMPRESSION, TDigest};
28
68
 
29
- /// Why a sketch could not be read from or written to a byte buffer.
69
+ /// Why a call was not honoured. A refused call changed nothing.
70
+ ///
71
+ /// This is the crate's only refusal type; every operation that can refuse
72
+ /// answers `Result<_, Refusal>`.
30
73
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31
- pub enum CodecError {
32
- /// The buffer is shorter than the encoded form needs.
74
+ pub enum Refusal {
75
+ /// The buffer is shorter than the frame: the output of an `encode`, or the
76
+ /// input of a `decode`.
33
77
  Truncated,
34
- /// The leading byte names a different structure.
35
- Tag,
36
- /// The encoded shape does not match the target type's.
37
- Parameters,
78
+ /// The frame's leading tag byte names another structure.
79
+ WrongStructure,
80
+ /// The frame, or the sketch given to a `merge`, was built at another
81
+ /// shape: other const-generic parameters, or another digest compression.
82
+ WrongShape,
83
+ /// The frame has the right shape but holds contents no sequence of calls
84
+ /// could have produced.
85
+ Malformed,
86
+ /// A cuckoo filter found no free slot for the fingerprint, in its two
87
+ /// buckets or after 64 evictions.
88
+ Full,
89
+ /// A counter or a total would pass the largest value its type holds: a
90
+ /// `u32` count-min counter, a `u64` heavy-hitters counter or observation
91
+ /// count, or a digest's `f64` total weight becoming infinite.
92
+ Overflow,
93
+ /// A count of zero observes nothing, and on a heavy-hitters table would
94
+ /// still evict a tracked key.
95
+ ZeroCount,
96
+ /// A value or a weight given to a digest is NaN or infinite.
97
+ NotFinite,
98
+ /// A weight given to a digest is zero or negative.
99
+ InvalidWeight,
38
100
  }
39
101
 
40
- impl core::fmt::Display for CodecError {
102
+ impl core::fmt::Display for Refusal {
41
103
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42
104
  f.write_str(match self {
43
- Self::Truncated => "buffer too short",
44
- Self::Tag => "wrong structure tag",
45
- Self::Parameters => "shape mismatch",
105
+ Self::Truncated => "buffer shorter than the frame",
106
+ Self::WrongStructure => "the frame holds another structure",
107
+ Self::WrongShape => "the frame was written at another shape",
108
+ Self::Malformed => "the frame holds contents no sketch produces",
109
+ Self::Full => "no free slot for the fingerprint",
110
+ Self::Overflow => "a counter would overflow",
111
+ Self::ZeroCount => "a count of zero observes nothing",
112
+ Self::NotFinite => "a value or weight is not finite",
113
+ Self::InvalidWeight => "a weight is zero or negative",
46
114
  })
47
115
  }
48
116
  }
49
117
 
50
- impl core::error::Error for CodecError {}
118
+ impl core::error::Error for Refusal {}
51
119
 
52
120
  pub(crate) const TAG_HYPERLOGLOG: u8 = 0xA1;
53
121
  pub(crate) const TAG_TOPK: u8 = 0xB1;
@@ -56,10 +124,64 @@ pub(crate) const TAG_COUNTMIN: u8 = 0xC1;
56
124
  pub(crate) const TAG_TDIGEST: u8 = 0xD1;
57
125
  pub(crate) const TAG_CUCKOO: u8 = 0xF1;
58
126
 
59
- /// The first eight bytes of a field, for the little-endian scalars the frames
60
- /// are built from.
61
- pub(crate) const fn read8(bytes: &[u8]) -> [u8; 8] {
62
- let mut buffer = [0_u8; 8];
63
- buffer.copy_from_slice(bytes);
64
- buffer
127
+ /// Fills the first `len` bytes of `out` through `write`, handed the `H`-byte
128
+ /// header and the body after it, for the frames every sketch encodes to.
129
+ ///
130
+ /// # Errors
131
+ ///
132
+ /// [`Refusal::Truncated`] when `out` is shorter than `len`. Every frame is at
133
+ /// least its header long, so `len` never falls short of `H`; were it to, the
134
+ /// frame could not be written and the answer is the same refusal, with `out`
135
+ /// untouched.
136
+ pub(crate) fn encode_frame<const H: usize>(
137
+ out: &mut [u8],
138
+ len: usize,
139
+ write: impl FnOnce(&mut [u8; H], &mut [u8]),
140
+ ) -> Result<usize, Refusal> {
141
+ let Some((header, body)) = out
142
+ .get_mut(..len)
143
+ .and_then(<[u8]>::split_first_chunk_mut::<H>)
144
+ else {
145
+ return Err(Refusal::Truncated);
146
+ };
147
+ write(header, body);
148
+ Ok(len)
149
+ }
150
+
151
+ /// A freshly allocated `len`-byte frame filled through `write`, handed the
152
+ /// `H`-byte header and the body after it.
153
+ #[cfg(feature = "alloc")]
154
+ pub(crate) fn encoded_frame<const H: usize>(
155
+ len: usize,
156
+ write: impl FnOnce(&mut [u8; H], &mut [u8]),
157
+ ) -> alloc::boxed::Box<[u8]> {
158
+ let mut frame = alloc::vec![0_u8; len].into_boxed_slice();
159
+ if let Some((header, body)) = frame.split_first_chunk_mut::<H>() {
160
+ write(header, body);
161
+ } else {
162
+ // An all-zero frame carries no tag, so every decoder refuses it.
163
+ debug_assert!(false, "every frame is at least its header long");
164
+ }
165
+ frame
166
+ }
167
+
168
+ /// The `H`-byte header and the body of the first `len` bytes of `bytes`,
169
+ /// once they are known to be a frame tagged `tag`.
170
+ ///
171
+ /// # Errors
172
+ ///
173
+ /// [`Refusal::Truncated`] when `bytes` is shorter than `len` or than the
174
+ /// header, [`Refusal::WrongStructure`] when the tag names another structure.
175
+ pub(crate) fn open_frame<const H: usize>(
176
+ bytes: &[u8],
177
+ len: usize,
178
+ tag: u8,
179
+ ) -> Result<(&[u8; H], &[u8]), Refusal> {
180
+ let Some((header, body)) = bytes.get(..len).and_then(<[u8]>::split_first_chunk::<H>) else {
181
+ return Err(Refusal::Truncated);
182
+ };
183
+ if header.first() != Some(&tag) {
184
+ return Err(Refusal::WrongStructure);
185
+ }
186
+ Ok((header, body))
65
187
  }