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
//! The storage side of a [`MediaTimeRange`] query, behind the `sqlx` feature: the interval algebra as
//! SQL over the two derived endpoint columns.
//!
//! ```text
//! MediaTimeRangeFilter                     rendered, at a field named `span`
//!   contains: "0:00:01.5"    ──►        "span_start_nanos" <= ? AND "span_end_nanos" > ?
//!   contains: {start,end}    ──►        "span_start_nanos" <= ? AND "span_end_nanos" >= ?
//!   overlaps: {start,end}    ──►        "span_start_nanos" <  ? AND "span_end_nanos" > ?
//!   within:   {start,end}    ──►        "span_start_nanos" >= ? AND "span_end_nanos" <= ?
//!   before:   "0:00:10"      ──►        "span_end_nanos" <= ?
//!   after:    "0:00:01"      ──►        "span_start_nanos" >= ?
//!   duration: { gte: … }     ──►        ("span_end_nanos" - "span_start_nanos") >= ?
//!   startPts: { gt: 0 }      ──►        "span_start_pts" > ?
//!   timebase: "MPEG_90K"     ──►        "span_timebase_num" = ? AND "span_timebase_den" = ?
//! ```
//!
//! # Each operator renders its OWN conjuncts, and that is what keeps them independent
//!
//! The obvious shape is to route the algebra through two
//! [`SqlScalarComparison`](crate::comparison::sql::SqlScalarComparison)s — one per endpoint
//! column — since every predicate above decomposes into inequalities on those two. It does not
//! survive contact with a client: `contains` and `overlaps` both want `end > ?`, so a filter naming
//! both would need one slot to hold two operands, and the choices are to refuse a legitimate pair of
//! questions or to keep whichever was written last.
//!
//! Rendering directly costs one helper and removes the interaction entirely. Every operator opens
//! its own conjuncts through the accumulator it is handed, so the count is the sum of the operators
//! and no two of them share anything.
//!
//! # `duration` is an EXPRESSION, and the only one here
//!
//! `(end - start)` is arithmetic over two columns rather than a column, so a bound on it cannot use
//! an index the way the endpoint bounds can. That is a real cost and it is the shape of the question
//! rather than a choice: a length is not stored, and the alternative — a seventh column holding it —
//! would be a third derived authority to keep in step with two others.
//!
//! Subtraction and not addition-on-the-other-side (`end >= start + ?`), because the two are the same
//! predicate and only the first says what it means. Both dodge overflow equally here: the operands
//! are `i64` nanoseconds that already fit, and the difference of two of them is what the write path
//! computed.
//!
//! # Refusals
//!
//! Three, and each is inherited rather than invented: an operand past `i64` nanoseconds, an operand
//! range whose endpoints run backwards, and the nested timebase citizen's own.
//!
//! [`MediaTimeRangeFilter`]: super::MediaTimeRangeFilter

use core::fmt::{self, Display};

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, CompositeComparison, FieldName,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{
    SqlConjunction, SqlLoweringError, SqlScalarComparison, push_column, render_column,
  },
};

use super::{
  super::{
    MediaTimestamp, NanosecondOverflow, SqlTimebaseComparison, Timebase, TimebaseCrossingError,
    timebase::{TIMEBASE_DEN, TIMEBASE_NUM},
  },
  MediaContained, MediaTimeRange, MediaTimeRangeFilter,
  storage::{END_NANOS, END_PTS, SEGMENTS, START_NANOS, START_PTS, TIMEBASE},
};

// The DIALECT this house's crossing tests render against is Postgres — its NUMBERED placeholders are
// what say which operand reached which column, where a `?` dialect can only say how many there were —
// so the module names `sqlx::Postgres` and needs that driver rather than the family root alone.
//
// The source crate carried a bare `#[cfg(test)]` here and never felt it, its own `sqlx` word arriving
// with a dialect behind it. In this crate `sqlx` is the family ROOT and a dialect is a word of its
// own, so the gate has to name the one it spells. It is the divergence the language family recorded
// on the same move — per-dialect gates replacing a single `sqlx` word — read one dialect over.
#[cfg(all(test, feature = "postgres"))]
mod tests;

/// What `contains` became at the crossing: one position, or a pair of them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ContainedNanos {
  Instant(i64),
  Span(i64, i64),
}

