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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! [`BoundingBox<T>`](BoundingBox): an axis-aligned rectangle, its four faces, and the unit-square
//! invariants that belong to ONE instantiation rather than to the holder.

use crate::{
  ColumnEq, ColumnKind, ColumnName, ColumnShape, CompositeFilterMarker, CompositeMarker,
  CursorValue, DefaultMarker, DefaultVecMarker, FieldName, OrderLevel, PayloadFilter,
  QuantifiedMarker, shape,
};

use super::NormCoord;

#[cfg(test)]
mod tests;

/// **AN AXIS-ALIGNED RECTANGLE** — its top-left corner and its two extents, in whatever `T` the
/// declaration measures in.
///
/// ```text
///   (x, y) ●──────────────┐
///          │              │  height
///          │              │
///          └──────────────┘
///               width
/// ```
///
/// # TOP-LEFT ORIGIN and `xywh`, which is the ancestors' settled geometry
///
/// `y` grows DOWNWARD, and the corner the pair names is the box's top-left. That is the convention
/// every producer this framework has met already keeps — `avanalyze` flips Vision's bottom-left
/// normalized rectangles onto it before a box is ever built, and its contract states that
/// bounding boxes, 2-D pose joints, face landmarks and document quads all share it — so a second
/// convention here would be a translation layer standing between this crate and every caller it
/// has.
///
/// The extents are WIDTH and HEIGHT rather than a second corner. A right/bottom pair says the same
/// thing and says it worse at a column: two of the four values would then be derived from the other
/// two by a subtraction the database cannot see, and an `UPDATE` moving one edge would leave a row
/// that is still four valid numbers and no longer the rectangle anybody wrote.
///
/// # A DUMB GENERIC HOLDER — the invariants layer on the COMPONENT
///
/// This type checks NOTHING. [`new`](Self::new) is total and `const`, and a
/// `BoundingBox<f64>` measured in metres, a `BoundingBox<u32>` measured in pixels and a
/// `BoundingBox<NormCoord>` in the unit square are all built the same way. That is the ruling this
/// family is grown by: **not everyone wants a normalized coordinate**, and a holder that refused a
/// pixel rectangle for leaving the unit square would be a holder with an opinion about a unit it
/// was never told.
///
/// The unit square's own rules — a strictly positive extent, and an edge that does not run past
/// `1.0` — live on the [`BoundingBox<NormCoord>`](BoundingBox::try_unit) impl block ALONE, where
/// they are true. A metric box has no unit square to leave, and a pixel box has no `1.0` to reach.
///
/// # NO DEFAULT TYPE PARAMETER
///
/// `BoundingBox` bare does not compile, and the absence is a ruling rather than an oversight. A
/// default would make the normalized world the SILENT reading of a type whose whole subject is that
/// the world is the caller's to name — and it is exactly the question
/// [`Confidence<S>`](crate::Confidence) already answered in this direction: that type carries no
/// default either, despite `f32` being overwhelmingly the width its callers measure in, and the
/// bare name a caller wanted became [`Score`](crate::Score), a named ALIAS. No such alias stands
/// here yet, for the rule this module is grown by — a name arrives when a caller does.
///
/// # NO `Ord`, and none is coming
///
/// Two rectangles have no order. Nothing about *left of*, *smaller than* or *before* is a total
/// relation over four numbers, and a lexicographic order on `(x, y, width, height)` would be an
/// order over the STORAGE that reads like an order over the geometry. The three comparisons a
/// caller actually means — one box contains another, two overlap, one is within a region — are
/// SPATIAL PREDICATES, which are a future face rather than an absent one: see
/// [`BoundingBoxFilter`], where the door is named.
///
/// # Examples
///
/// ```
/// use ingraph::{BoundingBox, NormCoord};
///
/// let metres = BoundingBox::new(1.5_f64, 2.5, 4.0, 3.0);
/// assert_eq!(metres.width(), 4.0);
///
/// let pixels = BoundingBox::new(12_u32, 40, 200, 150);
/// assert_eq!(pixels.y(), 40);
///
/// let unit = BoundingBox::try_unit(0.1, 0.2, 0.5, 0.4).unwrap();
/// assert_eq!(unit.x(), NormCoord::new(0.1).unwrap());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BoundingBox<T> {
  pub(super) x: T,
  pub(super) y: T,
  pub(super) width: T,
  pub(super) height: T,
}

impl<T> BoundingBox<T> {
  /// The rectangle at `(x, y)` with these extents.
  ///
  /// TOTAL and `const`: see the type's note, where the absence of a check is the ruling.
  #[inline]
  #[must_use]
  pub const fn new(x: T, y: T, width: T, height: T) -> Self {
    Self {
      x,
      y,
      width,
      height,
    }
  }

  /// The left edge.
  #[inline]
  pub const fn x(&self) -> T
  where
    T: Copy,
  {
    self.x
  }

  /// The top edge.
  #[inline]
  pub const fn y(&self) -> T
  where
    T: Copy,
  {
    self.y
  }

  /// How far the box reaches to the right of [`x`](Self::x).
  #[inline]
  pub const fn width(&self) -> T
  where
    T: Copy,
  {
    self.width
  }

