ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! The [`Rate`] primitive: the newtype, the error its canonical spelling parses through, and the
//! filter that guards a column of it.

use core::{fmt, num::NonZeroI32, str::FromStr};

use crate::{ScalarFilter, ToGraphqlInput};
use mediatime as mt;
use smol_bytes::Utf8Bytes;

use crate::graphql::filter::opt_accessor;

#[cfg(feature = "sqlx")]
mod comparison;
#[cfg(feature = "async-graphql")]
mod graphql;
mod storage;

#[cfg(test)]
mod tests;

#[cfg(feature = "sqlx")]
pub use comparison::{RateCrossingError, SqlRateComparison};
pub use storage::{RateColumnError, RateCursor};
// Brought into scope for the declaration's `builder(entry = "checked_fps", …)` below, which the
// macro expands to a call resolved by METHOD RESOLUTION against `mediatime::Rate` — reachable only
// with the trait that provides it in scope, exactly as any other trait method would be.
//
// GATED, where the source crate had it ungated on the argument that the entry is a domain
// validation independent of `sqlx` and so belongs in scope on every road. That argument was true of
// a DOWNSTREAM declarer, where this crate's `sqlx` and the framework's were two words that could
// disagree; in the framework itself they are one, the emitted raise that calls this entry exists
// only under it, and an import in scope on a road with no caller is `unused_imports`. See the
// trait's own note, where the dissolved half of its sibling gate is written up.
#[cfg(feature = "sqlx")]
use storage::CheckedFps as _;