/// One encoding, in the four columns that hold it: both declared counts and the REDUCED timebase.
///
/// Reduced for the reason the timestamp's is — the timebase citizen's own storage law, met one level
/// up — and it costs nothing observable: two spellings of one timebase are one value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Encoding {
  start: i64,
  end: i64,
  num: i32,
  den: i32,
}

/// The duration facet's four bounds, in nanoseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct DurationNanos {
  gt: Option<i64>,
  gte: Option<i64>,
  lt: Option<i64>,
  lte: Option<i64>,
}

impl DurationNanos {
  const fn is_empty(&self) -> bool {
    self.gt.is_none() && self.gte.is_none() && self.lt.is_none() && self.lte.is_none()
  }

  const fn conjuncts(&self) -> usize {
    self.gt.is_some() as usize
      + self.gte.is_some() as usize
      + self.lt.is_some() as usize
      + self.lte.is_some() as usize
  }
}

/// [`MediaTimeRangeFilter`]'s storage-side twin: the algebra over the derived endpoints, the length, the
/// two declared counts, and the timebase citizen nested inside.
pub struct SqlMediaTimeRangeComparison<Db> {
  exact: Option<Encoding>,
  contains: Option<ContainedNanos>,
  overlaps: Option<(i64, i64)>,
  within: Option<(i64, i64)>,
  before: Option<i64>,
  after: Option<i64>,
  duration: DurationNanos,
  start_pts: SqlScalarComparison<i64, Db>,
  end_pts: SqlScalarComparison<i64, Db>,
  timebase: SqlTimebaseComparison<Db>,
}

impl<Db> SqlMediaTimeRangeComparison<Db> {
  /// The empty comparison — 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: DurationNanos {
        gt: None,
        gte: None,
        lt: None,
        lte: None,
      },
      start_pts: SqlScalarComparison::new(),
      end_pts: SqlScalarComparison::new(),
      timebase: SqlTimebaseComparison::new(),
    }
  }

  /// The encoding the four value columns must hold, or [`None`] where `exact` was not asked.
  ///
  /// Projected as the four storage numbers rather than as the domain value: the timebase half is
  /// REDUCED here, which is not always the timebase the client spelled.
  #[inline]
  pub const fn exact(&self) -> Option<(i64, i64, i32, i32)> {
    match self.exact {
      Some(Encoding {
        start,
        end,
        num,
        den,
      }) => Some((start, end, num, den)),
      None => None,
    }
  }

  /// The operators over the declared start count.
  #[inline]
  pub const fn start_pts(&self) -> &SqlScalarComparison<i64, Db> {
    &self.start_pts
  }

  /// The operators over the declared end count.
  #[inline]
  pub const fn end_pts(&self) -> &SqlScalarComparison<i64, Db> {
    &self.end_pts
  }

  /// The nested citizen's own comparison.
  #[inline]
  pub const fn timebase(&self) -> &SqlTimebaseComparison<Db> {
    &self.timebase
  }

  /// True while NO operator slot is set anywhere.
  #[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()
      && self.duration.is_empty()
      && self.start_pts.is_empty()
      && self.end_pts.is_empty()
      && self.timebase.is_empty()
  }

  /// How many conjuncts this comparison lowers to.
  ///
  /// EXACT, and counted per OPERATOR rather than per column: the two-sided members of the algebra
  /// open two each and the one-sided ones open one, which is what the rendering below does and is
  /// the only arithmetic here.
  #[inline]
  pub const fn conjuncts(&self) -> usize {
    self.exact.is_some() as usize * 4
      + self.contains.is_some() as usize * 2
      + self.overlaps.is_some() as usize * 2
      + self.within.is_some() as usize * 2
      + self.before.is_some() as usize
      + self.after.is_some() as usize
      + self.duration.conjuncts()
      + self.start_pts.conjuncts()
      + self.end_pts.conjuncts()
      + self.timebase.conjuncts()
  }
}