  /// How far the box reaches below [`y`](Self::y).
  #[inline]
  pub const fn height(&self) -> T
  where
    T: Copy,
  {
    self.height
  }

  /// **THE AREA** — `width × height`, in whatever the component measures in.
  ///
  /// It is the ONE derived reading a caller filters on, and *how much of the picture is this* is the
  /// question it answers: a detector emits spurious findings a few pixels across beside the ones a
  /// person cares about, and the area is the single ordered number that tells them apart. See
  /// [`BoundingBoxFilter`], whose `area` facet lowers onto the column this method computes.
  ///
  /// # THE BOUND IS THIS METHOD'S, and the census that picked it
  ///
  /// `T: Copy + Mul<Output = T>` — the honest minimum for one multiplication of two components, and
  /// **nothing wider**. It is stated HERE rather than on the type or the impl block, which is the
  /// arrangement every reading in this house takes ([`x`](Self::x) and its three siblings each carry
  /// their own `T: Copy`): a rectangle over a component with no arithmetic is still a rectangle a
  /// caller can build, store and read back, and only this one method is unavailable on it.
  ///
  /// So a component that multiplies is IN — [`NormCoord`], `f32`, `f64`, an integer width, a
  /// downstream newtype that publishes the operator — and one that does not simply lacks this
  /// method. That is out of bounds rather than refused, and no error type exists for it.
  ///
  /// # THE COMPONENT'S ARITHMETIC IS THE COMPONENT'S, including how it fails
  ///
  /// This is one `*` and nothing else. A `BoundingBox<u32>` whose extents overflow gets `u32`'s own
  /// answer to an overflowing multiply — a debug panic, a release wrap — because that is what `*`
  /// means for that type, and a holder with no opinion about a unit has none about its arithmetic
  /// either. A `BoundingBox<NormCoord>` cannot overflow at all: the interval is closed under
  /// multiplication, which is the row [`NormCoord`]'s `Mul` carries.
  ///
  /// It can be ZERO where neither extent is, and that is arithmetic rather than a hole: two extents
  /// small enough that their product underflows the width multiply to `+0.0`. At `f32` that needs
  /// both near `10⁻²⁰` — a rectangle far narrower than one pixel of an 8K frame — so the value is
  /// honest about what it is.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::{BoundingBox, NormCoord};
  ///
  /// let unit = BoundingBox::try_unit(0.1, 0.2, 0.5, 0.4).unwrap();
  /// assert_eq!(unit.area(), NormCoord::new(0.2).unwrap());
  ///
  /// let pixels = BoundingBox::new(12_u32, 40, 200, 150);
  /// assert_eq!(pixels.area(), 30_000);
  /// ```
  #[inline]
  #[must_use]
  pub fn area(&self) -> T
  where
    T: Copy + core::ops::Mul<Output = T>,
  {
    self.width * self.height
  }

  /// The same rectangle with every component carried through `f`.
  ///
  /// What a caller crossing between worlds spends — a normalized box into a pixel one, given the
  /// frame — and the one place this type does arithmetic on behalf of anybody. It does none: `f` is
  /// the caller's, applied four times in field order.
  #[inline]
  pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> BoundingBox<U> {
    BoundingBox {
      x: f(self.x),
      y: f(self.y),
      width: f(self.width),
      height: f(self.height),
    }
  }
}

impl BoundingBox<NormCoord> {
  /// **The unit square's own constructor** — the four numbers, the interval, and the two rules a
  /// rectangle inside a unit frame has.
  ///
  /// This is the ONE instantiation with rules of its own, and they are stated here rather than on
  /// the holder for the reason the type's note gives: a metric box has no unit square to leave.
  ///
  /// # Errors
  ///
  /// - [`RefusedBox::Component`] where any of the four is not a coordinate — `NaN`, an infinity, or
  ///   a number outside `[0.0, 1.0]`. The component's own refusal, reached through
  ///   [`NormCoord::new`], so a box and a bare coordinate cannot come to disagree about what one is.
  /// - [`RefusedBox::Degenerate`] where either extent is zero. A rectangle with no area is not a
  ///   region a detector found; it is the value a clamp produces when it has clamped everything
  ///   away, and admitting it would put an empty box in a row where a caller reads a location.
  /// - [`RefusedBox::OutOfBounds`] where `x + width` or `y + height` exceeds `1.0`. Each component
  ///   is inside the frame and their SUM need not be, which is the one rule the component cannot
  ///   state on its own and therefore the only reason this constructor exists.
  ///
  /// The order is COMPONENT, then degenerate, then out-of-bounds, and it is the order the rules
  /// depend on each other in: a sum is meaningless until both addends are numbers.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::{BoundingBox, RefusedBox};
  ///
  /// assert!(BoundingBox::try_unit(0.0, 0.0, 1.0, 1.0).is_ok());
  ///
  /// assert_eq!(BoundingBox::try_unit(0.1, 0.1, 0.0, 0.5), Err(RefusedBox::Degenerate));
  /// assert_eq!(BoundingBox::try_unit(0.8, 0.1, 0.5, 0.5), Err(RefusedBox::OutOfBounds));
  /// assert_eq!(BoundingBox::try_unit(f32::NAN, 0.1, 0.5, 0.5), Err(RefusedBox::Component));
  /// ```
  pub fn try_unit(x: f32, y: f32, width: f32, height: f32) -> Result<Self, RefusedBox> {
    let coord = |value| NormCoord::new(value).ok_or(RefusedBox::Component);

    let x = coord(x)?;
    let y = coord(y)?;
    let width = coord(width)?;
    let height = coord(height)?;

    if width == NormCoord::ZERO || height == NormCoord::ZERO {
      return Err(RefusedBox::Degenerate);
    }

    if x.get() + width.get() > 1.0 || y.get() + height.get() > 1.0 {
      return Err(RefusedBox::OutOfBounds);
    }

    Ok(Self::new(x, y, width, height))
  }

