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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! The [`MediaTimeRange`] primitive: the newtype, its interval filter and that filter's storage-side
//! comparison.

use crate::{CompositeFilterMarker, CompositeMarker, DefaultMarker, ScalarFilter, ToGraphqlInput};
use mediatime as mt;

use super::{MediaInstantBound, MediaTimestamp, NanosecondOverflow, TimebaseFilter};
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::{MediaTimeRangeCrossingError, SqlMediaTimeRangeComparison};
pub use storage::{InvertedMediaTimeRange, MediaTimeRangeLeaf};

/// A half-open interval `[start, end)`, both endpoints in one [`Timebase`], wrapping
/// [`mediatime::TimeRange`].
///
/// # The invariant, and exactly how far the guarantee reaches
///
/// `mediatime::TimeRange::new` panics on `start > end` and `try_new` returns `None`, and NEITHER
/// route is reachable from a client: the schema declares no input object, so a request cannot hand
/// a resolver two endpoints to build a range out of.
///
/// The guarantee is therefore about the wire, not about the type. `mediatime`'s `with_start`/
/// `set_start`/`with_end`/`set_end` re-check nothing, so `MediaTimeRange::new(0, 10, tb).with_start(100)`
/// yields a range whose start is after its end, and this newtype wraps whatever it is handed. A
/// value that arrives through [`From`] is exactly as well-formed as the value that was passed in.
///
/// [`Timebase`]: super::Timebase
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MediaTimeRange(mt::TimeRange);

impl MediaTimeRange {
  /// Wrap a [`mediatime::TimeRange`].
  ///
  /// The `const` route in; [`From`] is the other one and is not `const`. Neither re-checks the
  /// ordering invariant — see the type docs for how far the guarantee reaches.
  #[inline]
  pub const fn new(range: mt::TimeRange) -> Self {
    Self(range)
  }

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

  /// The endpoints in the storage form: `(start, end)` as `i64` NANOSECONDS.
  ///
  /// Two columns, in the one unit every stored row shares — the same normalization, and for the
  /// same reason, as [`MediaTimestamp::to_nanos`].
  ///
  /// # Errors
  ///
  /// [`NanosecondOverflow`] when either endpoint does not fit `i64` nanoseconds. `start` is
  /// converted first, so a range whose both endpoints are out of range reports `start`.
  #[inline]
  pub const fn to_nanos(self) -> Result<(i64, i64), NanosecondOverflow> {
    let timebase = self.0.timebase();
    let start = MediaTimestamp::new(mt::Timestamp::new(self.0.start_pts(), timebase));
    let end = MediaTimestamp::new(mt::Timestamp::new(self.0.end_pts(), timebase));

    match (start.to_nanos(), end.to_nanos()) {
      (Ok(start), Ok(end)) => Ok((start, end)),
      (Err(overflow), _) | (_, Err(overflow)) => Err(overflow),
    }
  }

  /// The start endpoint, as the [`MediaTimestamp`] it is.
  #[inline]
  #[must_use]
  pub const fn start(&self) -> MediaTimestamp {
    MediaTimestamp::new(self.0.start())
  }

  /// The end endpoint, as the [`MediaTimestamp`] it is. EXCLUDED from the interval — see the type docs.
  #[inline]
  #[must_use]
  pub const fn end(&self) -> MediaTimestamp {
    MediaTimestamp::new(self.0.end())
  }

  /// The span's LENGTH on the timeline, in nanoseconds — `end - start`, as the interval algebra's
  /// duration facet compares it.
  ///
  /// A DIFFERENCE OF TWO TRUNCATIONS rather than the exact rational length: each endpoint rounds
  /// toward zero on its way into nanoseconds, so this can be one nanosecond away from the length the
  /// two `pts` values name exactly. That is why the duration facet offers BOUNDS and no equality —
  /// see [`MediaSpanDurationFilter`].
  ///
  /// # Errors
  ///
  /// [`NanosecondOverflow`] when either endpoint has no `i64` nanosecond position; `start` is
  /// converted first, so a range with both out of range reports `start`.
  #[inline]
  pub const fn duration_nanos(self) -> Result<i64, NanosecondOverflow> {
    match self.to_nanos() {
      // The subtraction cannot overflow where both endpoints fit and the range is well formed:
      // `end >= start` holds by construction, so the difference is in `0..=i64::MAX`.
      Ok((start, end)) => Ok(end.wrapping_sub(start)),
      Err(overflow) => Err(overflow),
    }
  }
}