/// One inequality against one derived endpoint column — the whole of what the algebra renders.
///
/// The column is rendered through [`push_column`], as every leaf in the SQL family renders one, so
/// the joining and the bracketing stay the backend's.
fn endpoint<'q, Db>(
  builder: &mut SqlConjunction<'q, Db>,
  at: At<'_>,
  segment: &'static FieldName,
  operator: &'static str,
  operand: i64,
) where
  Db: sqlx::Database + Backend<Buffer: Display>,
  i64: Carrier<Db>,
{
  let frame = at.frame(segment);
  let qb = builder.open();
  push_column(qb, frame.at());
  qb.push(operator);
  <i64 as Carrier<Db>>::push_bind(&operand, qb);
}

/// One column equal to one operand — what the structural facet renders, four times.
fn equals<'q, Db, V>(builder: &mut SqlConjunction<'q, Db>, at: At<'_>, operand: V)
where
  Db: sqlx::Database + Backend<Buffer: Display>,
  V: Carrier<Db>,
{
  let qb = builder.open();
  push_column(qb, at);
  qb.push(" = ");
  operand.push_bind(qb);
}

/// The lowering: the identity, then the algebra, then the length, then the components.
impl<Db> ComplexComparison<Db> for SqlMediaTimeRangeComparison<Db>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: Db::Builder<'q>,
  ) -> Result<Db::Builder<'q>, Db::Error> {
    // The IDENTITY first, on the value columns — its own four conjuncts, sharing nothing with the
    // algebra below or with the component slots, so no two operators can want one slot.
    if let Some(Encoding {
      start,
      end,
      num,
      den,
    }) = self.exact
    {
      equals::<Db, i64>(&mut builder, at.frame(START_PTS).at(), start);
      equals::<Db, i64>(&mut builder, at.frame(END_PTS).at(), end);

      let timebase = at.frame(TIMEBASE);
      equals::<Db, i32>(&mut builder, timebase.at().frame(TIMEBASE_NUM).at(), num);
      equals::<Db, i32>(&mut builder, timebase.at().frame(TIMEBASE_DEN).at(), den);
    }

    // `[start, end)` is half-open, and every operator below is that fact written out — see
    // `MediaTimeRangeFilter`'s table, which these lines are the SQL of.
    match self.contains {
      Some(ContainedNanos::Instant(instant)) => {
        endpoint(&mut builder, at, START_NANOS, " <= ", instant);
        endpoint(&mut builder, at, END_NANOS, " > ", instant);
      }
      Some(ContainedNanos::Span(start, end)) => {
        endpoint(&mut builder, at, START_NANOS, " <= ", start);
        endpoint(&mut builder, at, END_NANOS, " >= ", end);
      }
      None => {}
    }

    if let Some((start, end)) = self.overlaps {
      endpoint(&mut builder, at, START_NANOS, " < ", end);
      endpoint(&mut builder, at, END_NANOS, " > ", start);
    }

    if let Some((start, end)) = self.within {
      endpoint(&mut builder, at, START_NANOS, " >= ", start);
      endpoint(&mut builder, at, END_NANOS, " <= ", end);
    }

    if let Some(before) = self.before {
      endpoint(&mut builder, at, END_NANOS, " <= ", before);
    }

    if let Some(after) = self.after {
      endpoint(&mut builder, at, START_NANOS, " >= ", after);
    }

    if !self.duration.is_empty() {
      // Rendered once for the four slots that each name both columns.
      let start = render_column::<Db>(at.frame(START_NANOS).at());
      let end = render_column::<Db>(at.frame(END_NANOS).at());

      for (operator, operand) in [
        (" > ", self.duration.gt),
        (" >= ", self.duration.gte),
        (" < ", self.duration.lt),
        (" <= ", self.duration.lte),
      ] {
        let Some(operand) = operand else {
          continue;
        };
        let qb = builder.open();
        qb.push("(");
        qb.push(&end);
        qb.push(" - ");
        qb.push(&start);
        qb.push(")");
        qb.push(operator);
        <i64 as Carrier<Db>>::push_bind(&operand, qb);
      }
    }

    let start_pts = at.frame(START_PTS);
    let builder = self.start_pts.apply(start_pts.at(), builder)?;
    let end_pts = at.frame(END_PTS);
    let builder = self.end_pts.apply(end_pts.at(), builder)?;
    let timebase = at.frame(TIMEBASE);
    self.timebase.apply(timebase.at(), builder)
  }
}