  /// The right edge — `x + width`, which [`try_unit`](Self::try_unit) proved is a coordinate.
  ///
  /// It is a READING rather than a stored column, for the reason the type's note gives about the
  /// second-corner spelling: an edge that a row held would be a fifth number an `UPDATE` could put
  /// out of step with the four it is computed from.
  #[inline]
  #[must_use]
  pub fn right(&self) -> NormCoord {
    NormCoord::new(self.x.get() + self.width.get())
      .expect("`try_unit` refused a box whose right edge leaves the frame")
  }

  /// The bottom edge — `y + height`, on [`right`](Self::right)'s terms.
  #[inline]
  #[must_use]
  pub fn bottom(&self) -> NormCoord {
    NormCoord::new(self.y.get() + self.height.get())
      .expect("`try_unit` refused a box whose bottom edge leaves the frame")
  }
}

/// **Why a unit box was refused** — the three rules [`BoundingBox::try_unit`] checks, in the order
/// it checks them.
///
/// It is a vocabulary rather than a single sentence because the three are ACTIONABLE differently: a
/// component refusal means the numbers are wrong, a degenerate one means the region collapsed, and
/// an out-of-bounds one means the frame was the wrong size. A producer clamping into the unit square
/// hits the second, and one that forgot to normalise hits the third.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RefusedBox {
  /// One of the four numbers is not a coordinate — `NaN`, an infinity, or outside `[0.0, 1.0]`.
  Component,
  /// An extent is zero, so the rectangle has no area.
  Degenerate,
  /// An edge runs past `1.0`, so the rectangle leaves the frame.
  OutOfBounds,
}

impl core::fmt::Display for RefusedBox {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(match self {
      Self::Component => {
        "each of x, y, width and height is a finite number in the closed unit interval `[0.0, 1.0]`"
      }
      Self::Degenerate => "a bounding box has a strictly positive width and height",
      Self::OutOfBounds => {
        "a bounding box stays inside the frame: x + width and y + height are at \
                            most 1.0"
      }
    })
  }
}

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

/// The left edge's segment.
pub(super) const X: &FieldName = FieldName::new("x");

/// The top edge's segment.
pub(super) const Y: &FieldName = FieldName::new("y");

/// The horizontal extent's segment.
pub(super) const WIDTH: &FieldName = FieldName::new("width");

/// The vertical extent's segment.
pub(super) const HEIGHT: &FieldName = FieldName::new("height");

/// The DERIVED extent's segment — `width × height`, computed by the write and read by no decode.
pub(super) const AREA: &FieldName = FieldName::new("area");

