probabilistic_machines 0.1.4 → 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.
@@ -2,13 +2,13 @@
2
2
 
3
3
  use std::cell::RefCell;
4
4
 
5
- use bytes::Bytes;
6
- use magnus::scan_args::scan_args;
7
5
  use magnus::typed_data::Obj;
8
- use magnus::{Error, RHash, RModule, RString, Ruby, Value, function, method, prelude::*};
9
- use probabilistic_machines::{CodecError, HyperLogLog};
6
+ use magnus::{Error, RModule, RString, Ruby, Value, function, method, prelude::*};
7
+ use matryona_machines::ruby::integer;
8
+ use probabilistic_machines::{HyperLogLog, Refusal};
10
9
 
11
- use crate::{Whole, codec_error, mismatch, required_kwarg, unsupported, unsupported_blob};
10
+ use crate::data::bytes;
11
+ use crate::{Pinned, answer, decoded_or_refused, define_class, partner, pin, sizes, unsupported};
12
12
 
13
13
  /// Register counts [`Sketch`] is monomorphised for.
14
14
  const REGISTERS: [usize; 4] = [1024, 4096, 16384, 65536];
@@ -33,6 +33,9 @@ macro_rules! sketch {
33
33
  };
34
34
  }
35
35
 
36
+ /// The class, pinned at init.
37
+ static CLASS: Pinned = Pinned::new("probabilistic_machines");
38
+
36
39
  #[magnus::wrap(class = "ProbabilisticMachines::HyperLogLog", free_immediately, size)]
37
40
  struct Wrapper(RefCell<Sketch>);
38
41
 
@@ -40,7 +43,7 @@ const fn registers_of<const M: usize>(_: &HyperLogLog<M>) -> usize {
40
43
  M
41
44
  }
42
45
 
