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.
@@ -3,16 +3,13 @@
3
3
  use std::cell::RefCell;
4
4
  use std::collections::{HashMap, HashSet};
5
5
 
6
- use bytes::Bytes;
7
- use magnus::scan_args::scan_args;
8
6
  use magnus::typed_data::Obj;
9
- use magnus::{Error, RArray, RHash, RModule, RString, Ruby, Value, function, method, prelude::*};
10
- use probabilistic_machines::{CodecError, HeavyHitters, hash64};
7
+ use magnus::{Error, RArray, RModule, RString, Ruby, Value, function, method, prelude::*};
8
+ use matryona_machines::ruby::integer;
9
+ use probabilistic_machines::{HeavyHitters, Hitter, Refusal, hash64};
11
10
 
12
- use crate::data::hitter;
13
- use crate::{
14
- Whole, codec_error, mismatch, optional_kwarg, required_kwarg, unsupported, unsupported_blob,
15
- };
11
+ use crate::data::{bytes, hitter, hitter_class, utf8_key};
12
+ use crate::{Pinned, answer, decoded_or_refused, define_class, partner, pin, sizes, unsupported};
16
13
 
17
14
  /// Counter counts [`Table`] is monomorphised for.
18
15
  const COUNTERS: [usize; 3] = [16, 64, 256];
@@ -35,24 +32,25 @@ macro_rules! table {
35
32
  };
36
33
  }
37
34
 
38
- /// Space-Saving needs `Copy + Eq` keys, so the table counts 64-bit key hashes
39
- /// and `names` holds the string each tracked hash came from. A key the table
40
- /// evicted leaves its name behind, so `names` is pruned back to the tracked
41
- /// hashes once it holds more than twice the counters.
35
+ type Names = HashMap<u64, String>;
36
+
37
+ /// The table counts 64-bit key hashes and `names` holds the string each
38
+ /// tracked hash came from. A key the table evicted leaves its name behind, so
39
+ /// `names` is pruned back to the tracked hashes once it holds more than twice
40
+ /// the counters.
41
+ /// The class, pinned at init.
42
+ static CLASS: Pinned = Pinned::new("probabilistic_machines");
43
+
42
44
  #[magnus::wrap(class = "ProbabilisticMachines::HeavyHitters", free_immediately, size)]
43
45
  struct Wrapper {
44
46
  table: RefCell<Table>,
45
- names: RefCell<HashMap<u64, String>>,
47
+ names: RefCell<Names>,
46
48
  }
47
49
 
48
50
  const fn counters_of<const K: usize>(_: &HeavyHitters<u64, K>) -> usize {
49
51
  K
50
52
  }
51
53
 
52
- const fn frame_len_of<const K: usize>(_: &HeavyHitters<u64, K>) -> usize {
53
- HeavyHitters::<u64, K>::ENCODED_LEN
54
- }
55
-
56
54
  /// Each shape is constructed behind its own call frame. Inlined, a debug build
57
55
  /// sizes one frame for every arm of the dispatch match at once.
58
56
  #[inline(never)]
@@ -60,18 +58,6 @@ fn boxed_new<const K: usize>() -> Box<HeavyHitters<u64, K>> {
60
58
  Box::new(HeavyHitters::new())
61
59
  }
62
60
 
63
- #[inline(never)]
64
- fn boxed_decode<const K: usize>(
65
- ruby: &Ruby,
66
- frame: &[u8],
67
- ) -> Result<Box<HeavyHitters<u64, K>>, Error> {
68
- let mut table = boxed_new::<K>();
69
- table
70
- .decode_into(frame)
71
- .map_err(|error| codec_error(ruby, error))?;
72
- Ok(table)
73
- }
74
-
75
61
  /// A `usize` as the key table's 64-bit little-endian length field.