impl From<mt::TimeRange> for MediaTimeRange {
  #[inline]
  fn from(range: mt::TimeRange) -> Self {
    Self(range)
  }
}

impl From<MediaTimeRange> for mt::TimeRange {
  #[inline]
  fn from(range: MediaTimeRange) -> Self {
    range.0
  }
}

/// A whole range, on its way IN as an IDENTITY operand — the exact encoding, and nothing that
/// merely names a pair of positions.
///
/// [`MediaSpanBound`]'s narrow twin, and the pair is [`MediaTimestampOperand`](super::MediaTimestampOperand)
/// beside [`MediaInstantBound`] one type down: the wide door takes anything that names a position, the
/// narrow one takes only what names a VALUE. A `{ start, end }` of two bounds lands in `NANOS` and
/// is a perfectly good operand for `overlaps`; as an identity it would compare against columns no
/// stream wrote, so this door does not take it.
///
/// 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. The binding's half
/// is the `#[Scalar]` in `graphql`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MediaTimeRangeOperand(MediaTimeRange);

impl MediaTimeRangeOperand {
  /// Wrap a [`MediaTimeRange`] as an identity operand.
  #[inline]
  #[must_use]
  pub const fn new(range: MediaTimeRange) -> Self {
    Self(range)
  }

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

impl From<MediaTimeRange> for MediaTimeRangeOperand {
  #[inline]
  fn from(range: MediaTimeRange) -> Self {
    Self(range)
  }
}

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

/// A pair of positions, on its way IN: `{ start, end }` or the exact `"[100, 250) @ 1/90000"`.
///
/// A `…Bound` and not a `…Operand` because the suffix states the SHAPE the door takes: an
/// `…Operand` carries an identity to match, a `…Bound` an edge to compare against, and both halves
/// of this pair are edges — each an [`MediaInstantBound`] in its own right.
///
/// 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. The binding's half
/// is the `#[Scalar]` in `graphql`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MediaSpanBound(MediaTimeRange);

impl MediaSpanBound {
  /// Wrap a [`MediaTimeRange`] as a bound.
  #[inline]
  #[must_use]
  pub const fn new(range: MediaTimeRange) -> Self {
    Self(range)
  }

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

impl From<MediaTimeRange> for MediaSpanBound {
  #[inline]
  fn from(range: MediaTimeRange) -> Self {
    Self(range)
  }
}

impl From<MediaSpanBound> for MediaTimeRange {
  #[inline]
  fn from(bound: MediaSpanBound) -> Self {
    bound.0
  }
}

/// What a `contains` operand may be: one position, or a whole span.///
/// 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. The binding's half
/// is the `#[Scalar]` in `graphql`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MediaContainedOperand(MediaContained);

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

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

impl From<MediaContained> for MediaContainedOperand {
  #[inline]
  fn from(contained: MediaContained) -> Self {
    Self(contained)
  }
}

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

/// The OPERAND's own crossing, so a `[MediaTimeRange]` column knows what one element looks like.
impl ToGraphqlInput for MediaTimeRange {
  type Input = MediaSpanBound;
  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 {
    MediaSpanBound::new(*operand)
  }
}

/// The three IDENTITY crossings this face's doors need, and why each is spelled on the wire type
/// rather than on the value.
///
/// A crossing is ONE row per type, and [`MediaTimeRange`] has already spent its row on the WIDE door
/// below: `overlaps` and `within` take anything that names a pair of positions, so `MediaTimeRange`
/// crosses as [`MediaSpanBound`]. `exact` is the narrow door over the same Rust type and cannot have a
/// second row — so the slot holds [`MediaTimeRangeOperand`], which crosses as itself. `contains` is the
/// same arrangement arrived at from the other side: [`MediaContained`] never had a crossing, its wire
/// form being the sum of two other doors' shapes.
impl ToGraphqlInput for MediaTimeRangeOperand {
  type Input = Self;
  type Error = core::convert::Infallible;

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

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

impl ToGraphqlInput for MediaContainedOperand {
  type Input = Self;
  type Error = core::convert::Infallible;

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

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

/// What guards a [`MediaTimeRange`] column — [`Timebase`]'s row, and the same reading of it.
///
/// [`Timebase`]: super::Timebase
impl CompositeFilterMarker for MediaTimeRange {
  type Filter = MediaTimeRangeFilter;
  type ColumnFilter = MediaTimeRangeFilter;
}

/// The interpretation a [`MediaTimeRange`] field is read under — the framework's COMPOSITE reading, the
/// third of the citizens to take it and for their reason.
impl DefaultMarker for MediaTimeRange {
  type Marker = CompositeMarker<MediaTimeRange>;
}

/// **A COLLECTION of spans is asked through the QUANTIFIERS alone** — the row the wall-clock
/// [`TimeRange`](crate::TimeRange) publishes, transferred rather than re-derived, because the
/// argument it rests on is a fact about RANGES rather than about which timeline they sit on.
///
/// Every question this house can ask about ONE span lives in [`MediaTimeRangeFilter`], and `any`
/// carries that filter WHOLE — so *is there a span meeting the first two seconds* is
/// `any: { overlaps: … }`, and `count` is *how many spans are there*. Those two are what a caller
/// asks of a speech-segment list, a scene list or a cue list, which is the shape this row exists
/// for.
///
/// What a [`ListFilter`](crate::ListFilter) would add over them is seven operators holding a WHOLE
/// span, and the four comparison ones are not questions this element can answer honestly: `gt`,
/// `gte`, `lt` and `lte` compare two collections LEXICOGRAPHICALLY under an order over the ELEMENT,
/// and a span HAS no such order — by start, by end and by length are three different answers, which
/// is why neither this type nor `mediatime`'s own carries [`Ord`]. The other three reduce to
/// equality on both endpoints, which `any: { start: { exact: … }, end: { exact: … } }` already asks
/// and asks more legibly.
impl crate::DefaultVecMarker for MediaTimeRange {
  type Marker = crate::QuantifiedMarker<Vec<MediaTimeRange>>;
}

/// What `contains` was handed: one INSTANT, or a whole SPAN.
///
/// One operator over two operand shapes rather than two operators, because a client asking "does
/// this range contain that" means one thing and the answer differs only in how many endpoints the
/// question has. The two predicates are stated on [`MediaTimeRangeFilter`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MediaContained {
  /// A single position: the range holds it.
  Instant(MediaTimestamp),
  /// A whole span: the range holds all of it.
  Span(MediaTimeRange),
}

/// The DURATION facet: bounds on the span's length, and no equality.
///
/// # Four operators, and the two that are missing are missing on purpose
///
/// The compared quantity is [`MediaTimeRange::duration_nanos`] — a difference of two TRUNCATIONS, each
/// endpoint having rounded toward zero on its way into nanoseconds. So it can sit one nanosecond
/// from the length the two `pts` values name exactly, and an `eq` over it would be a question about
/// that rounding rather than about the range. A bound is untouched by the same nanosecond: "longer
/// than five seconds" admits the same rows either way.
///
/// The operands are WIDE, on the ordering facet's own terms — `{ seconds }`, `{ nanos }`, a clock
/// string, or the exact `ticks @ num/den` a `mediatime::SignedDuration` spells. A length has no
/// identity to protect, so there is no narrow twin.
/// A LENGTH, on its way IN: `{ seconds }`, `{ nanos }`, a clock, or the exact `"ticks @ num/den"`.
///
/// The carrier [`MediaSpanDurationFilter`]'s four slots hold, and the ORPHAN RULE is what forces it: the
/// length itself is `mediatime::SignedDuration`, and a crossing spelled on that type would have this
/// crate implementing a foreign trait for a foreign type. So the wire newtype IS the slot's carrier
/// and crosses as itself.
///
/// Declared UNGATED for the ungated-operand rule's reason — a crossing says which FORM an operand
/// takes and asks nothing about who parses that form. The binding's half is the `#[Scalar]` in
/// `graphql`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MediaDurationBound(mt::SignedDuration);

impl MediaDurationBound {
  /// Wrap a `mediatime::SignedDuration` as a bound.
  #[inline]
  #[must_use]
  pub const fn new(duration: mt::SignedDuration) -> Self {
    Self(duration)
  }