/// **The FIVE columns a box spans** — the four it HOLDS and the one it is FILTERED on — and the one
/// authority every half of the crossing reads.
///
/// # The last entry is [`Derived`](ColumnShape::Derived), the DERIVED-AND-NEVER-NULL word
///
/// [`MediaTimestamp`](crate::MediaTimestamp)'s `nanos` is the precedent for the KIND of leaf: `x`,
/// `y`, `width` and `height` are what a row HOLDS, and `area` is what a row is asked about. Every
/// structural reader in the crate takes that: the decode never reads the area, an optional box's
/// `None` test never counts it, a row-value equality never compares it, and a cursor never carries
/// it. See [`ColumnShape`], where the law and its readers are written out.
///
/// **Where this house parts from the instant is nullability, and that is why the word is the third
/// one.** `nanos` is `NULL` for a real stored value past the ±292-year ceiling, so it is
/// [`Nullable`](ColumnShape::Nullable). An area is `width × height` and the components that reach
/// this leaf multiply totally, so no box this crate can bind writes `NULL` into it — and the DDL
/// says so: `area` takes `NOT NULL` wherever its field is required. A column the write always fills,
/// declared nullable, would be a schema stating *this may be missing* about something that never is.
///
/// An `optional` box still fans `NULL` over all five, the field being absent as a whole; that is the
/// FIELD's grain, and it composes over this leaf exactly as it does over the other four.
///
/// # WHY A COLUMN AT ALL, when the two factors are already stored
///
/// *How much of the picture is this* is the question people actually ask of a detection, and it is
/// the one question about a rectangle that is a single ordered number. Asked over the stored pair it
/// is `width * height >= ?` — an expression no index can serve, evaluated per row. Asked over this
/// column it is `area >= ?`, which is a range scan. That is the same bargain the derived instant
/// makes one house over, and it is the reason the ruling calls this leaf DERIVED rather than
/// reaching for a virtual expression the three dialects spell three ways.
///
/// # The LEAF GUARD, and why it is an assertion rather than a bound
///
/// The assertion refuses a component that spans more than one column, and it is what makes the
/// [`StoredAs`](crate::StoredAs) row below TRUE rather than merely plausible. That row is an ARRAY
/// OF WORDS whose length is fixed when the impl is written, and stable Rust cannot write
/// `4 * <T as StoredAs<Db>>::WORDS.len()` in a length position — the boundary
/// [`TimeRanged<T>`](crate::TimeRanged) records, having no `StoredAs` row at all for exactly this
/// reason. A FIXED-arity composite is unaffected, and this assertion is what keeps this one fixed:
/// with a one-column component the box is four columns in every instantiation, and with a composite
/// component it would be some other number that no row here could name.
///
/// So the openness is bounded where it has to be and nowhere else. Every leaf a declaration can name
/// is admitted — `NormCoord`, `f32`, `f64`, an integer width, a downstream newtype with a carrier —
/// and a component that is itself a composite meets `E0080` carrying the sentence below, which is
/// [`flattened`](crate::flattened)'s own refusal shape one house over.
///
/// ```compile_fail,E0080
/// use ingraph::{BoundingBox, ColumnKind, TimeRange};
///
/// const _: usize = <BoundingBox<TimeRange> as ColumnKind>::SEGMENTS.len();
/// ```
impl<T: ColumnKind> ColumnKind for BoundingBox<T> {
  const SEGMENTS: &'static [ColumnShape] = {
    assert!(
      T::SEGMENTS.is_empty(),
      "a bounding box's component spans ONE column: a composite component would make the box's own \
       width depend on it, and a fixed-arity row cannot state that"
    );
    &[
      shape::<T>(ColumnName::of(X)),
      shape::<T>(ColumnName::of(Y)),
      shape::<T>(ColumnName::of(WIDTH)),
      shape::<T>(ColumnName::of(HEIGHT)),
      ColumnShape::Derived(ColumnName::of(AREA)),
    ]
  };

  const ORDER: &'static [OrderLevel] = ORDER;
}

/// A rectangle is one column value when its four VALUE leaves are — `x`, `y`, `width` and
/// `height` — and never the derived `area`: the fold below reads only the four columns a row
/// actually holds, exactly as the row-value equality this face replaces does.
impl<T: ColumnEq> ColumnEq for BoundingBox<T> {
  #[inline]
  fn column_eq(&self, other: &Self) -> bool {
    self.x.column_eq(&other.x)
      && self.y.column_eq(&other.y)
      && self.width.column_eq(&other.width)
      && self.height.column_eq(&other.height)
  }
}

/// **The order those five columns MEAN — and the derived leaf is NOT ONE OF THEM.**
///
/// Four levels over five leaves: `x`, `y`, `width`, `height`, in the sequence they are declared in.
///
/// # Stating the sequence is what keeps the derived leaf out of every STRUCTURAL judgment
///
/// A composite that leaves this const at its default keeps the WIDE term it always had, and a wide
/// term's keyset row value is its whole width — so a rectangle wearing the non-reordering word would
/// have put `region_area` inside `("region_x", …, "region_area") > (?, ?, ?, ?, ?)`, which is a
/// derived leaf inside a pagination cursor. That is exactly the shape ingraph #454/#455 were: the
/// law says *a derived leaf serves the semantic order only; every structural judgment walks value
/// leaves only*, and stating a sequence is how a citizen executes it. A term over one EXPANDS
/// through [`OrderTerm::levels`](crate::OrderTerm::levels) into one ONE-COLUMN term per level, so no
/// row value a keyset renders can contain the area.
///
/// # It is the INVERSE of the instant's sequence, and the difference is what each leaf is FOR
///
/// [`MediaTimestamp`](crate::MediaTimestamp) puts its derived leaf FIRST, because `nanos` is the one
/// unit every stored row shares and the count beside it is not comparable across timebases — the
/// derived leaf is the only honest order. Here the derived leaf is in NO level at all, because two
/// rectangles have no order and this type publishes none: *nothing about left of, smaller than or
/// before is a total relation over four numbers*. Ordering by area first would be exactly the claim
/// the type refuses — that a bigger rectangle comes before a smaller one — dressed as a default.
///
/// So the four levels are the DECLARATION order, which is what a caller who orders by a whole box
/// gets today and what the wide term already gave them: a stable, total, lexicographic tie-break
/// over the value, with no semantics claimed for it. What the area IS for is the FILTER — see
/// [`BoundingBoxFilter`]'s `area` facet — and a filter needs no level.
pub(super) const ORDER: &[OrderLevel] = &[
  OrderLevel::new(0),
  OrderLevel::new(1),
  OrderLevel::new(2),
  OrderLevel::new(3),
];

