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.
@@ -2,21 +2,22 @@
2
2
 
3
3
  use std::cell::RefCell;
4
4
 
5
- use bytes::Bytes;
6
- use magnus::scan_args::{get_kwargs, 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, CountMinSketch};
6
+ use magnus::{Error, RModule, RString, Ruby, Value, function, method, prelude::*};
7
+ use matryona_machines::ruby::integer;
8
+ use probabilistic_machines::{CountMinSketch, Refusal};
10
9
 
11
- use crate::{Whole, codec_error, mismatch, optional_kwarg, unsupported};
10
+ use crate::data::bytes;
11
+ use crate::{Pinned, answer, decoded_or_refused, define_class, partner, pin, sizes, unsupported};
12
12
 
13
13
  /// Row widths [`Sketch`] is monomorphised for.
14
14
  ///
15
15
  /// Capped so the widest sketch is 128 KiB. The core returns by value, so a
16
16
  /// wider shape could not be built on Ruby's 256 KiB fiber stack without an
17
- /// in-place constructor, and that needs `unsafe`.
17
+ /// in-place constructor, which safe Rust cannot write.
18
18
  const WIDTHS: [usize; 2] = [1024, 4096];
19
- /// Row counts [`Sketch`] is monomorphised for.
19
+ /// Row counts [`Sketch`] is monomorphised for. Every width pairs with every
20
+ /// depth.
20
21
  const DEPTHS: [usize; 2] = [4, 8];
21
22
 
22
23
  #[derive(Clone)]
@@ -39,6 +40,9 @@ macro_rules! sketch {
39
40
  };
40
41
  }
41
42
 
43
+ /// The class, pinned at init.
44
+ static CLASS: Pinned = Pinned::new("probabilistic_machines");
45
+
42
46
  #[magnus::wrap(
43
47
  class = "ProbabilisticMachines::CountMinSketch",
44
48
  free_immediately,