  /// The wrapped duration.
  #[inline]
  #[must_use]
  pub const fn get(&self) -> mt::SignedDuration {
    self.0
  }
}

impl From<mt::SignedDuration> for MediaDurationBound {
  #[inline]
  fn from(duration: mt::SignedDuration) -> Self {
    Self(duration)
  }
}

impl From<MediaDurationBound> for mt::SignedDuration {
  #[inline]
  fn from(bound: MediaDurationBound) -> Self {
    bound.0
  }
}

/// The LENGTH door's crossing, which is the identity: the operand's own type is the carrier, there
/// being no local type underneath it for the wire form to convert into.
impl ToGraphqlInput for MediaDurationBound {
  type Input = Self;
  type Error = core::convert::Infallible;

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

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

/// # The wire face is DECLARED, not written
///
/// `#[ingraph(composed(shorthand = false))]`: the four slots below are the whole registration, and
/// the declined word is the SHORTHAND. A bare value here would have to mean one of the four and
/// none of them is the obvious one — `duration: "0:00:05"` could as readily be *at least* as *at
/// most* — so a client names the bound it wants. The refusal now lists the operators off the
/// PUBLISHED table rather than off a sentence written beside it.
#[derive(Debug, Clone, Copy, PartialEq, Default, ingraph::Filter)]
#[ingraph(composed(shorthand = false))]
pub struct MediaSpanDurationFilter {
  gt: Option<MediaDurationBound>,
  gte: Option<MediaDurationBound>,
  lt: Option<MediaDurationBound>,
  lte: Option<MediaDurationBound>,
}

impl MediaSpanDurationFilter {
  /// The empty facet — no bound set.
  #[inline]
  pub const fn new() -> Self {
    Self {
      gt: None,
      gte: None,
      lt: None,
      lte: None,
    }
  }