76
62
  fn length_field(length: usize) -> [u8; 8] {
77
63
  let mut field = [0_u8; 8];
@@ -81,45 +67,69 @@ fn length_field(length: usize) -> [u8; 8] {
81
67
  field
82
68
  }
83
69
 
84
- fn bad_key_table(ruby: &Ruby, reason: &str) -> Error {
85
- Error::new(
86
- ruby.exception_arg_error(),
87
- format!("the blob's key table {reason}"),
88
- )
89
- }
90
-
91
70
  /// Reads the name records that follow the core frame back into the
92
- /// hash-to-name map.
93
- fn key_table(ruby: &Ruby, mut records: &[u8]) -> Result<HashMap<u64, String>, Error> {
71
+ /// hash-to-name map. A record cut short, a length this platform cannot hold
72
+ /// or a key that is not UTF-8 is `Malformed`.
73
+ fn key_table(mut records: &[u8]) -> Result<Names, Refusal> {
94
74
  let mut names = HashMap::new();
95
- while !records.is_empty() {
96
- let Some((field, tail)) = records.split_first_chunk::<8>() else {
97
- return Err(bad_key_table(ruby, "ends inside a record header"));
98
- };
75
+ while let Some((field, tail)) = records.split_first_chunk::<8>() {
99
76
  let Ok(length) = usize::try_from(u64::from_le_bytes(*field)) else {
100
- return Err(bad_key_table(ruby, "names a key this platform cannot hold"));
77
+ return Err(Refusal::Malformed);
101
78
  };
102
79
  let Some((name, tail)) = tail.split_at_checked(length) else {
103
- return Err(bad_key_table(ruby, "ends inside a key"));
80
+ return Err(Refusal::Malformed);
104
81
  };
105
82
  let Ok(name) = str::from_utf8(name) else {
106
- return Err(bad_key_table(ruby, "holds a key that is not UTF-8"));
83
+ return Err(Refusal::Malformed);
107
84
  };
108
85
  names.insert(hash64(name.as_bytes()), name.to_owned());
109
86
  records = tail;
110
87
  }
111
- Ok(names)
88
+ if records.is_empty() {
89
+ Ok(names)
90
+ } else {
91
+ Err(Refusal::Malformed)
92
+ }
93
+ }
94
+
95
+ /// A table and its names from a blob written by `encoded`, refusing a key
96
+ /// table that is malformed or does not name every tracked key.
97
+ #[inline(never)]
98
+ fn decode_table<const K: usize>(
99
+ blob: &[u8],
100
+ ) -> Result<(Box<HeavyHitters<u64, K>>, Names), Refusal> {
101
+ let mut table = boxed_new::<K>();
102
+ table.decode_into(blob)?;
103
+ let names = key_table(&blob[HeavyHitters::<u64, K>::ENCODED_LEN..])?;
104
+ if table
105
+ .hitters()
106
+ .any(|entry| !names.contains_key(entry.key()))
107
+ {
108
+ return Err(Refusal::Malformed);
109
+ }
110
+ Ok((table, names))
111
+ }
112
+
113
+ /// The table a blob holds. A counter count this build does not carry is read
114
+ /// as the smallest one it does, which answers exactly what the core answers a
115
+ /// type of another shape: `Truncated`, `WrongStructure` or `WrongShape`.
116
+ fn decoded(blob: &[u8]) -> Result<(Table, Names), Refusal> {
117
+ Ok(match blob.get(1..3) {
118
+ Some([64, 0]) => decode_table(blob).map(|(table, names)| (Table::K64(table), names))?,
119
+ Some([0, 1]) => decode_table(blob).map(|(table, names)| (Table::K256(table), names))?,
120
+ Some(_) | None => decode_table(blob).map(|(table, names)| (Table::K16(table), names))?,
121
+ })
112
122
  }
113
123
 
114
124
  impl Wrapper {
115
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
116
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
117
- let Whole(counters): Whole<usize> = required_kwarg(args.keywords, "k")?;
125
+ /// `HeavyHitters.new(counters)`. `RangeError` outside [`COUNTERS`].
126
+ fn new(ruby: &Ruby, counters: Value) -> Result<Self, Error> {
127
+ let counters: usize = integer(counters, "counters")?;
118
128
  let table = match counters {
119
- 16 => Table::K16(boxed_new::<16>()),
120
- 64 => Table::K64(boxed_new::<64>()),
121
- 256 => Table::K256(boxed_new::<256>()),
122
- _ => return Err(unsupported(ruby, "k", counters, &COUNTERS)),
129
+ 16 => Table::K16(boxed_new()),
130
+ 64 => Table::K64(boxed_new()),
131
+ 256 => Table::K256(boxed_new()),
132
+ _ => return Err(unsupported(ruby, "counters", counters, &COUNTERS)),
123
133
  };
124
134
  Ok(Self {
125
135
  table: RefCell::new(table),
@@ -127,54 +137,64 @@ impl Wrapper {
127
137
  })
128
138
  }
129
139
 
130
- /// Reads a blob written by [`dump`](Self::dump).
131
- fn load(ruby: &Ruby, blob: Bytes) -> Result<Self, Error> {
132
- let Some(shape) = blob.get(1..3) else {
133
- return Err(codec_error(ruby, CodecError::Truncated));
134
- };
135
- let counters = u16::from_le_bytes([shape[0], shape[1]]);
136
- let table = match counters {
137
- 16 => Table::K16(boxed_decode::<16>(ruby, &blob)?),
138
- 64 => Table::K64(boxed_decode::<64>(ruby, &blob)?),
139
- 256 => Table::K256(boxed_decode::<256>(ruby, &blob)?),
140
- _ => return Err(unsupported_blob(ruby, "counter count", &COUNTERS)),
141
- };
142
-
143
- let frame_len = table!(&table, |inner| frame_len_of(&**inner));
144
- let names = key_table(ruby, &blob[frame_len..])?;
145
- let unnamed = table!(&table, |inner| inner
146
- .hitters()
147
- .any(|entry| !names.contains_key(&entry.key)));
148
- if unnamed {
149
- return Err(bad_key_table(ruby, "does not name every tracked key"));
150
- }
151
-
152
- Ok(Self {
140
+ /// `HeavyHitters.decode(bytes)`: a table, or the refusal symbol.
141
+ fn decode(ruby: &Ruby, blob: Value) -> Result<Value, Error> {
142
+ let blob = bytes(blob, "bytes")?;
143
+ let held = decoded(&blob).map(|(table, names)| Self {
153
144
  table: RefCell::new(table),
154
145
  names: RefCell::new(names),
155
- })
146
+ });
147
+ Ok(decoded_or_refused(ruby, held))
148
+ }
149
+
150
+ /// `:decoded`, or the refusal symbol with the table and names untouched.
151
+ fn decode_into(ruby: &Ruby, this: Obj<Self>, blob: Value) -> Result<Value, Error> {
152
+ this.check_frozen()?;
153
+ let blob = bytes(blob, "bytes")?;
154
+ let read = match &*this.table.borrow() {
155
+ Table::K16(_) => decode_table(&blob).map(|(table, names)| (Table::K16(table), names)),
156
+ Table::K64(_) => decode_table(&blob).map(|(table, names)| (Table::K64(table), names)),
157
+ Table::K256(_) => decode_table(&blob).map(|(table, names)| (Table::K256(table), names)),
158
+ };
159
+ let outcome = read.map(|(table, names)| {
160
+ *this.table.borrow_mut() = table;
161
+ *this.names.borrow_mut() = names;
162
+ });
163
+ Ok(answer(ruby, outcome, "decoded"))
156
164
  }
157
165
 
158
166
  fn counters(&self) -> usize {
159
167
  table!(&*self.table.borrow(), |table| counters_of(&**table))
160
168
  }
161
169
 
162
- fn add(rb_self: &Self, args: &[Value]) -> Result<(), Error> {
163
- let args = scan_args::<(String,), (), (), (), RHash, ()>(args)?;
164
- let (key,) = args.required;
165
- let count =
166
- optional_kwarg::<Whole<u64>>(args.keywords, "count")?.map_or(1, |Whole(count)| count);
170
+ fn add(ruby: &Ruby, this: Obj<Self>, key: Value) -> Result<Value, Error> {
171
+ this.check_frozen()?;
172
+ let key = utf8_key(key)?;
173
+ Ok(Self::counted(ruby, this, key, 1))
174
+ }
175
+
176
+ fn add_count(ruby: &Ruby, this: Obj<Self>, key: Value, count: Value) -> Result<Value, Error> {
177
+ this.check_frozen()?;
178
+ let key = utf8_key(key)?;
179
+ let count = integer(count, "count")?;
180
+ Ok(Self::counted(ruby, this, key, count))
181
+ }
182
+
183
+ /// Records the name only once the core has honoured the count.
184
+ fn counted(ruby: &Ruby, this: Obj<Self>, key: String, count: u64) -> Value {
167
185
  let hash = hash64(key.as_bytes());
168
- table!(&mut *rb_self.table.borrow_mut(), |table| table
186
+ let outcome = table!(&mut *this.table.borrow_mut(), |table| table
169
187
  .add_count(hash, count));
170
- rb_self.names.borrow_mut().insert(hash, key);
171
- rb_self.prune();
172
- Ok(())
188
+ if outcome.is_ok() {
189
+ this.names.borrow_mut().insert(hash, key);
190
+ this.prune();
191
+ }
192
+ answer(ruby, outcome, "added")
173
193
  }
174
194
 
175
- fn count(&self, key: String) -> u64 {
176
- let hash = hash64(key.as_bytes());
177
- table!(&*self.table.borrow(), |table| table.count(&hash))
195
+ fn count(this: &Self, key: Value) -> Result<u64, Error> {
196
+ let hash = hash64(utf8_key(key)?.as_bytes());
197
+ Ok(table!(&*this.table.borrow(), |table| table.count(&hash)))
178
198
  }
179
199
 
180
200
  fn observed(&self) -> u64 {
@@ -189,45 +209,69 @@ impl Wrapper {
189
209
  table!(&*self.table.borrow(), |table| table.is_empty())
190
210
  }
191
211
 
192
- fn ranked(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
193
- rb_self.take(ruby, usize::MAX)
212
+ /// The most frequent tracked key, `nil` when nothing is tracked.
213
+ fn top(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
214
+ let top = table!(&*this.table.borrow(), |table| table.top().copied());
215
+ this.built(ruby, top.as_slice())?.entry(0)
194
216
  }
195
217
 
196
- fn top(ruby: &Ruby, rb_self: &Self, Whole(count): Whole<usize>) -> Result<RArray, Error> {
197
- rb_self.take(ruby, count)
218
+ /// Every tracked key, most frequent first.
219
+ fn ranked(ruby: &Ruby, this: &Self) -> Result<RArray, Error> {
220
+ let ranked = table!(&*this.table.borrow(), |table| table.ranked());
221
+ this.built(ruby, &ranked)
198
222
  }
199
223
 
200
- fn merge(ruby: &Ruby, rb_self: Obj<Self>, other: &Self) -> Result<Obj<Self>, Error> {
224
+ /// Every tracked key, in the table's own order.
225
+ fn hitters(ruby: &Ruby, this: &Self) -> Result<RArray, Error> {
226
+ let hitters: Vec<Hitter<u64>> = table!(&*this.table.borrow(), |table| table
227
+ .hitters()
228
+ .copied()
229
+ .collect());
230
+ this.built(ruby, &hitters)
231
+ }
232
+
233
+ /// `:merged`, `:overflow`, or `:wrong_shape` for a table of another
234
+ /// counter count (in Rust that merge does not compile).
235
+ fn merge(ruby: &Ruby, this: Obj<Self>, other: Value) -> Result<Value, Error> {
236
+ this.check_frozen()?;
237
+ let other: Obj<Self> = partner(ruby, &CLASS, other)?;
201
238
  let source = other.table.borrow().clone();
202
239
  let names = other.names.borrow().clone();
203
- match (&mut *rb_self.table.borrow_mut(), &source) {
240
+ let merged = match (&mut *this.table.borrow_mut(), &source) {
204
241
  (Table::K16(target), Table::K16(source)) => target.merge(source),
205
242
  (Table::K64(target), Table::K64(source)) => target.merge(source),
206
243
  (Table::K256(target), Table::K256(source)) => target.merge(source),
207
- _ => return Err(mismatch(ruby, "table")),
244
+ (
245
+ Table::K16(_) | Table::K64(_) | Table::K256(_),
246
+ Table::K16(_) | Table::K64(_) | Table::K256(_),
247
+ ) => Err(Refusal::WrongShape),
248
+ };
249
+ if merged.is_ok() {
250
+ this.names.borrow_mut().extend(names);
251
+ this.prune();
208
252
  }
209
- rb_self.names.borrow_mut().extend(names);
210
- rb_self.prune();
211
- Ok(rb_self)
253
+ Ok(answer(ruby, merged, "merged"))
212
254
  }
213
255
 
214
256
  /// The core frame followed by the names of the keys it tracks.
215
257
  ///
216
258
  /// ```text
217
- /// core frame HeavyHitters::<u64, k>::ENCODED_LEN bytes, tag 0xB1
259
+ /// core frame HeavyHitters::<u64, counters>::ENCODED_LEN bytes, tag 0xB1
218
260
  /// name record u64 little-endian byte length, then that many UTF-8 bytes
219
261
  /// ```
220
262
  ///
221
263
  /// One record per tracked key, in the core frame's order, filling the rest
222
- /// of the blob. The table counts key hashes, so [`load`](Self::load)
223
- /// rehashes each name to rebuild the hash-to-name map `top` and `ranked`
224
- /// read.
225
- fn dump(ruby: &Ruby, rb_self: &Self) -> RString {
226
- let (frame, keys) = table!(&*rb_self.table.borrow(), |table| (
264
+ /// of the blob. The table counts key hashes, so [`decode`](Self::decode)
265
+ /// rehashes each name to rebuild the hash-to-name map.
266
+ fn encoded(ruby: &Ruby, this: &Self) -> RString {
267
+ let (frame, keys) = table!(&*this.table.borrow(), |table| (
227
268
  table.encoded(),
228
- table.hitters().map(|entry| entry.key).collect::<Vec<u64>>()
269
+ table
270
+ .hitters()
271
+ .map(|entry| *entry.key())
272
+ .collect::<Vec<u64>>()
229
273
  ));
230
- let names = rb_self.names.borrow();
274
+ let names = this.names.borrow();
231
275
  let mut blob = Vec::from(frame);
232
276
  for name in keys.iter().filter_map(|key| names.get(key)) {
233
277
  blob.extend_from_slice(&length_field(name.len()));
@@ -238,33 +282,30 @@ impl Wrapper {
238
282
 
239
283
  fn inspect(&self) -> String {
240
284
  format!(
241
- "#<ProbabilisticMachines::HeavyHitters k={} tracked={} observed={}>",
285
+ "#<ProbabilisticMachines::HeavyHitters counters={} tracked={} observed={}>",
242
286
  self.counters(),
243
287
  self.size(),
244
288
  self.observed()
245
289
  )
246
290
  }
247
291
 
248
- /// The `count` most frequent tracked keys, most frequent first.
249
- fn take(&self, ruby: &Ruby, count: usize) -> Result<RArray, Error> {
250
- let ranked = table!(&*self.table.borrow(), |table| table.ranked());
251
- let names = self.names.borrow();
252
- let hitters = ruby.ary_new_capa(ranked.len().min(count));
253
- for entry in ranked.into_iter().take(count) {
254
- let key = names.get(&entry.key).ok_or_else(|| {
255
- Error::new(
256
- ruby.exception_runtime_error(),
257
- "a tracked key lost its name",
258
- )
259
- })?;
260
- hitters.push(hitter(
261
- ruby,
262
- ruby.str_new(key).as_value(),
263
- entry.count,
264
- entry.overestimate,
265
- )?)?;
292
+ /// `Hitter` values for `entries`, with the name each hash came from. Every
293
+ /// tracked hash has one: names are recorded when a count is honoured and
294
+ /// pruned only to the tracked set, so no entry is ever left out.
295
+ fn built(&self, ruby: &Ruby, entries: &[Hitter<u64>]) -> Result<RArray, Error> {
296
+ let class = hitter_class(ruby)?;
297
+ let names = self.names.borrow().clone();
298
+ let array = ruby.ary_new_capa(entries.len());
299
+ for entry in entries {
300
+ let Some(name) = names.get(entry.key()) else {
301
+ // No answer names a key it cannot spell: a hash without its
302
+ // name is left out rather than reported under another one.
303
+ debug_assert!(false, "every tracked hash keeps its name");
304
+ continue;
305
+ };
306
+ array.push(hitter(class, name, entry)?)?;
266
307
  }
267
- Ok(hitters)
308
+ Ok(array)
268
309
  }
269
310
 
270
311
  fn prune(&self) {
@@ -274,26 +315,30 @@ impl Wrapper {
274
315
  }
275
316
  let tracked: HashSet<u64> = table!(&*self.table.borrow(), |table| table
276
317
  .hitters()
277
- .map(|entry| entry.key)
318
+ .map(|entry| *entry.key())
278
319
  .collect());
279
320
  names.retain(|hash, _| tracked.contains(hash));
280
321
  }
281
322
  }
282
323
 
283
324
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
284
- let class = module.define_class("HeavyHitters", ruby.class_object())?;
285
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
286
- class.define_singleton_method("load", function!(Wrapper::load, 1))?;
287
- class.define_method("k", method!(Wrapper::counters, 0))?;
288
- class.define_method("add", method!(Wrapper::add, -1))?;
325
+ let class = define_class(ruby, module, "HeavyHitters")?;
326
+ class.const_set("COUNTERS", sizes(ruby, &COUNTERS))?;
327
+ class.define_singleton_method("new", function!(Wrapper::new, 1))?;
328
+ class.define_singleton_method("decode", function!(Wrapper::decode, 1))?;
329
+ class.define_method("decode_into", method!(Wrapper::decode_into, 1))?;
330
+ class.define_method("counters", method!(Wrapper::counters, 0))?;
331
+ class.define_method("add", method!(Wrapper::add, 1))?;
332
+ class.define_method("add_count", method!(Wrapper::add_count, 2))?;
289
333
  class.define_method("count", method!(Wrapper::count, 1))?;
290
334
  class.define_method("observed", method!(Wrapper::observed, 0))?;
291
335
  class.define_method("size", method!(Wrapper::size, 0))?;
292
336
  class.define_method("empty?", method!(Wrapper::is_empty, 0))?;
293
- class.define_method("top", method!(Wrapper::top, 1))?;
337
+ class.define_method("top", method!(Wrapper::top, 0))?;
294
338
  class.define_method("ranked", method!(Wrapper::ranked, 0))?;
339
+ class.define_method("hitters", method!(Wrapper::hitters, 0))?;
295
340
  class.define_method("merge", method!(Wrapper::merge, 1))?;
296
- class.define_method("dump", method!(Wrapper::dump, 0))?;
341
+ class.define_method("encoded", method!(Wrapper::encoded, 0))?;
297
342
  class.define_method("inspect", method!(Wrapper::inspect, 0))?;
298
- Ok(())
343
+ pin::<Wrapper>(ruby, class, &CLASS)
299
344
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ProbabilisticMachines
4
- VERSION = '0.1.4'
4
+ VERSION = '0.6.1'
5
5
  end
@@ -2,6 +2,44 @@
2
2
 
3
3
  require_relative 'probabilistic_machines/version'
4
4
 
5
- # Every class, the two `Data` result objects and both error classes are defined
6
- # by the native extension; there is no pure-Ruby implementation to fall back to.
5
+ module ProbabilisticMachines
6
+ # The core's `Hitter`: a tracked key, its counter, and how much of that
7
+ # counter it may have inherited. The true count lies in
8
+ # `count - overestimate` through `count`, so like `Hitter::new` it needs an
9
+ # overestimate below the count: anything else raises RangeError (TypeError
10
+ # for a key that is not a String or a count that is not an Integer).
11
+ Hitter = Data.define(:key, :count, :overestimate) do
12
+ def initialize(key:, count:, overestimate:)
13
+ key, count, overestimate = ProbabilisticMachines.__send__(:__hitter, key, count, overestimate)
14
+ super
15
+ end
16
+ end
17
+
18
+ # The core's `Centroid`: one cluster of a digest, the mean of the values that
19
+ # collapsed into it. Like `Centroid::new` it holds a finite mean and a
20
+ # finite, positive weight: anything else raises RangeError (TypeError for a
21
+ # non-number). Stored as Floats.
22
+ Centroid = Data.define(:mean, :weight) do
23
+ def initialize(mean:, weight:)
24
+ mean, weight = ProbabilisticMachines.__send__(:__centroid, mean, weight)
25
+ super
26
+ end
27
+ end
28
+ end
29
+
30
+ # Native is required: there is no pure-Ruby fallback. It defines every sketch
31
+ # class and validates the Data values above.
7
32
  require 'probabilistic_machines_native/probabilistic_machines_native'
33
+
34
+ module ProbabilisticMachines
35
+ private_class_method :__hitter, :__centroid
36
+
37
+ # The values are final. `initialize` is where each validates, and a subclass
38
+ # could override it, or `allocate` build an instance that never ran it:
39
+ # subclassing raises TypeError (as subclassing Class does) and `allocate`
40
+ # is gone. `new`, keywords, `with` and `dup` all still run the check.
41
+ [Hitter, Centroid].each do |value|
42
+ value.singleton_class.undef_method(:allocate)
43
+ value.define_singleton_method(:inherited) { |_| raise TypeError, "#{value} cannot be subclassed" }
44
+ end
45
+ end