/// **The VALUE one of a rectangle's four levels compares** — the per-leaf vocabulary this citizen
/// publishes beside its sequence, and the type an emitted cursor's slot is minted with for a column
/// of this type.
///
/// One member per LEVEL, each carrying the component's own type, in the SEGMENT numbering: `x` is
/// `0`, `y` is `1`, `width` is `2` and `height` is `3`. There is no member for leaf `4`, and that is
/// the [`ORDER`] const said in a second place — the derived area is not a level, so no cursor slot
/// is ever minted for it and [`OrderLeaves::leaf`](crate::OrderLeaves::leaf) answers [`None`] there.
///
/// # It binds ONE placeholder, through the component's own row
///
/// Which is why a level's operand needs nothing new: a coordinate binds as a coordinate always has.
/// Nothing here is a second bind face — the [`Carrier`](crate::Carrier) row below dispatches to the
/// component's, and both of that trait's faces are the same one placeholder, a component having no
/// derived leaf of its own to leave out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BoundingBoxLeaf<T> {
  /// Leaf `0` — the left edge.
  X(T),
  /// Leaf `1` — the top edge.
  Y(T),
  /// Leaf `2` — the horizontal extent.
  Width(T),
  /// Leaf `3` — the vertical extent.
  Height(T),
}

/// One leaf is the same as another leaf when it is the SAME leaf holding the same component —
/// never across kinds, and there is no member for the derived area to be one of them.
impl<T: ColumnEq> ColumnEq for BoundingBoxLeaf<T> {
  fn column_eq(&self, other: &Self) -> bool {
    match (self, other) {
      (Self::X(this), Self::X(that)) => this.column_eq(that),
      (Self::Y(this), Self::Y(that)) => this.column_eq(that),
      (Self::Width(this), Self::Width(that)) => this.column_eq(that),
      (Self::Height(this), Self::Height(that)) => this.column_eq(that),
      _ => false,
    }
  }
}

/// **The four VALUE leaves, and [`None`] for the derived one.**
///
/// The area is a function of leaves `2` and `3` and is carried by nothing — not by the decode, not
/// by the whole box's own [`CursorValue`] row. Answering [`None`] at `4` is this citizen's honest
/// reading of *this value has no leaf there*: the const one screen up names four levels, so a
/// renderer walking a term's own width never asks, and a caller that asks anyway gets the sentence
/// the sequence already made rather than a value no statement compares.
impl<T: ColumnKind + Copy> crate::OrderLeaves for BoundingBox<T> {
  type Leaf = BoundingBoxLeaf<T>;

  fn leaf(&self, at: usize) -> Option<BoundingBoxLeaf<T>> {
    match at {
      0 => Some(BoundingBoxLeaf::X(self.x)),
      1 => Some(BoundingBoxLeaf::Y(self.y)),
      2 => Some(BoundingBoxLeaf::Width(self.width)),
      3 => Some(BoundingBoxLeaf::Height(self.height)),
      _ => None,
    }
  }
}

/// **The KEYSET position of ONE leaf**: which leaf, then that leaf's own bytes.
///
/// The tag is what makes the read total, for [`MediaTimestampLeaf`](crate::MediaTimestampLeaf)'s
/// reason: a slot is length-delimited by the cursor and holds nothing else, so a sum has to say
/// which member it is — and the bytes are a CLIENT's, so a byte naming no leaf is refused rather
/// than read as the nearest one. Four tags and no fifth: the derived leaf is no level, so there is
/// no encoding for it to have.
impl<T: CursorValue> CursorValue for BoundingBoxLeaf<T> {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    let (tag, value) = match self {
      Self::X(value) => (0, value),
      Self::Y(value) => (1, value),
      Self::Width(value) => (2, value),
      Self::Height(value) => (3, value),
    };
    out.push(tag);
    CursorValue::write_cursor(value, out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (tag, value) = bytes.split_first()?;
    let component = <T as CursorValue>::read_cursor(value)?;
    match tag {
      0 => Some(Self::X(component)),
      1 => Some(Self::Y(component)),
      2 => Some(Self::Width(component)),
      3 => Some(Self::Height(component)),
      _ => None,
    }
  }
}

/// **ONE BIND OUT**, through the row the component already had.
///
/// A level names one column, so its operand is one placeholder.
/// [`push_value_bind`](crate::Carrier::push_value_bind) takes its default: a component has no
/// derived leaf inside it to leave out.
#[cfg(feature = "sqlx")]
impl<Db, T> crate::Carrier<Db> for BoundingBoxLeaf<T>
where
  Db: sqlx::Database,
  T: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    let (Self::X(value) | Self::Y(value) | Self::Width(value) | Self::Height(value)) = self;
    <T as crate::Carrier<Db>>::push_bind(value, qb);
  }
}