/// A frame or sample rate — the rational `num / den` EVENTS PER SECOND a stream declares, wrapping
/// [`mediatime::Rate`].
///
/// # The reciprocal of a [`Timebase`], and stored as ITSELF
///
/// `mediatime` builds a rate out of a timebase and the two rosters mirror each other entry for
/// entry: `Rate::FPS_29_97` is `30000/1001` and `Timebase::NTSC_VIDEO` is `1001/30000`, one value
/// read two ways. [`mediatime::Rate::to_timebase`] and `from_timebase` are the conversion, and they
/// SWAP the pair.
///
/// What this citizen stores is the RATE's own reading — `num = 30000`, `den = 1001` — and not the
/// reciprocal. A column holding "the timebase of the rate" would make every rate query a division
/// away from the number a client sent, and would leave two conventions for one column type with
/// nothing in the SQL to say which a given table follows. So the rule is that a column named for a
/// rate holds a rate, and the reciprocal lives at the type where it is asked for by name. A stream
/// that declares both stores both, in two fields, each in its own reading.
///
/// # `Ord` is kept, and no whole-value ordering reaches the filter
///
/// `mediatime` orders rates as rationals and here that order MEANS something — sixty frames a second
/// is genuinely more than thirty, where a coarser timebase is not a later instant. The order is
/// therefore left on the type.
///
/// It still does not reach [`RateFilter`], and the reason is the STORAGE rather than the semantics:
/// two columns order lexicographically on `(num, den)` while the rationals order by cross
/// multiplication, and the two disagree — `30/1` is the greater rate and the lower pair against
/// `24000/1001`. Answering `gt` would take a derived column holding the quotient, which is the shape
/// [`MediaTimestamp`](super::MediaTimestamp) takes for exactly this reason and which nothing has asked for
/// here. Until something does, the filter offers what the two columns can answer exactly.
///
/// **The `cursor` word asserts the LEXICOGRAPHIC one, and that is the order it should assert.** A
/// paging position is a place in the order a statement actually walks, and a statement walks
/// `ORDER BY "fps_num", "fps_den"` — so the total order the head word names is the columns' and not
/// [`Ord`]'s. The two disagreeing is the same fact recorded just above, read from the other end: a
/// page resumes exactly where the previous one stopped because the boundary and the `ORDER BY` are
/// one order, while [`Ord`] stays on the type for callers comparing rates as rationals in memory.
/// Nothing pages by the rational order, because nothing can sort by it in SQL.
///
/// # The type is DECLARED, and the words it writes are the words it can
///
/// `#[crate::fields(…)]` reads the manifest below — the two halves `mediatime::Rate` publishes —
/// and emits the wrapper, a reader per half, the conversion family in both directions, and the two
/// marker rows a holder resolves a `Rate` column through. `remote = "…"` is what makes any of it
/// legal: the orphan rule forbids attaching a face to `mediatime`'s type where that type is
/// declared, and a wrapper is the position where it can be. `filter = "RateFilter"` is a SWAP rather
/// than a refinement — no predicate is generated, and the composite marker row names [`RateFilter`]
/// at both of its seats, which is what the hand-written `CompositeFilterMarker` impl used to say.
///
/// # The second bite: `record` retires the hand `ColumnKind`/`Carrier`/`Assemble`
///
/// ingraph#380 (door (a) of ingraph#377) opened the fragment HEAD to a whole-value transform, and
/// `record(write = "Rate::head_reduced")` is this citizen spending it: the emitted bind now pushes
/// the REDUCED pair the way the hand `Carrier` used to, and the emitted `ColumnKind` names the same
/// two columns the hand one did. No `read` word — a reduced rate is a valid rate, so the raise wants
/// no mirror back, the case ingraph's own fixture built the bare-`write` arm for. See
/// [`storage`](self::storage) for the census, what stays, and why.
///
/// `builder(entry = "checked_fps", fallible)` is the companion the RAISE still needs regardless of
/// `write`/`read`: a wrapped fragment's raise rebuilds through the remote's own constructor, and
/// `mediatime::Rate` has no constructor of the infallible shape the seat's default expects — see
/// `storage::CheckedFps` for why and for the one rule it still refuses.
///
/// # The third bite: `cursor` mounts, and the hand `CursorValue` is retired
///
/// `cursor` at the head asserts that the declared field order is this fragment's total order, and
/// `record(<db>(cursor = "RateCursor"))` names the codec that writes it at each store — the eight
/// flat bytes this citizen always wrote, now declared rather than hung beside the declaration. The
/// bytes are unchanged, so tokens minted by the retired kit still resume.
///
/// Three dialects and not two: the fallible exemption of ingraph#394 holds only while EVERY declared
/// dialect mounts, and `sqlite`/`postgres`/`mysql` is what this crate's `sqlx` feature means by the
/// SQL family. Naming them costs no feature wall — the cursor seam is keyed on `crate::dialect`'s
/// ungated markers, and the per-dialect comparison pair a named dialect also mints rides that
/// dialect's own gate macro, which expands to nothing where the backend is absent. MongoDB is
/// deliberately not among them: this citizen's storage face is `sqlx`-gated throughout, so a Mongo
/// holder is a story that has never existed here, and it is one line to add when one does.
///
/// **One word it does NOT write is measured rather than deferred**, and it is a door the framework
/// has yet to open rather than a preference taken here. It is recorded at the hand-written face that
/// stays because of it:
///
/// | absent | what refused it | where the note is |
/// |---|---|---|
/// | `graphql` | `NonZeroI32` and `&'static str` answer no `ToGraphqlOutput`, so neither the declared denominator nor the roster name can be published | the `graphql` module |
///
/// [`Timebase`]: super::Timebase
#[crate::fields(
  record(
    sqlite(cursor = "RateCursor"),
    postgres(cursor = "RateCursor"),
    mysql(cursor = "RateCursor"),
    write = "Rate::head_reduced"
  ),
  cursor,
  entity,
  remote = "mediatime::Rate",
  filter = "RateFilter",
  builder(entry = "checked_fps", fallible)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Rate {
  /// The numerator — the count of events, never negative.
  #[ingraph(copy)]
  num: i32,
  /// The denominator — the seconds those events span, always positive.
  #[ingraph(copy)]
  den: NonZeroI32,
}