  /// True while no bound is set.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.gt.is_none() && self.gte.is_none() && self.lt.is_none() && self.lte.is_none()
  }

  opt_accessor!(gt: MediaDurationBound => with_gt, set_gt, maybe_gt, update_gt);
  opt_accessor!(gte: MediaDurationBound => with_gte, set_gte, maybe_gte, update_gte);
  opt_accessor!(lt: MediaDurationBound => with_lt, set_lt, maybe_lt, update_lt);
  opt_accessor!(lte: MediaDurationBound => with_lte, set_lte, maybe_lte, update_lte);
}

/// The filter that guards a [`MediaTimeRange`] column: the INTERVAL ALGEBRA, the span's LENGTH, and the
/// three components a row actually holds.
///
/// Not the scalar operators: a range is not ordered by one number, and "greater than" over an
/// interval names no relation anybody wants. What a client asks of an interval is where it sits
/// relative to another interval or to an instant, which is the algebra below.
///
/// # `exact` is the one IDENTITY here, and it is the only whole-value seat
///
/// A range has no `eq`, and the reason is on the algebra: an interval is not equal to a point or to
/// another interval in any sense a client asks for. What a client does ask for is *the row I wrote*
/// — and until this seat existed the only way to spell it was three component filters, which meant
/// taking the crate's own rendering apart in the client:
///
/// ```text
///   before   startPts: { eq: 100 }, endPts: { eq: 250 }, timebase: { eq: "MPEG_90K" }
///   now      exact: "[100, 250) @ MPEG_90K"
/// ```
///
/// The second is the string [`MediaSpanBound`](super::MediaSpanBound) writes back, so a span read off this
/// schema is a span that can be sent to it. That round trip is what earns the seat: the components
/// were never WRONG, they were unreachable from the vocabulary the rest of the type speaks.
///
/// It differs from [`MediaTimestampFilter`](super::MediaTimestampFilter)'s `exact` in what it closes. There,
/// `exact` sits beside a semantic `eq` that inherits a truncation, and the pair are two honest
/// identities; here there is no lossy twin and nothing to correct — the gap was the VOCABULARY
/// alone. Both are the same law seen twice: an identity operand must reach the columns the write
/// path filled, and by the same route.
///
/// `exact` lowers to the FOUR value columns and touches neither derived position, so a range whose
/// endpoints have no `i64` nanosecond position is still findable by the encoding that wrote it.
///
/// # The predicates
///
/// The interval is HALF-OPEN, `[start, end)`, which `mediatime` documents on the type, and every
/// predicate is derived from that rather than guessed. `self` is the stored range; the operand is
/// what the client supplied. These are the contract a lowering must reproduce, and the SQL each
/// lowers to is on [`SqlMediaTimeRangeComparison`]:
///
/// | operator | holds | true when |
/// |---|---|---|
/// | `contains` | an instant `t` | `start <= t && t < end` |
/// | `contains` | a span `[a, b)` | `start <= a && end >= b` |
/// | `overlaps` | a span `[a, b)` | `start < b && end > a` |
/// | `within` | a span `[a, b)` | `start >= a && end <= b` |
/// | `before` | an instant `t` | `end <= t` |
/// | `after` | an instant `t` | `start >= t` |
///
/// Three asymmetries in that table are the half-openness showing through, and all three are
/// load-bearing. `contains` an INSTANT admits `t == start` and refuses `t == end`, so a stored
/// instant belongs to exactly one of two abutting ranges. `contains` a SPAN admits `end == b`,
/// because the operand's own end is excluded from it too and `[0, 10)` does contain `[0, 10)`.
/// `overlaps` is strict on both sides, so `[0, 10)` and `[10, 20)` do NOT overlap — they abut, and
/// an intersection of width zero is empty.
///
/// # The components are what a row HOLDS, and that is why they are not two timestamps
///
/// Both endpoints are counted in ONE timebase, so a range is two counts and one citizen rather than
/// two timestamps. A `start: MediaTimestampFilter` facet would carry a timebase question that has no
/// column to reach — see [`storage`] for the layout. What is offered instead is the pair of counts
/// and the whole [`TimebaseFilter`], which is every column there is.
///
/// [`SqlMediaTimeRangeComparison`]: crate::primitives::mediatime::SqlMediaTimeRangeComparison
///
/// # The wire face is DECLARED, not written
///
/// `#[ingraph(composed(shorthand = false))]` — a range has no `eq`, so there is no slot a bare value
/// could land in, and the word refuses one by naming the relations instead. The ten slots below are
/// the whole registration.
///
/// Four of them hold a WIRE newtype rather than the value, and each says which of two doors it is:
/// `exact` takes [`MediaTimeRangeOperand`] where `overlaps`/`within` take the wide [`MediaSpanBound`] through
/// [`MediaTimeRange`]'s own crossing; `contains` takes [`MediaContainedOperand`], which is two doors' shapes
/// in one operand; `before`/`after` take [`MediaInstantBound`], the position door one type down. A
/// crossing is one row per type, so a Rust type serving two doors has to spell the second one on a
/// newtype — and the declaration is now where that is visible.
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed(shorthand = false))]
pub struct MediaTimeRangeFilter {
  exact: Option<MediaTimeRangeOperand>,
  contains: Option<MediaContainedOperand>,
  overlaps: Option<MediaTimeRange>,
  within: Option<MediaTimeRange>,
  before: Option<MediaInstantBound>,
  after: Option<MediaInstantBound>,
  duration: Option<MediaSpanDurationFilter>,
  start_pts: Option<ScalarFilter<i64>>,
  end_pts: Option<ScalarFilter<i64>>,
  timebase: Option<TimebaseFilter>,
}

impl MediaTimeRangeFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      exact: None,
      contains: None,
      overlaps: None,
      within: None,
      before: None,
      after: None,
      duration: None,
      start_pts: None,
      end_pts: None,
      timebase: None,
    }
  }

  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
  /// field.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.exact.is_none()
      && self.contains.is_none()
      && self.overlaps.is_none()
      && self.within.is_none()
      && self.before.is_none()
      && self.after.is_none()
      && match &self.duration {
        Some(duration) => duration.is_empty(),
        None => true,
      }
      && match &self.start_pts {
        Some(start_pts) => start_pts.is_empty(),
        None => true,
      }
      && match &self.end_pts {
        Some(end_pts) => end_pts.is_empty(),
        None => true,
      }
      && match &self.timebase {
        Some(timebase) => timebase.is_empty(),
        None => true,
      }
  }

  /// The bounds on this range's length.
  #[inline]
  pub const fn duration(&self) -> Option<&MediaSpanDurationFilter> {
    self.duration.as_ref()
  }

  /// The declared start count's own filter.
  #[inline]
  pub const fn start_pts(&self) -> Option<&ScalarFilter<i64>> {
    self.start_pts.as_ref()
  }

  /// The declared end count's own filter.
  #[inline]
  pub const fn end_pts(&self) -> Option<&ScalarFilter<i64>> {
    self.end_pts.as_ref()
  }

  /// The shared timebase's filter, whole — the nested citizen.
  #[inline]
  pub const fn timebase(&self) -> Option<&TimebaseFilter> {
    self.timebase.as_ref()
  }

  opt_accessor!(exact: MediaTimeRangeOperand => with_exact, set_exact, maybe_exact, update_exact);
  opt_accessor!(contains: MediaContainedOperand => with_contains, set_contains, maybe_contains, update_contains);
  opt_accessor!(overlaps: MediaTimeRange => with_overlaps, set_overlaps, maybe_overlaps, update_overlaps);
  opt_accessor!(within: MediaTimeRange => with_within, set_within, maybe_within, update_within);
  opt_accessor!(before: MediaInstantBound => with_before, set_before, maybe_before, update_before);
  opt_accessor!(after: MediaInstantBound => with_after, set_after, maybe_after, update_after);

  /// Replace the duration facet (consuming).
  #[must_use]
  #[inline]
  pub fn with_duration(mut self, duration: MediaSpanDurationFilter) -> Self {
    self.set_duration(duration);
    self
  }

  /// Replace the duration facet (in place).
  #[inline]
  pub fn set_duration(&mut self, duration: MediaSpanDurationFilter) -> &mut Self {
    self.duration = Some(duration);
    self
  }

  /// Replace the start count's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_start_pts(mut self, start_pts: ScalarFilter<i64>) -> Self {
    self.set_start_pts(start_pts);
    self
  }

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

  /// Replace the end count's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_end_pts(mut self, end_pts: ScalarFilter<i64>) -> Self {
    self.set_end_pts(end_pts);
    self
  }

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

  /// Replace the timebase's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_timebase(mut self, timebase: TimebaseFilter) -> Self {
    self.set_timebase(timebase);
    self
  }

  /// Replace the timebase's filter (in place).
  #[inline]
  pub fn set_timebase(&mut self, timebase: TimebaseFilter) -> &mut Self {
    self.timebase = Some(timebase);
    self
  }
}

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