/// **The DECLARED half — FIVE words**, the component's own, five times.
///
/// The component's `WORDS` has exactly one entry, which the leaf guard above is what makes true:
/// index zero is the whole of it, and the five columns are one type stored five times rather than
/// five types that happen to agree.
///
/// The DERIVED column is the component's word too, and it has to be: an area is `width × height` at
/// the component's own `Mul`, so a `BoundingBox<NormCoord>` stores a fifth `f32` and a
/// `BoundingBox<u32>` a fifth integer. Nothing here widens anything — see
/// [`area`](BoundingBox::area), where the arithmetic is the component's including how it overflows.
impl<Db, T> crate::StoredAs<Db> for BoundingBox<T>
where
  T: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <T as crate::StoredAs<Db>>::WORDS[0],
    <T as crate::StoredAs<Db>>::WORDS[0],
    <T as crate::StoredAs<Db>>::WORDS[0],
    <T as crate::StoredAs<Db>>::WORDS[0],
    <T as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION**, and it DELEGATES: a box is one element of a collection exactly where its
/// component is one.
///
/// `Vec<BoundingBox<NormCoord>>` is what a detection pass produces — every face in a frame, every
/// word in a page — so this row is the one an edge table of regions needs.
impl<T: crate::CollectionElement> crate::CollectionElement for BoundingBox<T> {}

/// **FIVE BINDS OUT** — the four that carry the rectangle, then the one that carries how much of
/// the frame it covers.
///
/// The derived bind is [`area`](BoundingBox::area) itself, which is the SINGLE SOURCE the ruling
/// asks for: the column a query filters on and the number a caller reads are one expression, so
/// they cannot come to disagree. The `Mul` bound arrives here rather than on
/// [`ColumnKind`] deliberately — a rectangle over a component with no arithmetic still has a WIDTH
/// and a leaf guard, and what it does not have is a way to be WRITTEN, which is `E0277` naming
/// `Mul` at the declaration that tried. Out of bounds, not refused.
///
/// **AND FOUR FOR A STRUCTURAL JUDGMENT.** [`push_value_bind`](crate::Carrier::push_value_bind) is
/// overridden to leave the derived column out, and it has to be: its width is
/// [`value_width`](crate::value_width) of the same segments, which is four, and the left-hand side
/// a row-value equality writes names exactly those four columns. A whole-width bind under that
/// left-hand side is one placeholder too many — a statement the engine refuses to parse — which is
/// the loud failure the pairing exists to produce rather than the silent one ingraph #455 was.
#[cfg(feature = "sqlx")]
impl<T, Db> crate::Carrier<Db> for BoundingBox<T>
where
  Db: sqlx::Database,
  T: crate::Carrier<Db> + Copy + core::ops::Mul<Output = T>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    self.push_value_bind(qb);
    qb.push(", ");
    <T as crate::Carrier<Db>>::push_bind(&self.area(), qb);
  }

  fn push_value_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <T as crate::Carrier<Db>>::push_bind(&self.x, qb);
    qb.push(", ");
    <T as crate::Carrier<Db>>::push_bind(&self.y, qb);
    qb.push(", ");
    <T as crate::Carrier<Db>>::push_bind(&self.width, qb);
    qb.push(", ");
    <T as crate::Carrier<Db>>::push_bind(&self.height, qb);
  }
}

/// **AND THE FOUR VALUE COLUMNS BACK IN**, by name, and never the derived one.
///
/// Reading the area would give a row two ways to say what rectangle it holds, and a derived column
/// exists precisely so that there is one — [`MediaTimestamp`](crate::MediaTimestamp)'s own sentence
/// at its own decode. It also means a row whose area was written by an older schema, a hand
/// migration or another writer decodes exactly like any other: the extents are the value, and the
/// area is what the next write recomputes.
///
/// It states no invariant of its own, and that is the layering rather than an omission: whatever the
/// component refuses at its own column it refuses here — a stored `1.5` in a `NormCoord` box is
/// [`OutsideTheUnitInterval`](super::OutsideTheUnitInterval), named by the column that held it. What
/// this row cannot re-check is the SUM rule, and the gap is recorded rather than papered over: see
/// this type's own note in the family module, under *what a decode can and cannot re-prove*.
#[cfg(feature = "sqlx")]
impl<'a, R, T> crate::Assemble<'a, R> for BoundingBox<T>
where
  R: sqlx::Row,
  T: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let x: T = crate::assembled(row, X, under)?;
    let y: T = crate::assembled(row, Y, under)?;
    let width: T = crate::assembled(row, WIDTH, under)?;
    let height: T = crate::assembled(row, HEIGHT, under)?;

    Ok(Self::new(x, y, width, height))
  }
}

/// **THE KEYSET POSITION** — the four components in segment order, each in its own encoding.
///
/// The ORDER the bytes encode is the columns' rather than a claim about geometry: this type
/// publishes no [`Ord`], and a page's need for *an* order is not a claim about *the* order. That is
/// [`TimeRanged<T>`](crate::TimeRanged)'s own sentence at its own cursor, and it is the whole of
/// what a boundary over an unordered value means.
///
/// The split points are constants because the component is FIXED-WIDTH at the cursor: a
/// variable-width component would need a delimiter this row does not invent, and the read below
/// answers [`None`] rather than guessing where one part stops.
///
/// **The DERIVED column is absent, and the division above is why that is load-bearing.** A cursor
/// carries what a page is CUT at, which is the value; the area is recomputed by every write and
/// belongs to no boundary. It also keeps the four-way split exact — a fifth component here would
/// make a cursor a fifth wider for a number the value already determines, and this row's own
/// `len / 4` would then be reading a box out of the bytes of something else.
impl<T: CursorValue> CursorValue for BoundingBox<T> {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    CursorValue::write_cursor(&self.x, out);
    CursorValue::write_cursor(&self.y, out);
    CursorValue::write_cursor(&self.width, out);
    CursorValue::write_cursor(&self.height, out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let width = bytes.len() / 4;
    if width == 0 || width * 4 != bytes.len() {
      return None;
    }

    let x = <T as CursorValue>::read_cursor(&bytes[..width])?;
    let y = <T as CursorValue>::read_cursor(&bytes[width..width * 2])?;
    let w = <T as CursorValue>::read_cursor(&bytes[width * 2..width * 3])?;
    let h = <T as CursorValue>::read_cursor(&bytes[width * 3..])?;

    Some(Self::new(x, y, w, h))
  }
}