impl Rate {
  /// Wrap a [`mediatime::Rate`].
  ///
  /// The `const` route in; [`From`] is the other one, is emitted by the declaration, and is not
  /// `const`.
  #[inline]
  pub const fn new(rate: mt::Rate) -> Self {
    Self(rate)
  }

  /// The wrapped [`mediatime::Rate`].
  #[inline]
  pub const fn get(&self) -> mt::Rate {
    self.0
  }

  /// The storage form: the same rational in LOWEST TERMS, as the pair `(num, den)` the two columns
  /// hold.
  ///
  /// THE one reduction, and it is public so that it can be — [`Timebase::reduced`]'s law, over the
  /// other reading. A rate is written through these two columns and queried through the same two, so
  /// the write path and the crossing have to agree on which pair a rate becomes, and they agree by
  /// calling this rather than by each dividing correctly. A disagreement has no error to report and
  /// no wrong value to see: a row written from `60000/2002` and a filter binding `30000/1001` simply
  /// never meet.
  ///
  /// Total, and free of sign handling, for the reason the timebase's is: `mediatime`'s constructor
  /// refuses a negative half. `0/d` reduces to `0/1`.
  ///
  /// [`Timebase::reduced`]: super::Timebase::reduced
  #[inline]
  pub const fn reduced(&self) -> (i32, NonZeroI32) {
    let num = self.0.num();
    let den = self.0.den().get();
    let divisor = super::rational::gcd(num, den);

    match NonZeroI32::new(den / divisor) {
      Some(den) => (num / divisor, den),
      // `divisor` divides `den`, which is positive, so the quotient is at least one.
      None => unreachable!(),
    }
  }

  /// **THE SAME REDUCTION, AS A [`Rate`]** — [`Self::reduced`]'s pair, rebuilt.
  ///
  /// The shape `record(write = "…")` pins is `fn(&Self) -> Self`: the WHOLE value in and out,
  /// because the seat is spent at the bind and the cursor's write alike, and both carry a `Self`
  /// across the storage boundary rather than two loose integers. [`Self::reduced`] answers the pair
  /// those two hand sites still call directly — the cursor's write and
  /// [`comparison`](super::comparison)'s crossing — so this function does not replace it; it is the
  /// thinnest wrapper that could exist over it, kept separate so that the seat's own shape never
  /// moves what those two already call correctly.
  ///
  /// Infallible, though [`mt::Rate::try_fps`] answers an [`Option`]: [`Self::reduced`] divides both
  /// halves of an ALREADY VALID rate by their positive gcd, which preserves the sign of each half, so
  /// the pair it returns is always a valid rate. The `unreachable!` below is that argument and not a
  /// hope — [`Self::reduced`]'s own body carries the identical one, one call away.
  #[inline]
  pub const fn head_reduced(&self) -> Self {
    let (num, den) = self.reduced();
    match mt::Rate::try_fps(num, den) {
      Some(rate) => Self::new(rate),
      // `reduced` divides both halves of an already-valid rate by their positive gcd, which
      // preserves the sign of each half — the pair it returns is always a valid rate.
      None => unreachable!(),
    }
  }

  /// The rate as a floating-point count of events per second — `29.97002997…` for NTSC video.
  ///
  /// LOSSY and total: both halves are `i32`, which `f64` represents exactly, and the denominator
  /// cannot be zero. A rate of `0/1` is zero events per second, which is a real declaration and not
  /// an error.
  #[inline]
  #[must_use]
  pub fn per_second(&self) -> f64 {
    f64::from(self.0.num()) / f64::from(self.0.den().get())
  }
}

/// The canonical spelling, `num/den` — `mediatime`'s own rendering, forwarded.
///
/// Exact and unreduced: a rate is the pair the stream declared, so `60000/2002` renders as
/// `60000/2002` and not as the `30000/1001` it equals. That is what makes this the inverse of
/// [`FromStr`] rather than merely a display of it.
///
/// `mediatime` writes the same text under `{}` and `{:#}` — a rate has no second, lossy rendering
/// the way a timestamp has a clock — so there is one form here and nothing to choose between.
impl fmt::Display for Rate {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    self.0.fmt(f)
  }
}

