join_machines 0.6.2

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.
@@ -0,0 +1,550 @@
1
+ #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
3
+ #![doc = include_str!("../README.md")]
4
+ /// Per-input event-time progress, the sibling type this join is built on, and
5
+ /// what an honoured advance of it did: `Advanced`, or `Repeated` for an
6
+ /// idempotent repeat that changed nothing. Both are honoured; neither is a
7
+ /// refusal.
8
+ pub use window_machines::{Advancing, Watermark};
9
+
10
+ mod refusal;
11
+
12
+ pub use refusal::Refusal;
13
+
14
+ /// One of the two join inputs.
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
+ pub enum Side {
17
+ /// The input whose timestamp anchors the interval.
18
+ Left,
19
+ /// The input matched relative to a left timestamp.
20
+ Right,
21
+ }
22
+ impl Side {
23
+ /// The opposite input.
24
+ #[must_use]
25
+ pub const fn other(self) -> Self {
26
+ match self {
27
+ Self::Left => Self::Right,
28
+ Self::Right => Self::Left,
29
+ }
30
+ }
31
+ }
32
+
33
+ /// Join metadata for one externally stored record.
34
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35
+ pub struct Record {
36
+ /// Caller-assigned identity, unique among live records of its side.
37
+ pub id: u64,
38
+ /// Equi-join key; hashing a wider key into it is the caller's job.
39
+ pub key: u64,
40
+ /// Event time in caller-defined units.
41
+ pub timestamp: u64,
42
+ }
43
+
44
+ /// Inclusive range of opposite-side event times a record can match, never
45
+ /// empty: `first <= last`.
46
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
47
+ pub struct Reach {
48
+ first: u64,
49
+ last: u64,
50
+ }
51
+ impl Reach {
52
+ /// The range from `first` to `last` inclusive, or `None` unless
53
+ /// `first <= last`: a range holding no timestamp is not a reach.
54
+ #[must_use]
55
+ pub const fn new(first: u64, last: u64) -> Option<Self> {
56
+ if first <= last {
57
+ Some(Self { first, last })
58
+ } else {
59
+ None
60
+ }
61
+ }
62
+
63
+ /// Earliest matching timestamp.
64
+ #[must_use]
65
+ pub const fn first(self) -> u64 {
66
+ self.first
67
+ }
68
+
69
+ /// Latest matching timestamp.
70
+ #[must_use]
71
+ pub const fn last(self) -> u64 {
72
+ self.last
73
+ }
74
+
75
+ /// Whether an opposite-side timestamp is inside the range.
76
+ #[must_use]
77
+ pub const fn contains(self, timestamp: u64) -> bool {
78
+ self.first <= timestamp && timestamp <= self.last
79
+ }
80
+ }
81
+
82
+ /// Interval bounds: a pair matches when
83
+ /// `left - before <= right <= left + after` in event time.
84
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
85
+ pub struct Bounds {
86
+ before: u64,
87
+ after: u64,
88
+ }
89
+ impl Bounds {
90
+ /// Right records may trail a left record by `before` and lead it by `after`.
91
+ #[must_use]
92
+ pub const fn new(before: u64, after: u64) -> Self {
93
+ Self { before, after }
94
+ }
95
+ /// How far a right record may be behind its left record.
96
+ #[must_use]
97
+ pub const fn before(self) -> u64 {
98
+ self.before
99
+ }
100
+ /// How far a right record may be ahead of its left record.
101
+ #[must_use]
102
+ pub const fn after(self) -> u64 {
103
+ self.after
104
+ }
105
+ /// Opposite-side timestamps reachable from a record on `side`.
106
+ ///
107
+ /// Endpoints saturate at the `u64` domain edges, which is exact: no
108
+ /// timestamp exists beyond them.
109
+ #[must_use]
110
+ pub const fn reach(self, side: Side, timestamp: u64) -> Reach {
111
+ let (back, ahead) = match side {
112
+ Side::Left => (self.before, self.after),
113
+ Side::Right => (self.after, self.before),
114
+ };
115
+ // Saturating either way keeps `first <= timestamp <= last`.
116
+ Reach {
117
+ first: timestamp.saturating_sub(back),
118
+ last: timestamp.saturating_add(ahead),
119
+ }
120
+ }
121
+ }
122
+
123
+ /// A matched pair of record identities sharing `key`.
124
+ ///
125
+ /// The `Default` value is an output-buffer placeholder (`[Pair::default(); N]`).
126
+ /// It is not a sentinel: a real pair of zero-valued records equals it, so read
127
+ /// only the entries the call reports.
128
+ #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
129
+ pub struct Pair {
130
+ /// The shared join key.
131
+ pub key: u64,
132
+ /// Left record identity.
133
+ pub left: u64,
134
+ /// Right record identity.
135
+ pub right: u64,
136
+ }
137
+
138
+ /// A record dropped from the join; its external payload may be released.
139
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
140
+ pub struct Retired {
141
+ /// Input the record belonged to.
142
+ pub side: Side,
143
+ /// The metadata that was held.
144
+ pub record: Record,
145
+ }
146
+ /// An output-buffer placeholder (`[Retired::default(); N]`): a zeroed left
147
+ /// record. It is not a sentinel: a real retired record can equal it, so read
148
+ /// only the entries the call reports.
149
+ impl Default for Retired {
150
+ fn default() -> Self {
151
+ Self {
152
+ side: Side::Left,
153
+ record: Record {
154
+ id: 0,
155
+ key: 0,
156
+ timestamp: 0,
157
+ },
158
+ }
159
+ }
160
+ }
161
+
162
+ /// What an honoured [`Join::insert`] did.
163
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
164
+ pub enum Inserting {
165
+ /// The record is now held and its pairs are owed.
166
+ Accepted,
167
+ /// An idempotent repeat: this exact record (same side, identity, key and
168
+ /// timestamp) is already held. Nothing changed and no pair is owed twice.
169
+ Duplicate,
170
+ }
171
+
172
+ /// The pair owed next: `record` on `side` against `other`, the held opposite
173
+ /// record in slot `cursor`. It carries `other` so draining never looks the
174
+ /// slot up again.
175
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
176
+ struct Probe {
177
+ side: Side,
178
+ record: Record,
179
+ cursor: usize,
180
+ other: Record,
181
+ }
182
+
183
+ /// Bounded two-input interval join over record metadata.
184
+ ///
185
+ /// `L` and `R` are the live-record capacities of the left and right inputs.
186
+ #[derive(Debug, Clone, PartialEq, Eq)]
187
+ pub struct Join<const L: usize, const R: usize> {
188
+ bounds: Bounds,
189
+ left: [Option<Record>; L],
190
+ right: [Option<Record>; R],
191
+ left_watermark: Watermark,
192
+ right_watermark: Watermark,
193
+ probe: Option<Probe>,
194
+ }
195
+
196
+ impl<const L: usize, const R: usize> Join<L, R> {
197
+ /// Construct an empty join with uninitialized watermarks.
198
+ #[must_use]
199
+ pub fn new(bounds: Bounds) -> Self {
200
+ Self {
201
+ bounds,
202
+ left: [None; L],
203
+ right: [None; R],
204
+ left_watermark: Watermark::default(),
205
+ right_watermark: Watermark::default(),
206
+ probe: None,
207
+ }
208
+ }
209
+
210
+ /// The interval bounds fixed at construction.
211
+ #[must_use]
212
+ pub const fn bounds(&self) -> Bounds {
213
+ self.bounds
214
+ }
215
+
216
+ /// Live-record capacity of one input.
217
+ #[must_use]
218
+ pub const fn capacity(&self, side: Side) -> usize {
219
+ match side {
220
+ Side::Left => L,
221
+ Side::Right => R,
222
+ }
223
+ }
224
+
225
+ /// Live records currently held for one input.
226
+ #[must_use]
227
+ pub fn len(&self, side: Side) -> usize {
228
+ self.records(side).count()
229
+ }
230
+
231
+ /// Whether neither input holds a record.
232
+ #[must_use]
233
+ pub fn is_empty(&self) -> bool {
234
+ self.len(Side::Left) == 0 && self.len(Side::Right) == 0
235
+ }
236
+
237
+ /// Whether a live record on `side` uses this identity.
238
+ #[must_use]
239
+ pub fn contains(&self, side: Side, id: u64) -> bool {
240
+ self.held(side, id).is_some()
241
+ }
242
+
243
+ /// Last accepted watermark of one input, or `None` before the first.
244
+ #[must_use]
245
+ pub const fn watermark(&self, side: Side) -> Option<u64> {
246
+ self.side_watermark(side).value()
247
+ }
248
+
249
+ /// One input's event-time progress as the sibling [`Watermark`], a copy.
250
+ ///
251
+ /// Same state [`watermark`](Self::watermark) reads as an integer; use it to
252
+ /// ask sibling questions such as [`Watermark::closes`].
253
+ #[must_use]
254
+ pub const fn side_watermark(&self, side: Side) -> Watermark {
255
+ match side {
256
+ Side::Left => self.left_watermark,
257
+ Side::Right => self.right_watermark,
258
+ }
259
+ }
260
+
261
+ /// Admit a record and owe every pair it forms with held opposite records.
262
+ ///
263
+ /// A record whose identity is already held on `side` is answered from the
264
+ /// held record, before anything else is checked: the same key and
265
+ /// timestamp is the effect asked for already holding,
266
+ /// [`Inserting::Duplicate`], and nothing changes (no pair is owed twice);
267
+ /// any other contents are [`Refusal::Mismatch`]. Held means live right now:
268
+ /// a matched and drained record is still held, a retired one is not.
269
+ ///
270
+ /// A record that is not held is late when its timestamp is at or below
271
+ /// its own side's watermark, and on no other count: the opposite
272
+ /// watermark never refuses a record, so one whose partner is still held
273
+ /// is always admitted and paired, however far the two watermarks have
274
+ /// drifted apart. A record replayed after it was retired is
275
+ /// [`Refusal::Late`] for good, because [`retire`](Self::retire) lets a
276
+ /// record go only once its own watermark has reached it.
277
+ ///
278
+ /// # Errors
279
+ /// [`Refusal::Mismatch`] for a held identity with other contents,
280
+ /// [`Refusal::Pending`] while earlier pairs are undrained, [`Refusal::Late`]
281
+ /// at or below the side's own watermark, [`Refusal::Full`] without a free
282
+ /// slot. Nothing changes.
283
+ pub fn insert(&mut self, side: Side, record: Record) -> Result<Inserting, Refusal> {
284
+ if let Some(held) = self.held(side, record.id) {
285
+ return if held == record {
286
+ Ok(Inserting::Duplicate)
287
+ } else {
288
+ Err(Refusal::Mismatch)
289
+ };
290
+ }
291
+ if self.probe.is_some() {
292
+ return Err(Refusal::Pending);
293
+ }
294
+ if self.passed(side, record.timestamp) {
295
+ return Err(Refusal::Late);
296
+ }
297
+ let free = self
298
+ .slots_mut(side)
299
+ .iter_mut()
300
+ .find(|slot| slot.is_none())
301
+ .ok_or(Refusal::Full)?;
302
+ *free = Some(record);
303
+ self.probe = self.settle(side, record, 0);
304
+ Ok(Inserting::Accepted)
305
+ }
306
+
307
+ /// Whether at least one pair from the last insert is still owed.
308
+ #[must_use]
309
+ pub const fn pending(&self) -> bool {
310
+ self.probe.is_some()
311
+ }
312
+
313
+ /// Number of pairs still owed from the last insert.
314
+ #[must_use]
315
+ pub fn pending_pairs(&self) -> usize {
316
+ let mut count = 0;
317
+ let mut probe = self.probe;
318
+ while let Some(current) = probe {
319
+ // Each probe's cursor is past the last: at most one per slot.
320
+ count += 1;
321
+ probe = self.next(current);
322
+ }
323
+ count
324
+ }
325
+
326
+ /// Move owed pairs into `out`, each exactly once; returns how many.
327
+ ///
328
+ /// A full buffer loses nothing: the join stays [`pending`](Self::pending)
329
+ /// and the next call resumes after the last pair written.
330
+ pub fn drain(&mut self, out: &mut [Pair]) -> usize {
331
+ let mut written = 0;
332
+ for slot in out {
333
+ let Some(probe) = self.probe else {
334
+ break;
335
+ };
336
+ let other = probe.other;
337
+ *slot = match probe.side {
338
+ Side::Left => Pair {
339
+ key: probe.record.key,
340
+ left: probe.record.id,
341
+ right: other.id,
342
+ },
343
+ Side::Right => Pair {
344
+ key: probe.record.key,
345
+ left: other.id,
346
+ right: probe.record.id,
347
+ },
348
+ };
349
+ // At most `out.len()`.
350
+ written += 1;
351
+ self.probe = self.next(probe);
352
+ }
353
+ written
354
+ }
355
+
356
+ /// Advance or repeat one input's event-time progress.
357
+ ///
358
+ /// [`Advancing::Advanced`] when the side moved forward (or took its first
359
+ /// value). Repeating the value the side already holds is the effect asked
360
+ /// for already holding: [`Advancing::Repeated`], and nothing changes.
361
+ /// Advancing never removes records; call [`retire`](Self::retire) for that.
362
+ ///
363
+ /// # Errors
364
+ /// [`Refusal::WatermarkRegressed`] when `value` is behind the side's
365
+ /// watermark. Nothing changes.
366
+ pub const fn advance_watermark(
367
+ &mut self,
368
+ side: Side,
369
+ value: u64,
370
+ ) -> Result<Advancing, Refusal> {
371
+ // Asks the sibling where the side stands, then acts: the sibling's
372
+ // `advance` would answer refusals only its windows and sessions give.
373
+ let advancing = match self.watermark(side) {
374
+ Some(held) if value < held => return Err(Refusal::WatermarkRegressed),
375
+ Some(held) if value == held => return Ok(Advancing::Repeated),
376
+ Some(_) | None => Advancing::Advanced,
377
+ };
378
+ match side {
379
+ Side::Left => self.left_watermark = Watermark::at(value),
380
+ Side::Right => self.right_watermark = Watermark::at(value),
381
+ }
382
+ Ok(advancing)
383
+ }
384
+
385
+ /// Advance or repeat one input's progress from a caller-owned [`Watermark`].
386
+ ///
387
+ /// Honoured exactly when the side then equals `source`. A `source` with a
388
+ /// value behaves as [`advance_watermark`](Self::advance_watermark) with
389
+ /// that value. A `source` with no value yet has nothing to report: while
390
+ /// the side is uninitialized too they already agree, which is
391
+ /// [`Advancing::Repeated`]. It never clears a side.
392
+ ///
393
+ /// # Errors
394
+ /// [`Refusal::WatermarkRegressed`] when `source` is behind the side: its
395
+ /// value is lower, or it has none while the side holds one. Nothing changes.
396
+ pub const fn advance_watermark_from(
397
+ &mut self,
398
+ side: Side,
399
+ source: &Watermark,
400
+ ) -> Result<Advancing, Refusal> {
401
+ match (source.value(), self.watermark(side)) {
402
+ (Some(value), Some(_) | None) => self.advance_watermark(side, value),
403
+ (None, None) => Ok(Advancing::Repeated),
404
+ (None, Some(_)) => Err(Refusal::WatermarkRegressed),
405
+ }
406
+ }
407
+
408
+ /// Held records [`retire`](Self::retire) would remove right now: those
409
+ /// both watermarks have finished.
410
+ #[must_use]
411
+ pub fn retirable(&self) -> usize {
412
+ [Side::Left, Side::Right]
413
+ .into_iter()
414
+ .map(|side| {
415
+ self.records(side)
416
+ .filter(|held| self.finished(side, held.timestamp))
417
+ .count()
418
+ })
419
+ .sum()
420
+ }
421
+
422
+ /// Remove the records both watermarks have finished; returns how many.
423
+ ///
424
+ /// A held record is finished when both hold: the opposite watermark has
425
+ /// reached the end of its reach (`timestamp + after` for a left record,
426
+ /// `timestamp + before` for a right one, saturating at `u64::MAX`), so no
427
+ /// opposite record [`insert`](Self::insert) would still accept can match
428
+ /// it; and its own side's watermark has reached its timestamp, so the same
429
+ /// record offered again is [`Refusal::Late`]. Hence no pair is ever owed
430
+ /// twice and no record that could still match is dropped. A record whose
431
+ /// own watermark lags stays held, whatever the opposite one says.
432
+ /// At most `out.len()` records leave per call, left input first; the rest
433
+ /// stay held and [`retirable`](Self::retirable) until a later call.
434
+ ///
435
+ /// # Errors
436
+ /// [`Refusal::Pending`] while pairs are owed, so no owed pair can lose a
437
+ /// partner. Nothing changes.
438
+ pub fn retire(&mut self, out: &mut [Retired]) -> Result<usize, Refusal> {
439
+ if self.probe.is_some() {
440
+ return Err(Refusal::Pending);
441
+ }
442
+ let mut written = 0;
443
+ for side in [Side::Left, Side::Right] {
444
+ for index in 0..self.capacity(side) {
445
+ let Some(slot) = out.get_mut(written) else {
446
+ return Ok(written);
447
+ };
448
+ let Some(record) = self.slots(side).get(index).copied().flatten() else {
449
+ continue;
450
+ };
451
+ if !self.finished(side, record.timestamp) {
452
+ continue;
453
+ }
454
+ let Some(record) = self.slots_mut(side).get_mut(index).and_then(Option::take)
455
+ else {
456
+ debug_assert!(false, "the record just read at this slot is still there");
457
+ continue;
458
+ };
459
+ *slot = Retired { side, record };
460
+ // At most `out.len()`.
461
+ written += 1;
462
+ }
463
+ }
464
+ Ok(written)
465
+ }
466
+
467
+ /// The live record on `side` using this identity.
468
+ fn held(&self, side: Side, id: u64) -> Option<Record> {
469
+ self.records(side).copied().find(|held| held.id == id)
470
+ }
471
+
472
+ /// The live records on `side`, in slot order.
473
+ fn records(&self, side: Side) -> impl Iterator<Item = &Record> {
474
+ self.slots(side).iter().flatten()
475
+ }
476
+
477
+ const fn slots(&self, side: Side) -> &[Option<Record>] {
478
+ match side {
479
+ Side::Left => &self.left,
480
+ Side::Right => &self.right,
481
+ }
482
+ }
483
+
484
+ const fn slots_mut(&mut self, side: Side) -> &mut [Option<Record>] {
485
+ match side {
486
+ Side::Left => &mut self.left,
487
+ Side::Right => &mut self.right,
488
+ }
489
+ }
490
+
491
+ /// Whether `side`'s own watermark has reached `timestamp`: a record there
492
+ /// that is not held is [`Refusal::Late`].
493
+ ///
494
+ /// The one lateness test. `insert` refuses by it and `finished` requires
495
+ /// it, so "retired" implies "late on replay" by construction, and for
496
+ /// good: an honoured advance never lowers a watermark.
497
+ fn passed(&self, side: Side, timestamp: u64) -> bool {
498
+ self.watermark(side).is_some_and(|own| timestamp <= own)
499
+ }
500
+
501
+ /// Whether a held `side` record at `timestamp` may be retired. Both hold:
502
+ ///
503
+ /// 1. The opposite watermark has reached the end of the record's reach,
504
+ /// `other >= reach.last`. An opposite record is accepted only above its
505
+ /// own watermark, `u > other >= reach.last`, which is outside the
506
+ /// reach, so no future opposite record matches. One short
507
+ /// (`other == reach.last - 1`) a record at `reach.last` is still
508
+ /// accepted and matches, so the test is exact. A reach that saturates
509
+ /// at `u64::MAX` is reached only by `other == u64::MAX`, where no
510
+ /// opposite record is accepted at all.
511
+ /// 2. The record's own watermark has reached it ([`passed`](Self::passed)),
512
+ /// so the same record offered again is `Late`.
513
+ ///
514
+ /// The one retirement test, used by `retire` and `retirable`.
515
+ fn finished(&self, side: Side, timestamp: u64) -> bool {
516
+ let last = self.bounds.reach(side, timestamp).last;
517
+ let unmatchable = self
518
+ .watermark(side.other())
519
+ .is_some_and(|other| other >= last);
520
+ unmatchable && self.passed(side, timestamp)
521
+ }
522
+
523
+ /// The first pair `record` on `side` owes from opposite slot `from` on,
524
+ /// or `None` when it owes no more.
525
+ fn settle(&self, side: Side, record: Record, from: usize) -> Option<Probe> {
526
+ let reach = self.bounds.reach(side, record.timestamp);
527
+ self.slots(side.other())
528
+ .iter()
529
+ .enumerate()
530
+ .skip(from)
531
+ .find_map(|(cursor, held)| {
532
+ held.filter(|held| held.key == record.key && reach.contains(held.timestamp))
533
+ .map(|other| Probe {
534
+ side,
535
+ record,
536
+ cursor,
537
+ other,
538
+ })
539
+ })
540
+ }
541
+
542
+ /// The pair owed after `probe`.
543
+ fn next(&self, probe: Probe) -> Option<Probe> {
544
+ // `cursor` is a slot position, far below `usize::MAX`.
545
+ self.settle(probe.side, probe.record, probe.cursor + 1)
546
+ }
547
+ }
548
+
549
+ #[cfg(test)]
550
+ mod tests;
@@ -0,0 +1,41 @@
1
+ //! The one refusal type of the crate.
2
+
3
+ use core::fmt;
4
+
5
+ /// Why a call changed nothing.
6
+ ///
7
+ /// [`Join::insert`](crate::Join::insert) answers [`Mismatch`](Self::Mismatch),
8
+ /// [`Pending`](Self::Pending), [`Late`](Self::Late) or [`Full`](Self::Full);
9
+ /// [`Join::retire`](crate::Join::retire) answers [`Pending`](Self::Pending);
10
+ /// [`Join::advance_watermark`](crate::Join::advance_watermark) and
11
+ /// [`Join::advance_watermark_from`](crate::Join::advance_watermark_from) answer
12
+ /// [`WatermarkRegressed`](Self::WatermarkRegressed).
13
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
14
+ pub enum Refusal {
15
+ /// Pairs from the previous insert are still owed; drain them first.
16
+ Pending,
17
+ /// The record's timestamp is at or below its own side's watermark. The
18
+ /// opposite watermark never makes a record late.
19
+ Late,
20
+ /// A held record on that side uses this identity with another key or
21
+ /// timestamp. (The same contents are an honoured repeat, not a refusal.)
22
+ Mismatch,
23
+ /// That side has no free slot; advance watermarks and retire.
24
+ Full,
25
+ /// The watermark is behind the one that side already holds.
26
+ WatermarkRegressed,
27
+ }
28
+
29
+ impl fmt::Display for Refusal {
30
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31
+ f.write_str(match self {
32
+ Self::Pending => "pairs from the previous insert are still owed",
33
+ Self::Late => "record is at or below its side's watermark",
34
+ Self::Mismatch => "a held record on that side uses this identity with other contents",
35
+ Self::Full => "that side has no free slot",
36
+ Self::WatermarkRegressed => "watermark is behind the one the side holds",
37
+ })
38
+ }
39
+ }
40
+
41
+ impl core::error::Error for Refusal {}
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "join_machines_native"
3
+ version = "0.1.7"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ publish = false
8
+
9
+ [lib]
10
+ crate-type = ["cdylib"]
11
+ test = false
12
+ doctest = false
13
+
14
+ [dependencies]
15
+ join-machines.workspace = true
16
+ magnus.workspace = true
17
+ rb-sys.workspace = true
18
+ matryona-machines = { workspace = true, features = ["ruby"] }
19
+
20
+ [lints]
21
+ workspace = true
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+ require 'mkmf'
3
+ require 'pathname'
4
+ require 'rb_sys/mkmf'
5
+
6
+ create_rust_makefile('join_machines_native/join_machines_native') do |e|
7
+ e.ext_dir = Pathname(__dir__).relative_path_from(Pathname(Dir.pwd)).to_s
8
+ e.profile = ENV.fetch('RB_SYS_CARGO_PROFILE', :release).to_sym
9
+ end
10
+ makefile = File.join(Dir.pwd, 'Makefile')
11
+ File.write(makefile, File.read(makefile).gsub(
12
+ /^RB_SYS_CARGO_MANIFEST_DIR \?=.*$/,
13
+ "RB_SYS_CARGO_MANIFEST_DIR ?= #{File.expand_path(__dir__)}"
14
+ ))
@@ -0,0 +1,57 @@
1
+ //! The gem's `Data` classes, resolved once when the extension loads.
2
+ //!
3
+ //! Sealing in Ruby stops accidents, not reflection: a subclass constant is
4
+ //! bound before `inherited` raises, `Data#initialize` can be bound directly
5
+ //! and `Marshal.load` skips `initialize`. So the binding is the authority: a
6
+ //! value it reads must be an instance of exactly the sealed class, its members
7
+ //! are read natively (no method is dispatched) and the caller re-validates
8
+ //! them through the core.
9
+ use magnus::{Error, RModule, Ruby, Value, prelude::*};
10
+ use matryona_machines::ruby::{Class, exact_fields};
11
+
12
+ /// `JoinMachines::Reach`, `Bounds`, `Pair`, `Record`, `Retired`, `Watermark`.
13
+ pub struct Classes {
14
+ pub reach: Class,
15
+ pub bounds: Class,
16
+ pub pair: Class,
17
+ pub record: Class,
18
+ pub retired: Class,
19
+ pub watermark: Class,
20
+ }
21
+
22
+ matryona_machines::registry! {
23
+ static CLASSES: Classes = "join_machines";
24
+ /// The classes resolved at init.
25
+ pub fn classes;
26
+ }
27
+
28
+ /// Resolve and pin the classes Ruby defined before loading the extension.
29
+ pub fn resolve(ruby: &Ruby, module: RModule) -> Result<(), Error> {
30
+ let class = |name| Class::resolve(ruby, module, name);
31
+ let classes = Classes {
32
+ reach: class("Reach")?,
33
+ bounds: class("Bounds")?,
34
+ pair: class("Pair")?,
35
+ record: class("Record")?,
36
+ retired: class("Retired")?,
37
+ watermark: class("Watermark")?,
38
+ };
39
+ CLASSES.set(ruby, classes).map(drop)
40
+ }
41
+
42
+ /// A new value of `class`, through its own `new` (so through its check).
43
+ pub fn build<A: magnus::ArgList>(ruby: &Ruby, class: Class, args: A) -> Result<Value, Error> {
44
+ class.get(ruby).funcall("new", args)
45
+ }
46
+
47
+ /// The `N` members of `value`, read from the struct (no reader runs), when
48
+ /// `value` is an instance of exactly `class` (`instance_of?`, not `is_a?`);
49
+ /// `TypeError` with `message` otherwise.
50
+ pub fn members<const N: usize>(
51
+ ruby: &Ruby,
52
+ value: Value,
53
+ class: Class,
54
+ message: &'static str,
55
+ ) -> Result<[Value; N], Error> {
56
+ exact_fields::<N>(ruby, value, class.get(ruby), message)
57
+ }