/// The claim `flatten` needs, read off the one list the storage face states.
impl<Db> CompositeComparison<Db> for SqlMediaTimeRangeComparison<Db>
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  const SEGMENTS: &'static [crate::ColumnShape] = SEGMENTS;
}

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

impl<Db> fmt::Debug for SqlMediaTimeRangeComparison<Db> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SqlMediaTimeRangeComparison")
      .field("exact", &self.exact)
      .field("contains", &self.contains)
      .field("overlaps", &self.overlaps)
      .field("within", &self.within)
      .field("before", &self.before)
      .field("after", &self.after)
      .field("duration", &self.duration)
      .field("start_pts", &self.start_pts)
      .field("end_pts", &self.end_pts)
      .field("timebase", &self.timebase)
      .finish()
  }
}

impl<Db> Clone for SqlMediaTimeRangeComparison<Db> {
  fn clone(&self) -> Self {
    Self {
      exact: self.exact,
      contains: self.contains,
      overlaps: self.overlaps,
      within: self.within,
      before: self.before,
      after: self.after,
      duration: self.duration,
      start_pts: self.start_pts.clone(),
      end_pts: self.end_pts.clone(),
      timebase: self.timebase.clone(),
    }
  }
}

impl<Db> PartialEq for SqlMediaTimeRangeComparison<Db> {
  fn eq(&self, other: &Self) -> bool {
    self.exact == other.exact
      && self.contains == other.contains
      && self.overlaps == other.overlaps
      && self.within == other.within
      && self.before == other.before
      && self.after == other.after
      && self.duration == other.duration
      && self.start_pts == other.start_pts
      && self.end_pts == other.end_pts
      && self.timebase == other.timebase
  }
}

/// Every SQL dialect takes the range filter to the range comparison, and the storage type is `i64` —
/// the derived columns', which is what a declaration names.
impl<Db> ToDatabaseComparison<i64, Db> for MediaTimeRangeFilter
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlMediaTimeRangeComparison<Db>;
}

/// **The same comparison, keyed by the CITIZEN** — the row a field declared `MediaTimeRange`
/// resolves through, and the widest of the four: the projection reaches SIX columns by path, two
/// counts, the nested timebase's pair and two derived positions.
///
/// [`MediaTimestamp`]'s note above is this one's argument in full. What is worth stating here is the
/// half-openness, because a whole-value declaration is the first place a reader meets the interval
/// algebra without having written the columns themselves: `[start, end)` is the family law, the
/// comparison emits `<` and `<=` accordingly, and none of that moves when the field is declared at
/// the citizen rather than flattened by hand.
impl<Db> ToDatabaseComparison<MediaTimeRange, Db> for MediaTimeRangeFilter
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  type Comparison = SqlMediaTimeRangeComparison<Db>;
}

/// The crossing, and the only route into a [`SqlMediaTimeRangeComparison`].
impl<Db> TryFromFilter<MediaTimeRangeFilter> for SqlMediaTimeRangeComparison<Db> {
  type Error = MediaTimeRangeCrossingError;