@@ -63,55 +67,58 @@ fn boxed_new<const W: usize, const D: usize>() -> Box<CountMinSketch<W, D>> {
63
67
 
64
68
  #[inline(never)]
65
69
  fn boxed_decode<const W: usize, const D: usize>(
66
- ruby: &Ruby,
67
70
  frame: &[u8],
68
- ) -> Result<Box<CountMinSketch<W, D>>, Error> {
71
+ ) -> Result<Box<CountMinSketch<W, D>>, Refusal> {
69
72
  let mut sketch = boxed_new::<W, D>();
70
- sketch
71
- .decode_into(frame)
72
- .map_err(|error| codec_error(ruby, error))?;
73
+ sketch.decode_into(frame)?;
73
74
  Ok(sketch)
74
75
  }
75
76
 
77
+ /// The sketch a frame holds. A shape this build does not carry is read as the
78
+ /// smallest one it does, which answers exactly what the core answers a type of
79
+ /// another shape: `Truncated`, `WrongStructure` or `WrongShape`.
80
+ fn decoded(frame: &[u8]) -> Result<Sketch, Refusal> {
81
+ Ok(match (frame.get(1), frame.get(2)) {
82
+ (Some(10), Some(8)) => Sketch::W1024D8(boxed_decode(frame)?),
83
+ (Some(12), Some(4)) => Sketch::W4096D4(boxed_decode(frame)?),
84
+ (Some(12), Some(8)) => Sketch::W4096D8(boxed_decode(frame)?),
85
+ (Some(_) | None, Some(_) | None) => Sketch::W1024D4(boxed_decode(frame)?),
86
+ })
87
+ }
88
+
76
89
  impl Wrapper {
77
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
78
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
79
- let (Whole(width), Whole(depth)) = get_kwargs::<_, (Whole<usize>, Whole<usize>), (), ()>(
80
- args.keywords,
81
- &["width", "depth"],
82
- &[],
83
- )?
84
- .required;
85
- if !DEPTHS.contains(&depth) {
86
- return Err(unsupported(ruby, "depth", depth, &DEPTHS));
90
+ /// `CountMinSketch.new(width, depth)`. `RangeError` outside [`WIDTHS`] by
91
+ /// [`DEPTHS`].
92
+ fn new(ruby: &Ruby, width: Value, depth: Value) -> Result<Self, Error> {
93
+ let (width, depth): (usize, usize) = (integer(width, "width")?, integer(depth, "depth")?);
94
+ if !WIDTHS.contains(&width) {
95
+ return Err(unsupported(ruby, "width", width, &WIDTHS));
87
96
  }
88
97
  let sketch = match (width, depth) {
89
- (1024, 4) => Sketch::W1024D4(boxed_new::<1024, 4>()),
90
- (1024, 8) => Sketch::W1024D8(boxed_new::<1024, 8>()),
91
- (4096, 4) => Sketch::W4096D4(boxed_new::<4096, 4>()),
92
- (4096, 8) => Sketch::W4096D8(boxed_new::<4096, 8>()),
93
- _ => return Err(unsupported(ruby, "width", width, &WIDTHS)),
98
+ (1024, 4) => Sketch::W1024D4(boxed_new()),
99
+ (1024, 8) => Sketch::W1024D8(boxed_new()),
100
+ (4096, 4) => Sketch::W4096D4(boxed_new()),
101
+ (4096, 8) => Sketch::W4096D8(boxed_new()),
102
+ _ => return Err(unsupported(ruby, "depth", depth, &DEPTHS)),
94
103
  };
95
104
  Ok(Self(RefCell::new(sketch)))
96
105
  }
97
106
 
98
- fn load(ruby: &Ruby, blob: Bytes) -> Result<Self, Error> {
99
- let Some(shape) = blob.get(1..3) else {
100
- return Err(codec_error(ruby, CodecError::Truncated));
101
- };
102
- let sketch = match (shape[0], shape[1]) {
103
- (10, 4) => Sketch::W1024D4(boxed_decode::<1024, 4>(ruby, &blob)?),
104
- (10, 8) => Sketch::W1024D8(boxed_decode::<1024, 8>(ruby, &blob)?),
105
- (12, 4) => Sketch::W4096D4(boxed_decode::<4096, 4>(ruby, &blob)?),
106
- (12, 8) => Sketch::W4096D8(boxed_decode::<4096, 8>(ruby, &blob)?),
107
- _ => {
108
- return Err(Error::new(
109
- ruby.exception_arg_error(),
110
- format!("blob was written with a shape outside {WIDTHS:?} x {DEPTHS:?}"),
111
- ));
112
- }
113
- };
114
- Ok(Self(RefCell::new(sketch)))
107
+ /// `CountMinSketch.decode(bytes)`: a sketch, or the refusal symbol.
108
+ fn decode(ruby: &Ruby, bytes: Value) -> Result<Value, Error> {
109
+ let bytes = self::bytes(bytes, "bytes")?;
110
+ Ok(decoded_or_refused(
111
+ ruby,
112
+ decoded(&bytes).map(|held| Self(RefCell::new(held))),
113
+ ))
114
+ }
115
+
116
+ fn decode_into(ruby: &Ruby, this: Obj<Self>, bytes: Value) -> Result<Value, Error> {
117
+ this.check_frozen()?;
118
+ let bytes = self::bytes(bytes, "bytes")?;
119
+ let outcome = sketch!(&mut *this.0.borrow_mut(), |sketch| sketch
120
+ .decode_into(&bytes));
121
+ Ok(answer(ruby, outcome, "decoded"))
115
122
  }
116
123
 
117
124
  fn width(&self) -> usize {
@@ -122,42 +129,71 @@ impl Wrapper {
122
129
  sketch!(&*self.0.borrow(), |sketch| depth_of(&**sketch))
123
130
  }
124
131
 
125
- fn add(rb_self: &Self, args: &[Value]) -> Result<(), Error> {
126
- let args = scan_args::<(Bytes,), (), (), (), RHash, ()>(args)?;
127
- let (item,) = args.required;
128
- let count =
129
- optional_kwarg::<Whole<u32>>(args.keywords, "count")?.map_or(1, |Whole(count)| count);
130
- sketch!(&mut *rb_self.0.borrow_mut(), |sketch| sketch
132
+ fn add(ruby: &Ruby, this: Obj<Self>, item: Value) -> Result<Value, Error> {
133
+ this.check_frozen()?;
134
+ let item = bytes(item, "item")?;
135
+ let outcome = sketch!(&mut *this.0.borrow_mut(), |sketch| sketch.add(&item));
136
+ Ok(answer(ruby, outcome, "added"))
137
+ }
138
+
139
+ fn add_count(ruby: &Ruby, this: Obj<Self>, item: Value, count: Value) -> Result<Value, Error> {
140
+ this.check_frozen()?;
141
+ let item = bytes(item, "item")?;
142
+ let count: u32 = integer(count, "count")?;
143
+ let outcome = sketch!(&mut *this.0.borrow_mut(), |sketch| sketch
131
144
  .add_count(&item, count));
132
- Ok(())
145
+ Ok(answer(ruby, outcome, "added"))
133
146
  }
134
147
 
135
- fn count(&self, item: Bytes) -> u32 {
136
- sketch!(&*self.0.borrow(), |sketch| sketch.estimate(&item))
148
+ fn add_hash_count(
149
+ ruby: &Ruby,
150
+ this: Obj<Self>,
151
+ hash: Value,
152
+ count: Value,
153
+ ) -> Result<Value, Error> {
154
+ this.check_frozen()?;
155
+ let hash: u64 = integer(hash, "hash")?;
156
+ let count: u32 = integer(count, "count")?;
157
+ let outcome = sketch!(&mut *this.0.borrow_mut(), |sketch| sketch
158
+ .add_hash_count(hash, count));
159
+ Ok(answer(ruby, outcome, "added"))
137
160
  }
138
161
 
139
- fn saturated(&self) -> bool {
140
- sketch!(&*self.0.borrow(), |sketch| sketch.saturated())
162
+ fn estimate(&self, item: Value) -> Result<u32, Error> {
163
+ let item = bytes(item, "item")?;
164
+ Ok(sketch!(&*self.0.borrow(), |sketch| sketch.estimate(&item)))
165
+ }
166
+
167
+ fn estimate_hash(&self, hash: Value) -> Result<u32, Error> {
168
+ let hash = integer(hash, "hash")?;
169
+ Ok(sketch!(&*self.0.borrow(), |sketch| sketch.estimate_hash(hash)))
141
170
  }
142
171
 
143
172
  fn total(&self) -> u64 {
144
173
  sketch!(&*self.0.borrow(), |sketch| sketch.total())
145
174
  }
146
175
 
147
- fn merge(ruby: &Ruby, rb_self: Obj<Self>, other: &Self) -> Result<Obj<Self>, Error> {
176
+ /// `:merged`, `:overflow`, or `:wrong_shape` for a sketch of another
177
+ /// width or depth (in Rust that merge does not compile).
178
+ fn merge(ruby: &Ruby, this: Obj<Self>, other: Value) -> Result<Value, Error> {
179
+ this.check_frozen()?;
180
+ let other: Obj<Self> = partner(ruby, &CLASS, other)?;
148
181
  let source = other.0.borrow().clone();
149
- match (&mut *rb_self.0.borrow_mut(), &source) {
182
+ let merged = match (&mut *this.0.borrow_mut(), &source) {
150
183
  (Sketch::W1024D4(target), Sketch::W1024D4(source)) => target.merge(source),
151
184
  (Sketch::W1024D8(target), Sketch::W1024D8(source)) => target.merge(source),
152
185
  (Sketch::W4096D4(target), Sketch::W4096D4(source)) => target.merge(source),
153
186
  (Sketch::W4096D8(target), Sketch::W4096D8(source)) => target.merge(source),
154
- _ => return Err(mismatch(ruby, "sketch")),
155
- }
156
- Ok(rb_self)
187
+ (
188
+ Sketch::W1024D4(_) | Sketch::W1024D8(_) | Sketch::W4096D4(_) | Sketch::W4096D8(_),
189
+ Sketch::W1024D4(_) | Sketch::W1024D8(_) | Sketch::W4096D4(_) | Sketch::W4096D8(_),
190
+ ) => Err(Refusal::WrongShape),
191
+ };
192
+ Ok(answer(ruby, merged, "merged"))
157
193
  }
158
194
 
159
- fn dump(ruby: &Ruby, rb_self: &Self) -> RString {
160
- let frame = sketch!(&*rb_self.0.borrow(), |sketch| sketch.encoded());
195
+ fn encoded(ruby: &Ruby, this: &Self) -> RString {
196
+ let frame = sketch!(&*this.0.borrow(), |sketch| sketch.encoded());
161
197
  ruby.str_from_slice(&frame)
162
198
  }
163
199
 
@@ -172,17 +208,22 @@ impl Wrapper {
172
208
  }
173
209
 
174
210
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
175
- let class = module.define_class("CountMinSketch", ruby.class_object())?;
176
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
177
- class.define_singleton_method("load", function!(Wrapper::load, 1))?;
211
+ let class = define_class(ruby, module, "CountMinSketch")?;
212
+ class.const_set("WIDTHS", sizes(ruby, &WIDTHS))?;
213
+ class.const_set("DEPTHS", sizes(ruby, &DEPTHS))?;
214
+ class.define_singleton_method("new", function!(Wrapper::new, 2))?;
215
+ class.define_singleton_method("decode", function!(Wrapper::decode, 1))?;
216
+ class.define_method("decode_into", method!(Wrapper::decode_into, 1))?;
178
217
  class.define_method("width", method!(Wrapper::width, 0))?;
179
218
  class.define_method("depth", method!(Wrapper::depth, 0))?;
180
- class.define_method("add", method!(Wrapper::add, -1))?;
181
- class.define_method("count", method!(Wrapper::count, 1))?;
219
+ class.define_method("add", method!(Wrapper::add, 1))?;
220
+ class.define_method("add_count", method!(Wrapper::add_count, 2))?;
221
+ class.define_method("add_hash_count", method!(Wrapper::add_hash_count, 2))?;
222
+ class.define_method("estimate", method!(Wrapper::estimate, 1))?;
223
+ class.define_method("estimate_hash", method!(Wrapper::estimate_hash, 1))?;
182
224
  class.define_method("total", method!(Wrapper::total, 0))?;
183
- class.define_method("saturated?", method!(Wrapper::saturated, 0))?;
184
225
  class.define_method("merge", method!(Wrapper::merge, 1))?;
185
- class.define_method("dump", method!(Wrapper::dump, 0))?;
226
+ class.define_method("encoded", method!(Wrapper::encoded, 0))?;
186
227
  class.define_method("inspect", method!(Wrapper::inspect, 0))?;
187
- Ok(())
228
+ pin::<Wrapper>(ruby, class, &CLASS)
188
229
  }
@@ -2,12 +2,13 @@
2
2
 
3
3
  use std::cell::RefCell;
4
4
 
5
- use bytes::Bytes;
6
- use magnus::scan_args::scan_args;
7
- use magnus::{Error, RHash, RModule, RString, Ruby, Value, function, method, prelude::*};
8
- use probabilistic_machines::{CodecError, CuckooFilter};
5
+ use magnus::typed_data::Obj;
6
+ use magnus::{Error, RModule, RString, Ruby, Value, function, method, prelude::*};
7
+ use matryona_machines::ruby::{Symbols, integer};
8
+ use probabilistic_machines::{CuckooFilter, Refusal, Removing};
9
9
 
10
- use crate::{Whole, codec_error, full, required_kwarg, unsupported, unsupported_blob};
10
+ use crate::data::bytes;
11
+ use crate::{Pinned, answer, decoded_or_refused, define_class, pin, sizes, unsupported};
11
12
 
12
13
  /// Bucket counts [`Filter`] is monomorphised for.
13
14
  const BUCKETS: [usize; 4] = [1024, 4096, 16384, 65536];
@@ -31,6 +32,9 @@ macro_rules! filter {
31
32
  };
32
33
  }
33
34
 
35
+ /// The class, pinned at init.
36
+ static CLASS: Pinned = Pinned::new("probabilistic_machines");
37
+
34
38
  #[magnus::wrap(class = "ProbabilisticMachines::CuckooFilter", free_immediately, size)]
35
39
  struct Wrapper(RefCell<Filter>);
36
40
 
@@ -50,40 +54,66 @@ fn boxed_new<const N: usize>() -> Box<CuckooFilter<N>> {
50
54
  }
51
55
 
52
56
  #[inline(never)]
53
- fn boxed_decode<const N: usize>(ruby: &Ruby, frame: &[u8]) -> Result<Box<CuckooFilter<N>>, Error> {
57
+ fn boxed_decode<const N: usize>(frame: &[u8]) -> Result<Box<CuckooFilter<N>>, Refusal> {
54
58
  let mut filter = boxed_new::<N>();
55
- filter
56
- .decode_into(frame)
57
- .map_err(|error| codec_error(ruby, error))?;
59
+ filter.decode_into(frame)?;
58
60
  Ok(filter)
59
61
  }
60
62
 
63
+ /// The filter a frame holds. A bucket count this build does not carry is read
64
+ /// as the smallest one it does, which answers exactly what the core answers a
65
+ /// type of another shape: `Truncated`, `WrongStructure` or `WrongShape`.
66
+ fn decoded(frame: &[u8]) -> Result<Filter, Refusal> {
67
+ Ok(match frame.get(1) {
68
+ Some(12) => Filter::B4096(boxed_decode(frame)?),
69
+ Some(14) => Filter::B16384(boxed_decode(frame)?),
70
+ Some(16) => Filter::B65536(boxed_decode(frame)?),
71
+ Some(_) | None => Filter::B1024(boxed_decode(frame)?),
72
+ })
73
+ }
74
+
75
+ matryona_machines::symbols! {
76
+ /// What an honoured removal answers.
77
+ Removings for Removing as "a removal" {
78
+ Cleared => "cleared",
79
+ NotHeld => "not_held",
80
+ }
81
+ }
82
+
83
+ /// The symbol of an honoured removal.
84
+ fn removing(ruby: &Ruby, removed: Removing) -> Value {
85
+ Removings::symbol(ruby, removed).as_value()
86
+ }
87
+
61
88
  impl Wrapper {
62
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
63
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
64
- let Whole(buckets): Whole<usize> = required_kwarg(args.keywords, "buckets")?;
89
+ /// `CuckooFilter.new(buckets)`. `RangeError` outside [`BUCKETS`].
90
+ fn new(ruby: &Ruby, buckets: Value) -> Result<Self, Error> {
91
+ let buckets: usize = integer(buckets, "buckets")?;
65
92
  let filter = match buckets {
66
- 1024 => Filter::B1024(boxed_new::<1024>()),
67
- 4096 => Filter::B4096(boxed_new::<4096>()),
68
- 16384 => Filter::B16384(boxed_new::<16384>()),
69
- 65536 => Filter::B65536(boxed_new::<65536>()),
93
+ 1024 => Filter::B1024(boxed_new()),
94
+ 4096 => Filter::B4096(boxed_new()),
95
+ 16384 => Filter::B16384(boxed_new()),
96
+ 65536 => Filter::B65536(boxed_new()),
70
97
  _ => return Err(unsupported(ruby, "buckets", buckets, &BUCKETS)),
71
98
  };
72
99
  Ok(Self(RefCell::new(filter)))
73
100
  }
74
101
 
75
- fn load(ruby: &Ruby, blob: Bytes) -> Result<Self, Error> {
76
- let Some(&exponent) = blob.get(1) else {
77
- return Err(codec_error(ruby, CodecError::Truncated));
78
- };
79
- let filter = match exponent {
80
- 10 => Filter::B1024(boxed_decode::<1024>(ruby, &blob)?),
81
- 12 => Filter::B4096(boxed_decode::<4096>(ruby, &blob)?),
82
- 14 => Filter::B16384(boxed_decode::<16384>(ruby, &blob)?),
83
- 16 => Filter::B65536(boxed_decode::<65536>(ruby, &blob)?),
84
- _ => return Err(unsupported_blob(ruby, "bucket count", &BUCKETS)),
85
- };
86
- Ok(Self(RefCell::new(filter)))
102
+ /// `CuckooFilter.decode(bytes)`: a filter, or the refusal symbol.
103
+ fn decode(ruby: &Ruby, bytes: Value) -> Result<Value, Error> {
104
+ let bytes = self::bytes(bytes, "bytes")?;
105
+ Ok(decoded_or_refused(
106
+ ruby,
107
+ decoded(&bytes).map(|held| Self(RefCell::new(held))),
108
+ ))
109
+ }
110
+
111
+ fn decode_into(ruby: &Ruby, this: Obj<Self>, bytes: Value) -> Result<Value, Error> {
112
+ this.check_frozen()?;
113
+ let bytes = self::bytes(bytes, "bytes")?;
114
+ let outcome = filter!(&mut *this.0.borrow_mut(), |filter| filter
115
+ .decode_into(&bytes));
116
+ Ok(answer(ruby, outcome, "decoded"))
87
117
  }
88
118
 
89
119
  fn buckets(&self) -> usize {
@@ -94,18 +124,42 @@ impl Wrapper {
94
124
  filter!(&*self.0.borrow(), |filter| capacity_of(&**filter))
95
125
  }
96
126
 
97
- fn insert(ruby: &Ruby, rb_self: &Self, item: Bytes) -> Result<bool, Error> {
98
- filter!(&mut *rb_self.0.borrow_mut(), |filter| filter.insert(&item))
99
- .map(|()| true)
100
- .map_err(|_| full(ruby))
127
+ fn insert(ruby: &Ruby, this: Obj<Self>, item: Value) -> Result<Value, Error> {
128
+ this.check_frozen()?;
129
+ let item = bytes(item, "item")?;
130
+ let outcome = filter!(&mut *this.0.borrow_mut(), |filter| filter.insert(&item));
131
+ Ok(answer(ruby, outcome, "inserted"))
132
+ }
133
+
134
+ fn insert_hash(ruby: &Ruby, this: Obj<Self>, hash: Value) -> Result<Value, Error> {
135
+ this.check_frozen()?;
136
+ let hash: u64 = integer(hash, "hash")?;
137
+ let outcome = filter!(&mut *this.0.borrow_mut(), |filter| filter.insert_hash(hash));
138
+ Ok(answer(ruby, outcome, "inserted"))
139
+ }
140
+
141
+ fn contains(&self, item: Value) -> Result<bool, Error> {
142
+ let item = bytes(item, "item")?;
143
+ Ok(filter!(&*self.0.borrow(), |filter| filter.contains(&item)))
144
+ }
145
+
146
+ fn contains_hash(&self, hash: Value) -> Result<bool, Error> {
147
+ let hash = integer(hash, "hash")?;
148
+ Ok(filter!(&*self.0.borrow(), |filter| filter.contains_hash(hash)))
101
149
  }
102
150
 
103
- fn contains(&self, item: Bytes) -> bool {
104
- filter!(&*self.0.borrow(), |filter| filter.contains(&item))
151
+ fn remove(ruby: &Ruby, this: Obj<Self>, item: Value) -> Result<Value, Error> {
152
+ this.check_frozen()?;
153
+ let item = bytes(item, "item")?;
154
+ let removed = filter!(&mut *this.0.borrow_mut(), |filter| filter.remove(&item));
155
+ Ok(removing(ruby, removed))
105
156
  }
106
157
 
107
- fn remove(&self, item: Bytes) -> bool {
108
- filter!(&mut *self.0.borrow_mut(), |filter| filter.remove(&item))
158
+ fn remove_hash(ruby: &Ruby, this: Obj<Self>, hash: Value) -> Result<Value, Error> {
159
+ this.check_frozen()?;
160
+ let hash: u64 = integer(hash, "hash")?;
161
+ let removed = filter!(&mut *this.0.borrow_mut(), |filter| filter.remove_hash(hash));
162
+ Ok(removing(ruby, removed))
109
163
  }
110
164
 
111
165
  fn size(&self) -> usize {
@@ -116,8 +170,8 @@ impl Wrapper {
116
170
  filter!(&*self.0.borrow(), |filter| filter.is_empty())
117
171
  }
118
172
 
119
- fn dump(ruby: &Ruby, rb_self: &Self) -> RString {
120
- let frame = filter!(&*rb_self.0.borrow(), |filter| filter.encoded());
173
+ fn encoded(ruby: &Ruby, this: &Self) -> RString {
174
+ let frame = filter!(&*this.0.borrow(), |filter| filter.encoded());
121
175
  ruby.str_from_slice(&frame)
122
176
  }
123
177
 
@@ -132,18 +186,22 @@ impl Wrapper {
132
186
  }
133
187
 
134
188
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
135
- let class = module.define_class("CuckooFilter", ruby.class_object())?;
136
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
137
- class.define_singleton_method("load", function!(Wrapper::load, 1))?;
189
+ let class = define_class(ruby, module, "CuckooFilter")?;
190
+ class.const_set("BUCKETS", sizes(ruby, &BUCKETS))?;
191
+ class.define_singleton_method("new", function!(Wrapper::new, 1))?;
192
+ class.define_singleton_method("decode", function!(Wrapper::decode, 1))?;
193
+ class.define_method("decode_into", method!(Wrapper::decode_into, 1))?;
138
194
  class.define_method("buckets", method!(Wrapper::buckets, 0))?;
139
195
  class.define_method("capacity", method!(Wrapper::capacity, 0))?;
140
196
  class.define_method("insert", method!(Wrapper::insert, 1))?;
141
- class.define_method("include?", method!(Wrapper::contains, 1))?;
197
+ class.define_method("insert_hash", method!(Wrapper::insert_hash, 1))?;
142
198
  class.define_method("contains?", method!(Wrapper::contains, 1))?;
199
+ class.define_method("contains_hash?", method!(Wrapper::contains_hash, 1))?;
143
200
  class.define_method("remove", method!(Wrapper::remove, 1))?;
201
+ class.define_method("remove_hash", method!(Wrapper::remove_hash, 1))?;
144
202
  class.define_method("size", method!(Wrapper::size, 0))?;
145
203
  class.define_method("empty?", method!(Wrapper::is_empty, 0))?;
146
- class.define_method("dump", method!(Wrapper::dump, 0))?;
204
+ class.define_method("encoded", method!(Wrapper::encoded, 0))?;
147
205
  class.define_method("inspect", method!(Wrapper::inspect, 0))?;
148
- Ok(())
206
+ pin::<Wrapper>(ruby, class, &CLASS)
149
207
  }
@@ -1,69 +1,116 @@
1
- //! The frozen `Data` objects the sketches hand back.
1
+ //! The `Data` values the sketches hand back, `Hitter` and `Centroid`.
2
+ //!
3
+ //! Both classes are defined in Ruby (`lib/probabilistic_machines.rb`) so their
4
+ //! `initialize` runs for every instance, hand-built or returned. It calls the
5
+ //! private validation hooks below, which hold a value to the core's own
6
+ //! constructor: `Hitter::new` and `Centroid::new`.
2
7
 
3
- use std::sync::OnceLock;
8
+ use magnus::{Error, RArray, RClass, RModule, Ruby, Value, function, prelude::*};
9
+ use matryona_machines::ruby::{
10
+ Class, Registry, bytes_with, class_name, finite, integer, utf8_with,
11
+ };
12
+ use probabilistic_machines::{Centroid, Hitter};
4
13
 
5
- use magnus::value::Opaque;
6
- use magnus::{Error, RClass, RModule, RStruct, Ruby, Value, prelude::*};
7
-
8
- use crate::{defined_twice, uninitialised};
14
+ /// `Hitter` and `Centroid`, resolved once at init and pinned:
15
+ /// `lib/probabilistic_machines.rb` defines both before the extension loads.
16
+ struct Classes {
17
+ hitter: Class,
18
+ centroid: Class,
19
+ }
9
20
 
10
- static HITTER: OnceLock<Opaque<RClass>> = OnceLock::new();
11
- static CENTROID: OnceLock<Opaque<RClass>> = OnceLock::new();
21
+ static CLASSES: Registry<Classes> = Registry::new("probabilistic_machines");
12
22
 
13
23
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
14
- let hitter = ruby.define_data(None, ("key", "count", "overestimate"))?;
15
- module.const_set("Hitter", hitter)?;
16
- HITTER
17
- .set(hitter.into())
18
- .map_err(|_| defined_twice(ruby, "Hitter"))?;
19
-
20
- let centroid = ruby.define_data(None, ("mean", "weight"))?;
21
- module.const_set("Centroid", centroid)?;
22
- CENTROID
23
- .set(centroid.into())
24
- .map_err(|_| defined_twice(ruby, "Centroid"))
24
+ let classes = Classes {
25
+ hitter: Class::resolve(ruby, module, "Hitter")?,
26
+ centroid: Class::resolve(ruby, module, "Centroid")?,
27
+ };
28
+ CLASSES.set(ruby, classes)?;
29
+ module.define_singleton_method("__hitter", function!(checked_hitter, 3))?;
30
+ module.define_singleton_method("__centroid", function!(checked_centroid, 2))?;
31
+ Ok(())
25
32
  }
26
33
 
27
- /// A tracked key, its counter, and how much of that counter it inherited from
28
- /// keys evicted before it.
29
- pub fn hitter(ruby: &Ruby, key: Value, count: u64, overestimate: u64) -> Result<Value, Error> {
30
- new_data(
31
- ruby,
32
- &HITTER,
33
- [key, ruby.into_value(count), ruby.into_value(overestimate)],
34
- )
34
+ /// A key as the table hashes it: exactly a String of UTF-8 text.
35
+ /// `TypeError` naming the class it got, `RangeError` for bytes that are not
36
+ /// UTF-8 text.
37
+ pub fn utf8_key(value: Value) -> Result<String, Error> {
38
+ utf8_with(value, "key", || {
39
+ format!("key must be a String, not {}", class_name(value))
40
+ })
35
41
  }
36
42
 
37
- /// One cluster of a digest: the mean of the values that collapsed into it.
38
- pub fn centroid(ruby: &Ruby, mean: f64, weight: f64) -> Result<Value, Error> {
39
- new_data(
40
- ruby,
41
- &CENTROID,
42
- [ruby.into_value(mean), ruby.into_value(weight)],
43
- )
43
+ /// An item or a frame: the bytes of exactly a String, in any encoding.
44
+ /// `TypeError` naming the argument and the class it got, as a key does.
45
+ pub fn bytes(value: Value, name: &str) -> Result<Vec<u8>, Error> {
46
+ bytes_with(value, || {
47
+ format!("{name} must be a String, not {}", class_name(value))
48
+ })
44
49
  }
45
50
 
46
- /// Instantiate one of our `Data` classes from its member values, in
47
- /// declaration order.
48
- ///
49
- /// `Data#initialize` takes keywords only, so `new_instance` would need a
50
- /// temporary `Hash` per call plus a temporary `String` per key while magnus
51
- /// interns it. Allocating, filling the members by position and freezing is
52
- /// everything `Data#initialize` does, and both classes are defined here with
53
- /// no `initialize` override to skip.
54
- fn new_data<const N: usize>(
51
+ /// `ProbabilisticMachines.__hitter(key, count, overestimate)`: the members of a
52
+ /// valid `Hitter`, the key a frozen UTF-8 copy so the value cannot change under
53
+ /// the caller. `TypeError` for a key that is not exactly a String or a count
54
+ /// that is not an Integer; `RangeError` for a key that is not UTF-8 text, where
55
+ /// `Hitter::new` answers `None` (an overestimate not below the count) or a
56
+ /// count is outside `0..2**64`.
57
+ fn checked_hitter(
55
58
  ruby: &Ruby,
56
- slot: &OnceLock<Opaque<RClass>>,
57
- members: [Value; N],
58
- ) -> Result<Value, Error> {
59
- let class = slot
60
- .get()
61
- .map(|class| ruby.get_inner(*class))
62
- .ok_or_else(|| uninitialised(ruby))?;
63
- let instance = RStruct::try_convert(class.obj_alloc()?)?;
64
- for (index, value) in members.into_iter().enumerate() {
65
- instance.aset(index, value)?;
59
+ key: Value,
60
+ count: Value,
61
+ overestimate: Value,
62
+ ) -> Result<RArray, Error> {
63
+ let count: u64 = integer(count, "count")?;
64
+ let overestimate: u64 = integer(overestimate, "overestimate")?;
65
+ let key = utf8_key(key)?;
66
+ if Hitter::new((), count, overestimate).is_none() {
67
+ return Err(Error::new(
68
+ ruby.exception_range_error(),
69
+ format!("overestimate {overestimate} is not below count {count}"),
70
+ ));
66
71
  }
67
- instance.freeze();
68
- Ok(instance.as_value())
72
+ let key = ruby.str_new(&key);
73
+ key.freeze();
74
+ Ok(ruby.ary_new_from_values(&[
75
+ key.as_value(),
76
+ ruby.into_value(count),
77
+ ruby.into_value(overestimate),
78
+ ]))
79
+ }
80
+
81
+ /// `ProbabilisticMachines.__centroid(mean, weight)`: the members of a valid
82
+ /// `Centroid`, as Floats. `TypeError` for anything but a Float or an Integer;
83
+ /// `RangeError` for a mean or weight that is not finite, and where
84
+ /// `Centroid::new` answers `None` (a weight that is not positive).
85
+ fn checked_centroid(ruby: &Ruby, mean: Value, weight: Value) -> Result<(f64, f64), Error> {
86
+ let (mean, weight) = (finite(mean, "mean")?, finite(weight, "weight")?);
87
+ let Some(centroid) = Centroid::new(mean, weight) else {
88
+ return Err(Error::new(
89
+ ruby.exception_range_error(),
90
+ format!(
91
+ "a centroid needs a finite mean and a finite, positive weight: {mean}, {weight}"
92
+ ),
93
+ ));
94
+ };
95
+ Ok((centroid.mean(), centroid.weight()))
96
+ }
97
+
98
+ /// The `Hitter` class resolved at init.
99
+ pub fn hitter_class(ruby: &Ruby) -> Result<RClass, Error> {
100
+ Ok(CLASSES.get(ruby)?.hitter.get(ruby))
101
+ }
102
+
103
+ /// The `Centroid` class resolved at init.
104
+ pub fn centroid_class(ruby: &Ruby) -> Result<RClass, Error> {
105
+ Ok(CLASSES.get(ruby)?.centroid.get(ruby))
106
+ }
107
+
108
+ /// A `Hitter` for a key the table tracks.
109
+ pub fn hitter(class: RClass, key: &str, entry: &Hitter<u64>) -> Result<Value, Error> {
110
+ class.funcall("new", (key, entry.count(), entry.overestimate()))
111
+ }
112
+
113
+ /// A `Centroid` for one cluster of a digest.
114
+ pub fn centroid(class: RClass, cluster: &Centroid) -> Result<Value, Error> {
115
+ class.funcall("new", (cluster.mean(), cluster.weight()))
69
116
  }