impl FromStr for Rate {
  type Err = ParseRateError;

  /// Read the canonical `num/den` spelling — the text arm of what a whole-value filter operand may
  /// be.
  ///
  /// Whitespace is not trimmed and no other spelling is admitted, for the reason the timebase's
  /// parser admits none: an operand comes off a wire rather than out of a person's hand, and a
  /// tolerant parser here would let two spellings of one rate into a query.
  ///
  /// The ROSTER arm is not missing, it is one layer out — the wire face reads `"FPS_29_97"` through
  /// `mediatime::Rate::from_name` and this parser through the slash, and the slash tells them apart
  /// totally, no rate name containing one. Keeping the arms apart is what buys the error below its
  /// detail.
  ///
  /// # Errors
  ///
  /// [`ParseRateError`], naming the half or the rule that refused. The separator is the FIRST `/`,
  /// so `"1/2/3"` fails on its denominator rather than on its shape.
  fn from_str(text: &str) -> Result<Self, Self::Err> {
    let (num, den) = text
      .split_once('/')
      .ok_or(ParseRateError::MissingSeparator)?;

    let num = num.parse::<i32>().map_err(|_| ParseRateError::Numerator)?;
    let den = den
      .parse::<i32>()
      .map_err(|_| ParseRateError::Denominator)?;
    let den = NonZeroI32::new(den).ok_or(ParseRateError::ZeroDenominator)?;

    mt::Rate::try_fps(num, den)
      .map(Self)
      .ok_or(ParseRateError::NegativeHalf)
  }
}

/// A string does not name a [`Rate`].
///
/// One variant per way the canonical spelling can fail, rather than one opaque error, because the
/// operand arrives from a client: which half was wrong is the only part of the answer that tells the
/// client what to send instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseRateError {
  /// No `/`. A bare number is refused — see [`RateFilter`], where the reason is.
  MissingSeparator,
  /// The text before the `/` is not an `i32`.
  Numerator,
  /// The text after the FIRST `/` is not an `i32`.
  Denominator,
  /// The denominator is zero, which [`NonZeroI32`] forbids.
  ZeroDenominator,
  /// A half is negative, which `mediatime`'s constructor refuses.
  NegativeHalf,
}

impl fmt::Display for ParseRateError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let reason = match self {
      Self::MissingSeparator => "a rate is spelled num/den",
      Self::Numerator => "the numerator is not a 32-bit integer",
      Self::Denominator => "the denominator is not a 32-bit integer",
      Self::ZeroDenominator => "the denominator must not be zero",
      Self::NegativeHalf => "neither half may be negative",
    };

    f.write_str(reason)
  }
}

impl core::error::Error for ParseRateError {}

/// A whole rate, on its way IN — the carrier the value facet's four operators cross on.
///
/// A type of its own rather than [`Rate`], and GraphQL's shared name namespace is what forces it —
/// the same wall [`TimebaseOperand`](super::TimebaseOperand) is on the other side of.
///
/// Declared UNGATED, beside the type it carries, and the reason is the ungated-operand rule
/// this house's note states for its whole roster: a crossing says which FORM an operand takes and asks nothing about who parses that form, so it is a fact
/// about `Rate` rather than a piece of the GraphQL binding. The binding's half — the [`ScalarType`]
/// that reads the three arms and writes the canonical one — is in `graphql`, behind the feature.
///
/// [`ScalarType`]: https://docs.rs/async-graphql/latest/async_graphql/trait.ScalarType.html
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RateOperand(Rate);

impl RateOperand {
  /// Wrap a [`Rate`] as an operand.
  #[inline]
  #[must_use]
  pub const fn new(rate: Rate) -> Self {
    Self(rate)
  }

  /// The wrapped [`Rate`].
  #[inline]
  #[must_use]
  pub const fn get(&self) -> Rate {
    self.0
  }
}

