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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +70 -0
- data/Cargo.lock +22 -3
- data/Cargo.toml +2 -0
- data/README.md +166 -58
- data/ext/probabilistic_machines_native/core/Cargo.toml +10 -5
- data/ext/probabilistic_machines_native/core/src/countmin.rs +117 -99
- data/ext/probabilistic_machines_native/core/src/cuckoo.rs +109 -81
- data/ext/probabilistic_machines_native/core/src/hash.rs +9 -17
- data/ext/probabilistic_machines_native/core/src/hyperloglog.rs +104 -92
- data/ext/probabilistic_machines_native/core/src/lib.rs +144 -22
- data/ext/probabilistic_machines_native/core/src/tdigest.rs +175 -90
- data/ext/probabilistic_machines_native/core/src/topk.rs +253 -126
- data/ext/probabilistic_machines_native/ffi/Cargo.toml +5 -11
- data/ext/probabilistic_machines_native/ffi/src/countmin.rs +111 -70
- data/ext/probabilistic_machines_native/ffi/src/cuckoo.rs +102 -44
- data/ext/probabilistic_machines_native/ffi/src/data.rs +102 -55
- data/ext/probabilistic_machines_native/ffi/src/hyperloglog.rs +92 -49
- data/ext/probabilistic_machines_native/ffi/src/init.rs +15 -0
- data/ext/probabilistic_machines_native/ffi/src/lib.rs +74 -109
- data/ext/probabilistic_machines_native/ffi/src/tdigest.rs +91 -90
- data/ext/probabilistic_machines_native/ffi/src/topk.rs +181 -136
- data/lib/probabilistic_machines/version.rb +1 -1
- data/lib/probabilistic_machines.rb +40 -2
- data/sig/probabilistic_machines.rbs +129 -56
- metadata +2 -1
|
@@ -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
|
|
34
|
+
let mut rest = bytes;
|
|
34
35
|
|
|
35
|
-
while
|
|
36
|
-
|
|
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
|
-
|
|
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
|
|
56
|
-
tail |= (
|
|
47
|
+
while let [byte, after @ ..] = rest {
|
|
48
|
+
tail |= (*byte as u64) << shift;
|
|
57
49
|
shift += 8;
|
|
58
|
-
|
|
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::{
|
|
4
|
+
use crate::{Refusal, TAG_HYPERLOGLOG, open_frame};
|
|
5
|
+
use sliderule_machines::ln_ratio;
|
|
5
6
|
|
|
6
|
-
///
|
|
7
|
-
const
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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 =
|
|
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
|
-
|
|
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
|
|
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
|
|
85
|
-
|
|
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(|®ister| 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 ®ister in &self.registers {
|
|
103
|
-
histogram
|
|
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
|
-
|
|
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 *
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
-
/// [`
|
|
176
|
-
/// when it holds another structure, [`
|
|
177
|
-
/// written with a different register count
|
|
178
|
-
/// its precision leaves cannot reach.
|
|
179
|
-
pub fn decode(bytes: &[u8]) -> Result<Self,
|
|
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<(),
|
|
194
|
-
let
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
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(|®ister| register > Self::MAX_RANK) {
|
|
218
|
+
return Err(Refusal::Malformed);
|
|
209
219
|
}
|
|
210
|
-
self.registers
|
|
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
|
-
///
|
|
229
|
-
/// `
|
|
230
|
-
///
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
let
|
|
249
|
-
let
|
|
250
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
32
|
-
/// The buffer is shorter than the
|
|
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
|
|
35
|
-
|
|
36
|
-
/// The
|
|
37
|
-
|
|
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
|
|
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
|
|
44
|
-
Self::
|
|
45
|
-
Self::
|
|
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
|
|
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
|
-
///
|
|
60
|
-
///
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
}
|