/// The interpretation a [`BoundingBox<T>`] field is read under — the COMPOSITE reading, because the
/// value occupies columns of its own and all four can be absent together.
///
/// The bound is the COMPONENT's own default, which is the membership rule spelled as a bound exactly
/// as [`TimeRanged<T>`](crate::TimeRanged)'s row spells its payload's: a box has a default
/// interpretation wherever its component has one. A component with none reaches `E0277` naming
/// ITSELF, which is the sentence a declaration's author can act on.
impl<T: DefaultMarker> DefaultMarker for BoundingBox<T> {
  type Marker = CompositeMarker<BoundingBox<T>>;
}

/// **A COLLECTION of boxes is asked through the QUANTIFIERS alone.**
///
/// `any` carries the whole [`BoundingBoxFilter`], so *something was detected in the top-left
/// quadrant* is one element question. The wide kind's four lexicographic operators are not
/// questions a list of boxes could answer, for the reason this type publishes no [`Ord`].
impl<T: DefaultMarker> DefaultVecMarker for BoundingBox<T> {
  type Marker = QuantifiedMarker<Vec<BoundingBox<T>>>;
}

/// What guards a [`BoundingBox<T>`] column — its own filter at both seats.
///
/// The component's filter is resolved through [`PayloadFilter<T>`](crate::PayloadFilter) rather than
/// listed, which is what keeps this row FRAMEWORK-OPEN: a component type declared in a downstream
/// crate reaches this filter by having a default marker, which every column type already has. The
/// alias is the framework's general *the filter this column type takes* resolver, under the name the
/// house that first needed it spent; there is one such expression in the crate and this row reads it
/// rather than writing a second.
impl<T> CompositeFilterMarker for BoundingBox<T>
where
  T: DefaultMarker,
{
  type Filter = BoundingBoxFilter<PayloadFilter<T>>;
  type ColumnFilter = BoundingBoxFilter<PayloadFilter<T>>;
}