impl From<Rate> for RateOperand {
  #[inline]
  fn from(rate: Rate) -> Self {
    Self(rate)
  }
}

impl From<RateOperand> for Rate {
  #[inline]
  fn from(operand: RateOperand) -> Self {
    operand.0
  }
}

/// The OPERAND's own crossing — the row a COLLECTION face reads to learn what one element of a
/// `[Rate]` looks like on the wire, and the row each of [`RateFilter`]'s four value slots resolves
/// through.
///
/// Infallible, because the validation is the scalar's: a [`RateOperand`] cannot exist holding a
/// value the door refused.
impl ToGraphqlInput for Rate {
  type Input = RateOperand;
  type Error = core::convert::Infallible;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Ok(input.into())
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    RateOperand::new(*operand)
  }
}

/// The filter that guards a [`Rate`] column: the three facets a rational stored in two columns can
/// honestly be asked about — [`TimebaseFilter`]'s shape, over the other reading.
///
/// | facet | slots | asks about |
/// |---|---|---|
/// | VALUE | `eq`, `ne`, `in_`, `not_in` | the whole rate, as a value |
/// | RENDER | `starts_with`, `ends_with`, `contains` | the `num/den` TEXT the two columns spell |
/// | COMPONENT | `numerator`, `denominator` | one half alone, with its own ordering |
///
/// Three shapes reach the value facet and one comes back — WIDE IN, STRICT OUT. A client may send
/// the structure `{ numerator: 30000, denominator: 1001 }`, the text `"30000/1001"`, or the roster
/// NAME `"FPS_29_97"` (case-folded, as `mediatime`'s own `from_name` folds it); all three name one
/// value, and the one spelling written back is the canonical text.
///
/// # A BARE NUMBER is refused, and the reason is not the timebase's
///
/// A timebase refuses `30` because it is ambiguous three ways — numerator, denominator, or tick
/// rate, all different values. A rate has no such trap: `30` as `30/1` and `30` as "thirty a second"
/// are the SAME rational, and only `1/30` reads differently, which nobody writes as `30`. So the
/// operand would not be ambiguous, and it is still refused. Two reasons, and the first is the one
/// that settles it:
///
/// - **The next thing a client writes is `29.97`, and that is a DIFFERENT RATE.** NTSC video is
///   `30000/1001` — `29.970029970…` — where `29.97` is `2997/100`. A door that took integers would
///   have to take the decimal beside them or explain why not, and taking it means either rounding to
///   whatever roster entry is near (guessing) or storing a rate no stream declares (silently wrong).
///   Refusing both is one rule; refusing one of them makes the grammar depend on whether the number
///   a client happened to send divides exactly, which is the same defect as an operator whose
///   meaning depends on its operand.
/// - **The forms it would save are already there.** `"30/1"`, `"FPS_30"` and
///   `{ numerator: 30, denominator: 1 }` all name thirty frames a second, and the shortest of them
///   is four characters.
///
/// # The render facet asks about the STORED spelling
///
/// Which is the reduced one — see [`Rate::reduced`]. `contains: "/1001"` finds a stream that
/// declared `60000/2002`, because that is the row the write path wrote. Three operators and not
/// twelve: the subject is two decimal integers and a slash, so there is no case to fold, and the
/// operand alphabet is `[0-9/]` with anything outside it refused at the crossing.
///
/// [`TimebaseFilter`]: super::TimebaseFilter
///
/// # The wire face is DECLARED, not written
///
/// The nine slots below are the whole of it: `#[ingraph(composed)]` reads this field list once and
/// emits the registration, the parse and the render from it, so the table exists in exactly one
/// place. The hand-written face this replaced carried it three times over — once in a
/// `filter_fields!` macro, once in `parse`, once in `bare_values` — and keeping those three agreeing
/// was a discipline rather than a fact.
///
/// # It is MOUNTED, not merely written beside the type
///
/// [`Rate`]'s declaration names this type at `filter = "RateFilter"`, which is a SWAP: no predicate
/// is generated, and the composite marker row names this one at both of its seats — the FULL face a
/// rowless host reads and the STORED face a row-holding one reads. That is the same statement the
/// hand-written [`CompositeFilterMarker`] impl made, now made by the declaration; the two faces are
/// one type here because a rate stores every field it declares, so there is no subset for them to
/// part over.
///
/// What a mount owes, and what this type already carried, is the lowering — a predicate's meaning
/// includes what it compares, so the [`ToDatabaseComparison`] row lives in
/// [`comparison`](super::comparison) beside the comparison it names rather than being emitted here.
///
/// [`CompositeFilterMarker`]: crate::CompositeFilterMarker
/// [`ToDatabaseComparison`]: crate::ToDatabaseComparison
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed)]
pub struct RateFilter {
  eq: Option<Rate>,
  ne: Option<Rate>,
  in_: Option<Box<[Rate]>>,
  not_in: Option<Box<[Rate]>>,
  starts_with: Option<Utf8Bytes>,
  ends_with: Option<Utf8Bytes>,
  contains: Option<Utf8Bytes>,
  numerator: Option<ScalarFilter<i32>>,
  denominator: Option<ScalarFilter<NonZeroI32>>,
}