43
- fn standard_error_of<const M: usize>(_: &HyperLogLog<M>) -> f64 {
46
+ const fn standard_error_of<const M: usize>(_: &HyperLogLog<M>) -> f64 {
44
47
  HyperLogLog::<M>::standard_error()
45
48
  }
46
49
 
@@ -52,52 +55,71 @@ fn boxed_new<const N: usize>() -> Box<HyperLogLog<N>> {
52
55
  }
53
56
 
54
57
  #[inline(never)]
55
- fn boxed_decode<const N: usize>(ruby: &Ruby, frame: &[u8]) -> Result<Box<HyperLogLog<N>>, Error> {
58
+ fn boxed_decode<const N: usize>(frame: &[u8]) -> Result<Box<HyperLogLog<N>>, Refusal> {
56
59
  let mut sketch = boxed_new::<N>();
57
- sketch
58
- .decode_into(frame)
59
- .map_err(|error| codec_error(ruby, error))?;
60
+ sketch.decode_into(frame)?;
60
61
  Ok(sketch)
61
62
  }
62
63
 
64
+ /// The sketch a frame holds. A precision this build does not carry is read
65
+ /// as the smallest shape it does, which answers exactly what the core answers
66
+ /// a type of another shape: `Truncated`, `WrongStructure` or `WrongShape`.
67
+ fn decoded(frame: &[u8]) -> Result<Sketch, Refusal> {
68
+ Ok(match frame.get(1) {
69
+ Some(12) => Sketch::M4096(boxed_decode(frame)?),
70
+ Some(14) => Sketch::M16384(boxed_decode(frame)?),
71
+ Some(16) => Sketch::M65536(boxed_decode(frame)?),
72
+ Some(_) | None => Sketch::M1024(boxed_decode(frame)?),
73
+ })
74
+ }
75
+
63
76
  impl Wrapper {
64
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
65
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
66
- let Whole(registers): Whole<usize> = required_kwarg(args.keywords, "registers")?;
77
+ /// `HyperLogLog.new(registers)`. `RangeError` outside [`REGISTERS`].
78
+ fn new(ruby: &Ruby, registers: Value) -> Result<Self, Error> {
79
+ let registers: usize = integer(registers, "registers")?;
67
80
  let sketch = match registers {
68
- 1024 => Sketch::M1024(boxed_new::<1024>()),
69
- 4096 => Sketch::M4096(boxed_new::<4096>()),
70
- 16384 => Sketch::M16384(boxed_new::<16384>()),
71
- 65536 => Sketch::M65536(boxed_new::<65536>()),
81
+ 1024 => Sketch::M1024(boxed_new()),
82
+ 4096 => Sketch::M4096(boxed_new()),
83
+ 16384 => Sketch::M16384(boxed_new()),
84
+ 65536 => Sketch::M65536(boxed_new()),
72
85
  _ => return Err(unsupported(ruby, "registers", registers, &REGISTERS)),
73
86
  };
74
87
  Ok(Self(RefCell::new(sketch)))
75
88
  }
76
89
 
77
- fn load(ruby: &Ruby, blob: Bytes) -> Result<Self, Error> {
78
- let Some(&precision) = blob.get(1) else {
79
- return Err(codec_error(ruby, CodecError::Truncated));
80
- };
81
- let sketch = match precision {
82
- 10 => Sketch::M1024(boxed_decode::<1024>(ruby, &blob)?),
83
- 12 => Sketch::M4096(boxed_decode::<4096>(ruby, &blob)?),
84
- 14 => Sketch::M16384(boxed_decode::<16384>(ruby, &blob)?),
85
- 16 => Sketch::M65536(boxed_decode::<65536>(ruby, &blob)?),
86
- _ => return Err(unsupported_blob(ruby, "register count", &REGISTERS)),
87
- };
88
- Ok(Self(RefCell::new(sketch)))
90
+ /// `HyperLogLog.decode(bytes)`: a sketch, or the refusal symbol.
91
+ fn decode(ruby: &Ruby, bytes: Value) -> Result<Value, Error> {
92
+ let bytes = self::bytes(bytes, "bytes")?;
93
+ Ok(decoded_or_refused(
94
+ ruby,
95
+ decoded(&bytes).map(|held| Self(RefCell::new(held))),
96
+ ))
97
+ }
98
+
99
+ fn decode_into(ruby: &Ruby, this: Obj<Self>, bytes: Value) -> Result<Value, Error> {
100
+ this.check_frozen()?;
101
+ let bytes = self::bytes(bytes, "bytes")?;
102
+ let outcome = sketch!(&mut *this.0.borrow_mut(), |sketch| sketch
103
+ .decode_into(&bytes));
104
+ Ok(answer(ruby, outcome, "decoded"))
89
105
  }
90
106
 
91
107
  fn registers(&self) -> usize {
92
108
  sketch!(&*self.0.borrow(), |sketch| registers_of(&**sketch))
93
109
  }
94
110
 
95
- fn add(&self, item: Bytes) {
96
- sketch!(&mut *self.0.borrow_mut(), |sketch| sketch.add(&item));
111
+ fn add(this: Obj<Self>, item: Value) -> Result<(), Error> {
112
+ this.check_frozen()?;
113
+ let item = bytes(item, "item")?;
114
+ sketch!(&mut *this.0.borrow_mut(), |sketch| sketch.add(&item));
115
+ Ok(())
97
116
  }
98
117
 
99
- fn add_hash(&self, Whole(hash): Whole<u64>) {
100
- sketch!(&mut *self.0.borrow_mut(), |sketch| sketch.add_hash(hash));
118
+ fn add_hash(this: Obj<Self>, hash: Value) -> Result<(), Error> {
119
+ this.check_frozen()?;
120
+ let hash: u64 = integer(hash, "hash")?;
121
+ sketch!(&mut *this.0.borrow_mut(), |sketch| sketch.add_hash(hash));
122
+ Ok(())
101
123
  }
102
124
 
103
125
  fn estimate(&self) -> f64 {
@@ -112,20 +134,39 @@ impl Wrapper {
112
134
  sketch!(&*self.0.borrow(), |sketch| sketch.is_empty())
113
135
  }
114
136
 
115
- fn merge(ruby: &Ruby, rb_self: Obj<Self>, other: &Self) -> Result<Obj<Self>, Error> {
137
+ /// `:merged`, or `:wrong_shape` for a sketch of another register count
138
+ /// (in Rust that merge does not compile).
139
+ fn merge(ruby: &Ruby, this: Obj<Self>, other: Value) -> Result<Value, Error> {
140
+ this.check_frozen()?;
141
+ let other: Obj<Self> = partner(ruby, &CLASS, other)?;
116
142
  let source = other.0.borrow().clone();
117
- match (&mut *rb_self.0.borrow_mut(), &source) {
118
- (Sketch::M1024(target), Sketch::M1024(source)) => target.merge(source),
119
- (Sketch::M4096(target), Sketch::M4096(source)) => target.merge(source),
120
- (Sketch::M16384(target), Sketch::M16384(source)) => target.merge(source),
121
- (Sketch::M65536(target), Sketch::M65536(source)) => target.merge(source),
122
- _ => return Err(mismatch(ruby, "sketch")),
123
- }
124
- Ok(rb_self)
143
+ let merged = match (&mut *this.0.borrow_mut(), &source) {
144
+ (Sketch::M1024(target), Sketch::M1024(source)) => {
145
+ target.merge(source);
146
+ Ok(())
147
+ }
148
+ (Sketch::M4096(target), Sketch::M4096(source)) => {
149
+ target.merge(source);
150
+ Ok(())
151
+ }
152
+ (Sketch::M16384(target), Sketch::M16384(source)) => {
153
+ target.merge(source);
154
+ Ok(())
155
+ }
156
+ (Sketch::M65536(target), Sketch::M65536(source)) => {
157
+ target.merge(source);
158
+ Ok(())
159
+ }
160
+ (
161
+ Sketch::M1024(_) | Sketch::M4096(_) | Sketch::M16384(_) | Sketch::M65536(_),
162
+ Sketch::M1024(_) | Sketch::M4096(_) | Sketch::M16384(_) | Sketch::M65536(_),
163
+ ) => Err(Refusal::WrongShape),
164
+ };
165
+ Ok(answer(ruby, merged, "merged"))
125
166
  }
126
167
 
127
- fn dump(ruby: &Ruby, rb_self: &Self) -> RString {
128
- let frame = sketch!(&*rb_self.0.borrow(), |sketch| sketch.encoded());
168
+ fn encoded(ruby: &Ruby, this: &Self) -> RString {
169
+ let frame = sketch!(&*this.0.borrow(), |sketch| sketch.encoded());
129
170
  ruby.str_from_slice(&frame)
130
171
  }
131
172
 
@@ -139,9 +180,11 @@ impl Wrapper {
139
180
  }
140
181
 
141
182
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
142
- let class = module.define_class("HyperLogLog", ruby.class_object())?;
143
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
144
- class.define_singleton_method("load", function!(Wrapper::load, 1))?;
183
+ let class = define_class(ruby, module, "HyperLogLog")?;
184
+ class.const_set("REGISTERS", sizes(ruby, &REGISTERS))?;
185
+ class.define_singleton_method("new", function!(Wrapper::new, 1))?;
186
+ class.define_singleton_method("decode", function!(Wrapper::decode, 1))?;
187
+ class.define_method("decode_into", method!(Wrapper::decode_into, 1))?;
145
188
  class.define_method("registers", method!(Wrapper::registers, 0))?;
146
189
  class.define_method("add", method!(Wrapper::add, 1))?;
147
190
  class.define_method("add_hash", method!(Wrapper::add_hash, 1))?;
@@ -149,7 +192,7 @@ pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
149
192
  class.define_method("standard_error", method!(Wrapper::standard_error, 0))?;
150
193
  class.define_method("empty?", method!(Wrapper::is_empty, 0))?;
151
194
  class.define_method("merge", method!(Wrapper::merge, 1))?;
152
- class.define_method("dump", method!(Wrapper::dump, 0))?;
195
+ class.define_method("encoded", method!(Wrapper::encoded, 0))?;
153
196
  class.define_method("inspect", method!(Wrapper::inspect, 0))?;
154
- Ok(())
197
+ pin::<Wrapper>(ruby, class, &CLASS)
155
198
  }
@@ -0,0 +1,15 @@
1
+ //! Private native entry point.
2
+ use magnus::{Error, Ruby};
3
+
4
+ use crate::{countmin, cuckoo, data, hyperloglog, tdigest, topk};
5
+
6
+ #[magnus::init]
7
+ fn init(ruby: &Ruby) -> Result<(), Error> {
8
+ let module = ruby.define_module("ProbabilisticMachines")?;
9
+ data::define(ruby, module)?;
10
+ hyperloglog::define(ruby, module)?;
11
+ countmin::define(ruby, module)?;
12
+ tdigest::define(ruby, module)?;
13
+ cuckoo::define(ruby, module)?;
14
+ topk::define(ruby, module)
15
+ }
@@ -1,140 +1,105 @@
1
1
  //! Ruby bindings for the `probabilistic-machines` sketches.
2
2
  //!
3
3
  //! Every sketch is sized by a const generic, so each class dispatches the size
4
- //! it is given to a fixed set of monomorphised variants and raises
5
- //! `ArgumentError` for any other size.
6
-
7
- #![allow(clippy::needless_pass_by_value)]
4
+ //! it is given to a fixed set of monomorphised variants, listed in a class
5
+ //! constant, and raises `RangeError` for any other size. Refusals come back as
6
+ //! the `snake_case` symbol of the core's `Refusal` variant and never raise.
8
7
 
9
8
  mod countmin;
10
9
  mod cuckoo;
11
10
  mod data;
12
11
  mod hyperloglog;
12
+ mod init;
13
13
  mod tdigest;
14
14
  mod topk;
15
15
 
16
- use std::sync::OnceLock;
17
-
18
- use magnus::scan_args::get_kwargs;
19
- use magnus::value::Opaque;
20
- use magnus::{Error, ExceptionClass, Integer, RHash, RModule, Ruby, TryConvert, Value, prelude::*};
21
- use probabilistic_machines::CodecError;
22
-
23
- /// `ProbabilisticMachines::Full`, defined in [`init`].
24
- static FULL: OnceLock<Opaque<ExceptionClass>> = OnceLock::new();
25
-
26
- /// A whole number of things: a count, a width, a depth, a `k`, a hash.
27
- ///
28
- /// magnus reads an integer through Ruby's `NUM2*` family, which truncates a
29
- /// `Float` towards zero instead of refusing it, so an argument that means an
30
- /// integer is read as one of these and anything but an `Integer` is turned
31
- /// away. An `Integer` outside the target width still comes back as the
32
- /// `RangeError` magnus raises for it.
33
- pub(crate) struct Whole<T>(pub(crate) T);
34
-
35
- impl<T: TryConvert> TryConvert for Whole<T> {
36
- fn try_convert(value: Value) -> Result<Self, Error> {
37
- if Integer::from_value(value).is_none() {
38
- return Err(not_whole(value));
39
- }
40
- T::try_convert(value).map(Self)
16
+ use magnus::{Error, RArray, RClass, RModule, Ruby, TypedData, Value, prelude::*, typed_data::Obj};
17
+ use matryona_machines::ruby::{Class, Registry, Symbols, class_name, exact_typed_with, symbol};
18
+ use probabilistic_machines::Refusal;
19
+
20
+ matryona_machines::symbols! {
21
+ /// The core's refusals, each the snake case of its variant.
22
+ Refusals for Refusal as "a refusal" {
23
+ Truncated => "truncated",
24
+ WrongStructure => "wrong_structure",
25
+ WrongShape => "wrong_shape",
26
+ Malformed => "malformed",
27
+ Full => "full",
28
+ Overflow => "overflow",
29
+ ZeroCount => "zero_count",
30
+ NotFinite => "not_finite",
31
+ InvalidWeight => "invalid_weight",
41
32
  }
42
33
  }
43
34
 
44
- fn not_whole(value: Value) -> Error {
45
- let ruby = Ruby::get_with(value);
46
- Error::new(
47
- ruby.exception_type_error(),
48
- format!(
49
- "no implicit conversion of {} into Integer: {}",
50
- value.class(),
51
- value.inspect()
52
- ),
53
- )
54
- }
55
-
56
- /// The one required keyword of a constructor.
57
- pub(crate) fn required_kwarg<T: TryConvert>(keywords: RHash, name: &str) -> Result<T, Error> {
58
- Ok(get_kwargs::<_, (T,), (), ()>(keywords, &[name], &[])?
59
- .required
60
- .0)
61
- }
62
-
63
- /// A keyword with a default the caller may leave out.
64
- pub(crate) fn optional_kwarg<T: TryConvert>(
65
- keywords: RHash,
66
- name: &str,
67
- ) -> Result<Option<T>, Error> {
68
- Ok(
69
- get_kwargs::<_, (), (Option<T>,), ()>(keywords, &[], &[name])?
70
- .optional
71
- .0,
72
- )
35
+ /// Ruby symbol of a refusal: the snake case of the core variant.
36
+ pub(crate) fn refusal(ruby: &Ruby, refused: Refusal) -> Value {
37
+ Refusals::symbol(ruby, refused).as_value()
73
38
  }
74
39
 
75
- pub(crate) fn unsupported(ruby: &Ruby, name: &str, given: usize, supported: &[usize]) -> Error {
76
- Error::new(
77
- ruby.exception_arg_error(),
78
- format!("{name} {given} is not supported, expected one of {supported:?}"),
79
- )
40
+ /// A sketch class the binding defined, pinned at init so a merge can check
41
+ /// its partner's exact class without looking it up by name.
42
+ pub(crate) type Pinned = Registry<Class>;
43
+
44
+ /// The other operand of a merge: a `T` that is an instance of exactly the
45
+ /// class pinned in `held`, never a subclass instance. `TypeError` otherwise,
46
+ /// naming that class and the one received.
47
+ pub(crate) fn partner<T: TypedData>(
48
+ ruby: &Ruby,
49
+ held: &Pinned,
50
+ other: Value,
51
+ ) -> Result<Obj<T>, Error> {
52
+ let class = held.get(ruby)?.get(ruby);
53
+ exact_typed_with(ruby, other, class, || {
54
+ format!("other must be a {class}, not {}", class_name(other))
55
+ })
80
56
  }
81
57
 
82
- pub(crate) fn unsupported_blob(ruby: &Ruby, name: &str, supported: &[usize]) -> Error {
83
- Error::new(
84
- ruby.exception_arg_error(),
85
- format!("blob was written with a {name} outside {supported:?}"),
86
- )
87
- }
88
-
89
- pub(crate) fn codec_error(ruby: &Ruby, error: CodecError) -> Error {
90
- Error::new(ruby.exception_arg_error(), format!("codec: {error}"))
91
- }
92
-
93
- pub(crate) fn mismatch(ruby: &Ruby, name: &str) -> Error {
94
- Error::new(
95
- ruby.exception_arg_error(),
96
- format!("the other {name} has a different shape"),
97
- )
58
+ /// The object a `decode` built, or the refusal symbol when its frame was
59
+ /// refused.
60
+ pub(crate) fn decoded_or_refused<T: TypedData>(ruby: &Ruby, outcome: Result<T, Refusal>) -> Value {
61
+ match outcome {
62
+ Ok(object) => ruby.obj_wrap(object).as_value(),
63
+ Err(refused) => refusal(ruby, refused),
64
+ }
98
65
  }
99
66
 
100
- pub(crate) fn uninitialised(ruby: &Ruby) -> Error {
101
- Error::new(
102
- ruby.exception_runtime_error(),
103
- "the probabilistic_machines extension is not initialised",
104
- )
67
+ /// `honoured` as a symbol when the call was honoured, its refusal otherwise.
68
+ pub(crate) fn answer(ruby: &Ruby, outcome: Result<(), Refusal>, honoured: &str) -> Value {
69
+ match outcome {
70
+ Ok(()) => symbol(ruby, honoured).as_value(),
71
+ Err(refused) => refusal(ruby, refused),
72
+ }
105
73
  }
106
74
 
107
- pub(crate) fn defined_twice(ruby: &Ruby, name: &str) -> Error {
75
+ /// A size this build carries no monomorphised variant for: rejected
76
+ /// configuration, so `RangeError`.
77
+ pub(crate) fn unsupported(ruby: &Ruby, name: &str, given: usize, supported: &[usize]) -> Error {
108
78
  Error::new(
109
- ruby.exception_runtime_error(),
110
- format!("ProbabilisticMachines::{name} was initialised twice"),
79
+ ruby.exception_range_error(),
80
+ format!("{name} {given} is not supported, expected one of {supported:?}"),
111
81
  )
112
82
  }
113
83
 
114
- /// `ProbabilisticMachines::Full`, raised when a cuckoo filter cannot place an
115
- /// item after relocating its neighbours.
116
- pub(crate) fn full(ruby: &Ruby) -> Error {
117
- FULL.get().map_or_else(
118
- || uninitialised(ruby),
119
- |class| Error::new(ruby.get_inner(*class), "the filter is full"),
120
- )
84
+ /// The supported sizes as a frozen Array, for a class constant.
85
+ pub(crate) fn sizes(ruby: &Ruby, supported: &[usize]) -> RArray {
86
+ let array = ruby.ary_from_iter(supported.iter().copied());
87
+ array.freeze();
88
+ array
121
89
  }
122
90
 
123
- fn define_errors(ruby: &Ruby, module: RModule) -> Result<(), Error> {
124
- let base = module.define_error("Error", ruby.exception_standard_error())?;
125
- let full = module.define_error("Full", base)?;
126
- FULL.set(full.into())
127
- .map_err(|_| defined_twice(ruby, "Full"))
91
+ /// Defines `name` under `module` with no allocator of its own, so
92
+ /// `Class#allocate` cannot hand out an object the core never built.
93
+ pub(crate) fn define_class(ruby: &Ruby, module: RModule, name: &str) -> Result<RClass, Error> {
94
+ let class = module.define_class(name, ruby.class_object())?;
95
+ class.undef_default_alloc_func();
96
+ Ok(class)
128
97
  }
129
98
 
130
- #[magnus::init]
131
- fn init(ruby: &Ruby) -> Result<(), Error> {
132
- let module = ruby.define_module("ProbabilisticMachines")?;
133
- define_errors(ruby, module)?;
134
- data::define(ruby, module)?;
135
- hyperloglog::define(ruby, module)?;
136
- countmin::define(ruby, module)?;
137
- tdigest::define(ruby, module)?;
138
- cuckoo::define(ruby, module)?;
139
- topk::define(ruby, module)
99
+ /// Pins `class` into `held` (no lookup back by name) and fixes magnus's class
100
+ /// for the wrapped `T` to it: building a `T` never runs `Object.const_get`
101
+ /// later. Called from init once the class and its methods are defined.
102
+ pub(crate) fn pin<T: TypedData>(ruby: &Ruby, class: RClass, held: &Pinned) -> Result<(), Error> {
103
+ held.set(ruby, Class::pin_wrapped::<T>(ruby, class)?)
104
+ .map(drop)
140
105
  }