/// **FOUR STORED FACETS AND ONE DERIVED ONE, and no whole-box operator at all.**
///
/// ```text
/// input BoundingBoxF32Filter {
///   x: F32Filter      y: F32Filter
///   width: F32Filter  height: F32Filter
///   area: F32Filter
/// }
/// ```
///
/// # The `area` FACET IS THE COMPONENT'S OWN FILTER, WIDE
///
/// It takes `CF` — the same filter the four stored facets take, resolved through
/// [`PayloadFilter<T>`](crate::PayloadFilter) — rather than a hand-narrowed four-slot kind of its
/// own. That is the standing WIDE-WIRE law, and reading it here is worth one paragraph because the
/// ancestor this facet comes from did the opposite: mediagraph's `AreaFilter` published `gt`, `gte`,
/// `lt` and `lte` alone, on the argument that nobody asks a rectangle's area for exact equality.
///
/// **A kind is not narrowed at the seat that uses it.** `eq`, `ne`, `in` and `notIn` are well
/// defined over an area exactly as they are over any other component — the component's own
/// constructor refuses `NaN`, so the order is total and equality is decidable — and the operand is
/// the component, so an area facet and a `width` facet publish ONE input object rather than two
/// names for one measurement. A face that dropped four slots would owe a client a reason why this
/// number answers fewer questions than the number it is computed from.
///
/// The area is DERIVED, and a filter is where a derived leaf is allowed to be: *a derived leaf
/// serves the semantic order only; every structural judgment walks value leaves only*, and a
/// SEMANTIC predicate is what this facet is. `{ area: { gte: 0.05 } }` lowers onto the `area` column
/// — see [`SqlBoundingBoxComparison`](super::SqlBoundingBoxComparison) — which is a range scan
/// rather than the per-row `width * height >= ?` the same question over the stored pair would be.
///
/// It is also NOT part of the leaf tuple below. A client writing all five facets writes four
/// conjuncts over the value and one over its index, which is a conjunction the engine can serve and
/// not a second identity: an area equal to the product of a width and a height it also asked for
/// is redundant rather than contradictory.
///
/// # The leaf-tuple EQUALITY is here, and it is spelled as the conjunction it IS
///
/// `{ x: { eq: 0.1 }, y: { eq: 0.2 }, width: { eq: 0.5 }, height: { eq: 0.4 } }` lowers to
/// `x = ? AND y = ? AND width = ? AND height = ?` — the leaf tuple, which is what whole-value
/// equality over a composite means and the only operator that decomposes conjunctively. A separate
/// `eq` slot holding a whole box would render exactly those four conjuncts, so what it would add is
/// a second spelling of one question and a conflict to adjudicate when a client wrote both.
///
/// That is [`MediaTimeRangeFilter`](crate::MediaTimeRangeFilter)'s own posture — a range has no `eq`
/// either — reached here by a different road: there the whole-value identity moved to `exact`
/// because a derived column made two identities possible, and here there is no derived column and no
/// second identity to tell apart.
///
/// # WHOLE-BOX ORDERING IS REFUSED, structurally
///
/// No slot takes a box-shaped bound, and none will. Four numbers have no total order; a
/// lexicographic one on `(x, y, width, height)` is an order over the STORAGE that would read like an
/// order over the geometry, and a filter that cannot express a question needs no error to refuse it
/// with. The COMPONENT orderings are genuine and are kept: `x: { gte: 0.5 }` is *the left edge is
/// past the midline*, and it is an index the database can use.
///
/// `ne`, `in` and `notIn` over a whole box are absent on the same terms and for a second reason
/// besides. A whole-value `ne` over a composite is a DISJUNCTION — *some column differs* — which
/// does not decompose into the conjunction a filter's slots are joined by; and a whole-value `in`
/// spelled per-column is the CARTESIAN PRODUCT, the trap
/// [`SqlKeyIn`](crate::comparison::sql::SqlKeyIn) exists one house over to make unwritable. Neither
/// is offered rather than offered wrongly.
///
/// # SPATIAL PREDICATES ARE THE DOOR THIS TYPE LEAVES OPEN
///
/// `contains`, `intersects` and `within` are the three questions a caller actually asks of a
/// rectangle, and they are a FUTURE face rather than an absent one. Each is a conjunction of
/// inequalities over the four columns — `contains` is `x <= ?x AND y <= ?y AND x + width >= ?right`
/// — so the columns to answer them are already stored and the arithmetic is a rendering rather than
/// a schema change. What they need is an OPERAND type and a ruling about which frame two boxes are
/// compared in, and neither is invented ahead of a caller.
pub struct BoundingBoxFilter<CF> {
  pub(super) x: Option<CF>,
  pub(super) y: Option<CF>,
  pub(super) width: Option<CF>,
  pub(super) height: Option<CF>,
  pub(super) area: Option<CF>,
}

impl<CF> BoundingBoxFilter<CF> {
  /// The empty filter — no facet set, so a column guarded by it is unconstrained.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      x: None,
      y: None,
      width: None,
      height: None,
      area: None,
    }
  }

  crate::graphql::filter::opt_accessor!(x: CF => with_x, set_x, maybe_x, update_x);
  crate::graphql::filter::opt_accessor!(y: CF => with_y, set_y, maybe_y, update_y);
  crate::graphql::filter::opt_accessor!(width: CF => with_width, set_width, maybe_width, update_width);
  crate::graphql::filter::opt_accessor!(height: CF => with_height, set_height, maybe_height, update_height);
  crate::graphql::filter::opt_accessor!(area: CF => with_area, set_area, maybe_area, update_area);
}

impl<CF: crate::GraphqlFilter> BoundingBoxFilter<CF> {
  /// True while NO operator slot is set on ANY of the five facets.
  ///
  /// The bound is on this ONE method rather than on the type, which is the arrangement every generic
  /// filter kind here takes: what emptiness MEANS for a component is the component filter's own
  /// answer, and a filter whose component family does not publish one is still a filter a caller can
  /// build.
  pub fn is_empty(&self) -> bool {
    [&self.x, &self.y, &self.width, &self.height, &self.area]
      .into_iter()
      .all(|facet| facet.as_ref().is_none_or(crate::GraphqlFilter::is_empty))
  }
}

impl<CF: crate::GraphqlFilter> crate::GraphqlFilter for BoundingBoxFilter<CF> {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

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

// The four derives are written out for `SqlTimebaseComparison`'s reason read one parameter over: a
// derive would bound `CF` on the whole type, where each of these needs it on itself alone — a filter
// over a component family that publishes no `Debug` is still a filter a caller can build and clone.
impl<CF: core::fmt::Debug> core::fmt::Debug for BoundingBoxFilter<CF> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("BoundingBoxFilter")
      .field("x", &self.x)
      .field("y", &self.y)
      .field("width", &self.width)
      .field("height", &self.height)
      .field("area", &self.area)
      .finish()
  }
}

impl<CF: Clone> Clone for BoundingBoxFilter<CF> {
  fn clone(&self) -> Self {
    Self {
      x: self.x.clone(),
      y: self.y.clone(),
      width: self.width.clone(),
      height: self.height.clone(),
      area: self.area.clone(),
    }
  }
}

impl<CF: PartialEq> PartialEq for BoundingBoxFilter<CF> {
  fn eq(&self, other: &Self) -> bool {
    self.x == other.x
      && self.y == other.y
      && self.width == other.width
      && self.height == other.height
      && self.area == other.area
  }
}