impl RateFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      in_: None,
      not_in: None,
      starts_with: None,
      ends_with: None,
      contains: None,
      numerator: None,
      denominator: None,
    }
  }

  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
  /// field.
  ///
  /// A component slot FOLDS IN rather than counting as set: an absent one and a present one asking
  /// nothing are the same predicate, which is the emptiness law every nested filter slot answers by.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.eq.is_none()
      && self.ne.is_none()
      && self.in_.is_none()
      && self.not_in.is_none()
      && self.starts_with.is_none()
      && self.ends_with.is_none()
      && self.contains.is_none()
      && match &self.numerator {
        Some(numerator) => numerator.is_empty(),
        None => true,
      }
      && match &self.denominator {
        Some(denominator) => denominator.is_empty(),
        None => true,
      }
  }

  /// The numerator's own filter, over the REDUCED half — absent where the component was never
  /// asked about.
  #[inline]
  pub const fn numerator(&self) -> Option<&ScalarFilter<i32>> {
    self.numerator.as_ref()
  }

  /// The denominator's own filter, over the REDUCED half — absent where the component was never
  /// asked about.
  #[inline]
  pub const fn denominator(&self) -> Option<&ScalarFilter<NonZeroI32>> {
    self.denominator.as_ref()
  }

  opt_accessor!(eq: Rate => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: Rate => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(in_: [Rate] => with_in_, set_in_, maybe_in_, update_in_);
  opt_accessor!(not_in: [Rate] => with_not_in, set_not_in, maybe_not_in, update_not_in);
  opt_accessor!(
    starts_with: Utf8Bytes => with_starts_with, set_starts_with, maybe_starts_with,
    update_starts_with
  );
  opt_accessor!(
    ends_with: Utf8Bytes => with_ends_with, set_ends_with, maybe_ends_with, update_ends_with
  );
  opt_accessor!(contains: Utf8Bytes => with_contains, set_contains, maybe_contains, update_contains);

  /// Replace the numerator's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_numerator(mut self, numerator: ScalarFilter<i32>) -> Self {
    self.set_numerator(numerator);
    self
  }

  /// Replace the numerator's filter (in place).
  #[inline]
  pub fn set_numerator(&mut self, numerator: ScalarFilter<i32>) -> &mut Self {
    self.numerator = Some(numerator);
    self
  }

  /// Replace the denominator's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_denominator(mut self, denominator: ScalarFilter<NonZeroI32>) -> Self {
    self.set_denominator(denominator);
    self
  }

  /// Replace the denominator's filter (in place).
  #[inline]
  pub fn set_denominator(&mut self, denominator: ScalarFilter<NonZeroI32>) -> &mut Self {
    self.denominator = Some(denominator);
    self
  }
}

impl Default for RateFilter {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}