  fn try_from_filter(filter: MediaTimeRangeFilter) -> Result<Self, Self::Error> {
    let MediaTimeRangeFilter {
      exact,
      contains,
      overlaps,
      within,
      before,
      after,
      duration,
      start_pts,
      end_pts,
      timebase,
    } = filter;

    // A component slot is OPTIONAL on the wire, and an absent one asks nothing — which is the empty
    // filter, exactly what the hand-written parse this replaced wrote for a key a client omitted.
    let duration = duration.unwrap_or_default();
    let start_pts = start_pts.unwrap_or_default();
    let end_pts = end_pts.unwrap_or_default();
    let timebase = timebase.unwrap_or_default();

    // Four slots carry a WIRE newtype, each because its door is the second one over a Rust type that
    // has already spent its crossing. Unwrapping here is where they become the values again.
    let contains = match contains.map(MediaContained::from) {
      Some(MediaContained::Instant(instant)) => Some(ContainedNanos::Instant(position(instant)?)),
      Some(MediaContained::Span(span)) => {
        let (start, end) = endpoints(span)?;
        Some(ContainedNanos::Span(start, end))
      }
      None => None,
    };

    // The structural facet needs no conversion and can refuse nothing: the value columns hold what
    // the operand already is, so an unplaceable range is still findable by the encoding that wrote
    // it.
    let exact = exact.map(MediaTimeRange::from).map(|operand| {
      let (num, den) = Timebase::new(operand.get().timebase()).reduced();
      Encoding {
        start: operand.get().start_pts(),
        end: operand.get().end_pts(),
        num,
        den: den.get(),
      }
    });

    Ok(Self {
      exact,
      contains,
      overlaps: overlaps.map(endpoints).transpose()?,
      within: within.map(endpoints).transpose()?,
      before: before.map(MediaTimestamp::from).map(position).transpose()?,
      after: after.map(MediaTimestamp::from).map(position).transpose()?,
      duration: DurationNanos {
        gt: length(duration.gt().copied().map(mediatime::SignedDuration::from))?,
        gte: length(duration.gte().copied().map(mediatime::SignedDuration::from))?,
        lt: length(duration.lt().copied().map(mediatime::SignedDuration::from))?,
        lte: length(duration.lte().copied().map(mediatime::SignedDuration::from))?,
      },
      start_pts: infallible(SqlScalarComparison::try_from_filter(start_pts)),
      end_pts: infallible(SqlScalarComparison::try_from_filter(end_pts)),
      timebase: SqlTimebaseComparison::try_from_filter(timebase)
        .map_err(MediaTimeRangeCrossingError::Timebase)?,
    })
  }
}

/// One instant operand's position on the timeline.
fn position(operand: MediaTimestamp) -> Result<i64, MediaTimeRangeCrossingError> {
  operand
    .to_nanos()
    .map_err(MediaTimeRangeCrossingError::Overflow)
}

/// One span operand's two positions.
fn endpoints(operand: MediaTimeRange) -> Result<(i64, i64), MediaTimeRangeCrossingError> {
  operand
    .to_nanos()
    .map_err(MediaTimeRangeCrossingError::Overflow)
}

/// One length operand in nanoseconds.
///
/// A `SignedDuration` is a count in a timebase like a timestamp is, so it crosses through the same
/// rescale and meets the same ceiling — a length of ten thousand years is refused here rather than
/// clamped into a bound that admits everything.
fn length(
  operand: Option<mediatime::SignedDuration>,
) -> Result<Option<i64>, MediaTimeRangeCrossingError> {
  operand
    .map(|operand| {
      operand
        .checked_rescale_to(mediatime::Timebase::NANOS)
        .map(|nanos| nanos.ticks())
        .ok_or(MediaTimeRangeCrossingError::DurationOverflow)
    })
    .transpose()
}

/// The scalar halves cross with `Error = Infallible`; matched out so the impossibility stays the
/// compiler's.
fn infallible<T>(crossed: Result<T, core::convert::Infallible>) -> T {
  match crossed {
    Ok(crossed) => crossed,
    Err(never) => match never {},
  }
}

/// A [`MediaTimeRangeFilter`] did not reach its columns, and this says which part of it did not.
///
/// [`MediaTimeRangeFilter`]: super::MediaTimeRangeFilter
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MediaTimeRangeCrossingError {
  /// An instant or endpoint operand is further from zero than `i64` nanoseconds reach.
  Overflow(NanosecondOverflow),
  /// A duration operand has no `i64` nanosecond length — a span longer than about 292 years.
  ///
  /// Its own variant rather than [`Overflow`](Self::Overflow), because the two are different
  /// questions: an instant is refused for WHERE it sits, a length for HOW LONG it is, and a client
  /// reading "292 years" needs to know which of its operands is the one being talked about.
  DurationOverflow,
  /// The `timebase` facet did not cross — carrying the nested citizen's own refusal.
  Timebase(TimebaseCrossingError),
}

impl fmt::Display for MediaTimeRangeCrossingError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Overflow(overflow) => overflow.fmt(f),
      Self::DurationOverflow => {
        f.write_str("a length longer than 292 years does not fit i64 nanoseconds")
      }
      Self::Timebase(timebase) => timebase.fmt(f),
    }
  }
}

impl core::error::Error for MediaTimeRangeCrossingError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Overflow(overflow) => Some(overflow),
      Self::Timebase(timebase) => Some(timebase),
      Self::DurationOverflow => None,
    }
  }
}