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
//! The OUTPUT CROSSING: what a domain type becomes where a wire face RETURNS it —
//! [`ToGraphqlOutput`], and nothing beside it.
//!
//! # The mirror this is measured against, and the posture it now takes
//!
//! The INPUT side is a MARKER LAYER and two maps over it:
//! [`DefaultMarker`](crate::DefaultMarker) maps a type to the interpretation it is read under,
//! [`ToGraphqlFilter`](crate::ToGraphqlFilter) maps an interpretation to the filter that guards it,
//! and the one question a TYPE cannot answer about itself — *what does a `Vec` of me mean* — is
//! delegated to the element through [`DefaultVecMarker`](crate::DefaultVecMarker), because the answer
//! is not uniform: a `Vec<u8>` is a blob and every other `Vec<T>` is a list, and a blanket beside an
//! exception for one element type is `E0119` on stable.
//!
//! This is that posture, one position over, and the two sides now share the SAME marker layer:
//!
//! | side | the map | the `Vec` fork |
//! |---|---|---|
//! | INPUT | [`DefaultMarker`](crate::DefaultMarker) → [`ToGraphqlFilter`](crate::ToGraphqlFilter) | [`DefaultVecMarker`](crate::DefaultVecMarker) |
//! | OUTPUT | [`ToGraphqlOutput`] | [`DefaultVecMarker`](crate::DefaultVecMarker) — the same rows |
//!
//! **There is ONE trait here, and that is the whole of this module's shape.** A second public trait
//! stood where the `Vec` fork is now — an element-keyed `VecToGraphqlOutput`, whose only job was to
//! carry the blob-versus-list answer. That answer already existed, on the input side, keyed on the
//! same element and stating the same fact; so the fork is READ from there, the second trait is gone,
//! and a declaring crate that has already said what its `Vec<Tag>` means says it once rather than
//! twice.
//!
//! # The trait is keyed on the TYPE, and the MARKER enters at exactly one fork
//!
//! Read the table again from underneath and the asymmetry is the positions': a FILTER is keyed on an
//! interpretation because a type does not determine its own reading, and a RETURN is not a reading —
//! what a client receives back is the value the row holds. So the rows here are the TYPE's, which is
//! also what keeps the door open downstream: `impl ingraph::ToGraphqlOutput for TheirType` names a
//! local type and is ordinary trait work, where `impl ToGraphqlOutput for SomeMarker<TheirType>`
//! would be `E0117` in every crate but this one.
//!
//! The MARKER is asked exactly where the type is genuinely ambiguous — `Vec<T>` — and there it is
//! asked through [`DefaultVecMarker`](crate::DefaultVecMarker)'s existing rows. That is what the
//! trait's `M` parameter is for: a marker's row is written `ToGraphqlOutput<Vec<E>>` and answers
//! about the type it MARKS rather than about itself, so `BytesMarker<Vec<u8>>` states the blob's
//! form and `ListMarker<Vec<E>, _>` states the list's, and neither can overlap the other because
//! they are different self types.
//!
//! # Why a map at all, and not `async_graphql::OutputType` directly
//!
//! Three of the framework's declarable field types have NO wire face of their own and can be given
//! none by any crate but async-graphql's: `u128` and `i128` are past the widest integer scalar that
//! library ships (`types/external/integers.rs` stops at 64 bits), and `jiff::SignedDuration` is a
//! foreign type of a foreign trait here. A fourth, `Vec<u8>`, HAS a face — `[Int!]`, a list of small
//! integers — and that face answers the wrong question about a blob.
//!
//! The SCALAR SUITE added a fifth reason and it is the broadest: every remaining numeric HAS a face
//! and it does not name the value's WIDTH. async-graphql spells `i8`…`i64` and `u8`…`u64` `Int` and
//! both floats `Float`, so a schema built through those rows returned a byte and a 64-bit id under
//! one type, and an `f32` measurement and an `f64` one under another. Each returns as its own width
//! now — see [`scalar`](super::scalar), where the twelve wrappers and the law that keeps them
//! inside this binding are stated.
//!
//! Each of them already crosses INWARD through a local newtype carrying the scalar
//! ([`scalar`](super::scalar), [`JiffDuration`](crate::JiffDuration)), so the operand a client
//! writes is exact. This map is the same crossing OUTWARD, and it exists so that the two directions
//! cannot come to disagree: a column filtered as `u128` is returned as `u128`.
//!
//! # It is TYPE-DIRECTED, and that is what makes it alias-proof
//!
//! A macro sees TOKENS. `type Uuid7 = u128` written into a declaration reaches an expansion as the
//! word `Uuid7`, and a projection chosen by matching that word against `u128` would hand the id
//! straight through and render nothing at all — silently, since the alias resolves to a type that
//! compiles. So the resolution is left to the compiler, which has the type:
//! `<Uuid7 as ToGraphqlOutput>::Output<'_>` IS `U128`, because the alias and the type it names
//! are one type to a trait solver.
//!
//! [`project`](crate::project) already made this argument for the accessor family's own projections,
//! and made it after a token-matching reading had shipped: *a field declared `files: Ids` was handed
//! back as `&Ids` with nothing to catch it*. This is that lesson applied to the wire.
//!
//! # ONE TYPE, ONE OUTPUT FORM — and where that is visible
//!
//! The map takes no second input at a call site, so a `Vec<u8>` column declared `bytes` and one
//! declared `list(scalar)` return the SAME form — hex — while their FILTERS differ, the first taking
//! byte substrings and the second asking about members.
//!
//! That survives the marker layer arriving, and it is worth saying why: the `Vec` fork is read from
//! the ELEMENT's [`DefaultVecMarker`](crate::DefaultVecMarker) row, which is the type's own default
//! and not the FIELD's declared word. A declaration's `list(scalar)` moves what the emitter builds a
//! FILTER from; it does not reach this map, because this map is never handed a field.
//!
//! # The seat is BARE — the backend's bound is not on this map
//!
//! Nothing here names a GraphQL library. `type Output<'a>` carries no `OutputType`, the module is
//! unconditional, and the carriers it maps onto are neutral newtypes whose CITIZENSHIP — the
//! `#[Scalar]` impl — is what the binding's feature gates.
//!
//! That is a law rather than a convenience. This map answers *what form does a value of this type
//! cross as*, which is one fact every binding shares; a bound naming one library would make the map,
//! and every row a declaring crate writes into it, that library's property. A second binding arrives
//! beside the first, over the same rows.
//!
//! What each backend needs of a form it demands at ITS OWN consumption point, inside ITS OWN gate:
//! async-graphql's `#[Object]` requires a resolver's return type to be an `OutputType`, so the
//! emitted face is `E0277` and names the member. The bound moved to where it is spent.
//!
//! # The rows, and what has NO row
//!
//! The table mirrors [`to_filter!`](super::filter)'s, row for row: those are the DECLARABLE field
//! types, so those are the types a wire face can be asked to return.
//!
//! What has no row here has no row there either, and the byte vocabularies are where that was once
//! an ABSENCE and is now a claim. `bytes::Bytes`, `smol_bytes::Bytes`, `smol_bytes::Utf8Bytes`,
//! `Vec<u8>` and `[u8; N]` were registered as filterable and reached no schema in EITHER direction:
//! their operands have no `async_graphql::InputType`, both the types and the traits are foreign to
//! this crate, and the crate that owns a type owes it its wire face. Each is one row here beside one
//! [`carrier`](super::carrier) row now, added in one motion for exactly the reason this paragraph
//! gives — a filter face with no return is half a field type.
//!
//! The MUTABLE byte types are not in that list and no longer have rows anywhere — see
//! [`carrier`](super::carrier)'s byte household for the 2026-08-19 ruling. A buffer is what a value
//! is built in; what a column holds is the value.
//!
//! A DOWNSTREAM type joins by writing its own row, and its `Vec` joins with NOTHING further: the
//! element's [`DefaultVecMarker`](crate::DefaultVecMarker) row — which such a crate already writes to
//! give its collections a filter — is what the `Vec` fork reads.
//!
//! **`primitives::lang`'s five rows are written IN THAT FAMILY** and are not in the list below, which
//! is the same placement its bind and its BSON form take: the family rides the `derive` feature, and
//! a row that cannot exist in every build has no business in a table this file states unconditionally.
//! Each is the identity arm — the three subtags face themselves as their own scalars, the two
//! composites as their own `#[Object]`s — so nothing about them varies from `faces_itself!` but where
//! it is written.

use core::marker::PhantomData;

#[cfg(feature = "jiff")]
use super::filter::JiffDuration;
#[cfg(feature = "jiff")]
use super::filter::{JiffCivilDateTime, JiffZoneOffset};
#[cfg(feature = "regex")]
use super::scalar::RegexPattern;
use super::scalar::{
  F32, F64, FixedU8Array, HexBytes, HyphenatedUuid, I8, I16, I32, I64, I128, NetIpAddr,
  NetIpv4Addr, NetIpv6Addr, NetSocketAddr, NetSocketAddrV4, NetSocketAddrV6, SmolBytes, U8,
  U8Vector, U16, U32, U64, U128,
};
use crate::{
  marker::{BytesMarker, DefaultVecMarker, ListMarker, QuantifiedMarker, SetMarker},
  primitives::{Confidence, Count, Timestamp},
};

// The module is unconditional and its TESTS are not: every one of them reads a form through
// `async_graphql::OutputType::type_name`, which is a question about the binding rather than about
// the map. The map's own claims — which row a type reaches, and that an alias reaches the same one —
// are asserted there too, and asserting them twice under two gates would be two lists to keep in
// step.
#[cfg(all(test, feature = "async-graphql"))]
mod tests;

/// **THE COMPOSED TAIL** — `component`'s published name with its first character RAISED, which is
/// what a generic holder puts after its own name.
///
/// # One expression, because a schema carries ONE convention
///
/// GraphQL keeps one flat namespace, so a holder with a type parameter composes the component's
/// published name onto its own — `BoundingBox` + `f32`. The two sources a composition can draw from
/// disagree about case, and that is not an accident either: an INPUT name composes a component
/// FILTER's name, which is Pascal by the roster's own law, and an OUTPUT name composes the
/// component's SCALAR, which is lowercase by the constitution's first law — *the roster is the
/// framework's own vocabulary, and it is Rust-flavoured*. Left alone, the two halves of one family
/// publish `BoundingBoxf32` beside `BoundingBoxF32Filter`.
///
/// **A Rust width is not a name.** Ruled 2026-08-29: a composed name is a NAME, so its tail takes
/// the case a name takes, and the roster scalar keeps its own lowercase spelling where it stands
/// alone. This is the one expression that raises it, shared by every holder that composes, so the
/// two halves of a family cannot drift and a schema holding two families carries one convention.
///
/// Only the FIRST character moves: `f32` becomes `F32` and `DetectedLanguage` is already what it
/// should be, so a payload whose published name is an object's passes through untouched.
#[cfg(feature = "async-graphql")]
pub(crate) fn composed_tail(component: &str) -> String {
  let mut chars = component.chars();
  let Some(first) = chars.next() else {
    return String::new();
  };
  let mut raised = String::with_capacity(component.len());
  raised.extend(first.to_uppercase());
  raised.push_str(chars.as_str());
  raised
}

/// What a wire face RETURNS a value as — keyed on the value's own type, or on the MARKER that states
/// a reading the type cannot state for itself.
///
/// Total over the types it registers, with the rows spelled out and no blanket. That is forced rather
/// than chosen — one trait cannot carry a `u128` row naming a carrier beside an identity row over
/// everything else without specialization, which is not on stable — and it is the posture
/// [`DefaultMarker`](crate::DefaultMarker) already takes on the other side of the wire.
///
/// # The seat is BARE, and the backend asks where it SPENDS the form
///
/// `type Output<'a>` carries no bound naming a GraphQL library, and that is a law rather than an
/// omission: this map says which FORM a value crosses as, which is one fact every binding shares. A
/// bound here would make the whole map — and every row a declaring crate writes into it — the
/// property of one library, so a second binding could not read it without the first being compiled.
///
/// What each backend needs of the form, it demands at ITS OWN consumption point inside ITS OWN gate:
/// the emitted wire face returns `<T as ToGraphqlOutput>::Output<'_>` from a resolver, and
/// async-graphql's `#[Object]` requires that type to be an `OutputType` structurally — `E0277` at the
/// emitted face, naming the member. The bound moved to where it is spent; nothing about which rows
/// are legal changed.
///
/// The cost, stated: a row naming a form nothing can render is now well formed, and fails at the
/// first face that returns it rather than at the row. That is the trade the law makes, and it is the
/// same one [`ToGraphqlFilter`](crate::ToGraphqlFilter) has always made — its `Filter` seat is bare
/// too, and a filter that no binding can read fails where a schema asks for it.
///
/// # The `M` parameter is what lets ONE trait serve two kinds of implementer
///
/// It DEFAULTS to `Self`, so a TYPE's row is written `impl ToGraphqlOutput for TheirType` and the
/// trait reads as the map it is — every call site spells `<T as ToGraphqlOutput>::Output<'_>` and
/// never mentions the parameter. A MARKER's row names the type it marks —
/// `impl ToGraphqlOutput<Vec<u8>> for BytesMarker<Vec<u8>>` — and that is the whole reason there is
/// no second trait here: the one question a type cannot answer about itself is delegated to the
/// interpretation layer that already answers it on the input side, through
/// [`DefaultVecMarker`](crate::DefaultVecMarker)'s own rows, instead of to a parallel element-keyed
/// trait a declaring crate would have had to implement twice.
///
/// A parameter rather than an associated type, and that was measured: an associated `Marked` puts a
/// PROJECTION in the GAT's `where` clause, and `rustc` will not accept an impl whose clause names
/// one — `E0276`, at every row — because it compares the written clause rather than its normal form.
/// The parameter is the same fact in a position the solver reads.
///
/// # The lifetime is what keeps an identity row free
///
/// `Output<'_>` rather than a plain associated type, because the two kinds of row want different
/// things: a type that already has a wire face is returned BY REFERENCE — `&'a Self`, which
/// async-graphql renders through its own blanket over `&T` — and a type that crosses through a
/// carrier has to build one. A lifetime-free associated type would have made every identity row a
/// clone, on every field of every row of every response.
///
/// # Examples
///
/// A downstream type joins by writing one row. This is `ingraph`'s trait, so the impl names a local
/// type and the orphan rule is satisfied without the framework knowing the type exists — and a
/// `Vec` of it needs nothing more, the element's `DefaultVecMarker` row being what the `Vec` fork
/// reads.
///
/// ```
/// # #[cfg(feature = "async-graphql")]
/// # fn main() {
/// use ingraph::ToGraphqlOutput;
///
/// /// A declarer's own type, with a wire face of its own.
/// #[derive(Clone)]
/// struct Tag(String);
///
/// #[ingraph::__private::async_graphql::Scalar(
///   crate = "ingraph::__private::async_graphql",
///   name = "Tag"
/// )]
/// impl ingraph::__private::async_graphql::ScalarType for Tag {
///   fn parse(
///     value: ingraph::__private::async_graphql::Value,
///   ) -> ingraph::__private::async_graphql::InputValueResult<Self> {
///     match value {
///       ingraph::__private::async_graphql::Value::String(text) => Ok(Self(text)),
///       other => Err(ingraph::__private::async_graphql::InputValueError::expected_type(other)),
///     }
///   }
///
///   fn to_value(&self) -> ingraph::__private::async_graphql::Value {
///     ingraph::__private::async_graphql::Value::String(self.0.clone())
///   }
/// }
///
/// impl ToGraphqlOutput for Tag {
///   type Output<'a> = &'a Self;
///
///   fn to_graphql_output(tag: &Self) -> &Self {
///     tag
///   }
/// }
/// # }
/// # #[cfg(not(feature = "async-graphql"))]
/// # fn main() {}
/// ```
pub trait ToGraphqlOutput<M: ?Sized = Self> {
  /// The form a value of `M` crosses into an OUTPUT position as.
  type Output<'a>
  where
    M: 'a;

  /// That value, in that form.
  ///
  /// An associated function rather than a method, because half the implementers are MARKERS and a
  /// marker has no value to be a receiver of. The call spelling is unchanged either way:
  /// `<T as ToGraphqlOutput>::to_graphql_output(value)`.
  fn to_graphql_output(marked: &M) -> Self::Output<'_>;
}

/// A `Vec` is returned as whatever its ELEMENT's own [`DefaultVecMarker`](crate::DefaultVecMarker)
/// row says a `Vec` of it is READ as — the input side's fork, spent once more.
///
/// This is the row the second trait existed for, and reading it here is what retired that trait: the
/// blob-versus-list question is one fact about an element, the input side already keys it on the
/// element, and a second element-keyed trait beside it was the same fact written twice.
///
/// The marker's row is what carries the answer, and `ToGraphqlOutput<Self>` in the bound is what
/// holds it to answering about the right thing — a marker stating a reading of something else fails
/// HERE, where the delegation is written, rather than at the field that spent it.
impl<T> ToGraphqlOutput for Vec<T>
where
  T: DefaultVecMarker,
  <T as DefaultVecMarker>::Marker: ToGraphqlOutput<Self>,
{
  type Output<'a>
    = <<T as DefaultVecMarker>::Marker as ToGraphqlOutput<Self>>::Output<'a>
  where
    Self: 'a;

  #[inline]
  fn to_graphql_output(marked: &Self) -> Self::Output<'_> {
    <<T as DefaultVecMarker>::Marker as ToGraphqlOutput<Self>>::to_graphql_output(marked)
  }
}

/// **The one element whose `Vec` is not a list.** A `Vec<u8>` is a BLOB, and it crosses as lowercase
/// hex through the same carrier its filter's operands cross through — two characters per byte, which
/// is how a checksum, a magic number and a content id are written everywhere else they appear.
///
/// Rendering it as `[Int!]` is what async-graphql's own blanket would do, and it is the face this
/// module exists to keep out of a schema: a client would receive a thumbnail as a list of small
/// integers, and would have filtered it as hex one field earlier.
///
/// Written on the MARKER rather than on the element, and that is the exception carrying its own
/// reason: `u8`'s [`DefaultVecMarker`](crate::DefaultVecMarker) row already names
/// [`BytesMarker<Vec<u8>>`](crate::BytesMarker) as what a `Vec` of bytes is read under, so the blob's
/// output form is stated at the interpretation that decided it is a blob.
///
/// The copy is the honest cost of a total crossing: [`HexBytes`] owns its bytes, and returning a
/// blob must not consume the row it came from — the same trade the input side's `write` makes.
impl ToGraphqlOutput<Vec<u8>> for BytesMarker<Vec<u8>> {
  type Output<'a>
    = U8Vector
  where
    Vec<u8>: 'a;

  #[inline]
  fn to_graphql_output(marked: &Vec<u8>) -> U8Vector {
    U8Vector::from(marked.clone())
  }
}

/// Every OTHER collection: a list of whatever its element crosses as.
///
/// One row over all three collection markers rather than one per element type, and that is what the
/// marker layer buys: the element's own row supplies the form, so a `Vec<u128>` is a list of
/// `U128` and a `Vec<Vec<u8>>` a list of hex strings without either being registered here. A
/// declaring crate's `Vec<Tag>` reaches a schema with NO output row of its own beyond `Tag`'s.
///
/// The element marker `VM` is not read, and is not meant to be: it is the FILTER's half of the
/// reading, and a return is not a reading. What decides the shape here is that the collection IS one.
///
/// # **The NARROW reading joins them, and the sentence above is the whole reason**
///
/// [`QuantifiedMarker`](crate::QuantifiedMarker) says a collection may be asked only `any` and
/// `count` — that its ELEMENT has no honest literal, so seven of a sequence's nine operators would
/// publish questions with no true answer. Every word of that is about the FILTER. What a client
/// RECEIVES is the members, and a list of members is a list of members under all three readings.
///
/// The row was missing while no element in this crate DEFAULTED to that marker: a declaration's
/// `quantified` word moves the filter and never reaches this map — see *ONE TYPE, ONE OUTPUT FORM* in
/// the module note — so a `Vec<u64>` declared narrow still published through `u64`'s own `ListMarker`
/// default. `primitives::lang`'s `DetectedLanguage` is the first type whose `DefaultVecMarker` IS
/// the narrow one — spelled rather than linked, that family riding the `derive` feature where this
/// module states its rows in every build — and a `Vec` of it is the ruling's own top-k shape, so the
/// absence surfaced as `E0277` at the emitted face of a column a declaration is meant to hold, which
/// is exactly what a missing output row does.
///
/// # The cost, stated
///
/// `Vec<E::Output<'a>>` rather than `&'a [E]`, so a list field allocates a vector per row where the
/// retired element-keyed trait could hand the storage back untouched. That is the price of the fork
/// being read from ONE place: an element whose form is a carrier has to build one per element, so a
/// row that could sometimes borrow and sometimes build would need to branch on the element's own
/// answer, which no stable trait solver will do.
///
/// What the vector HOLDS depends on the element's row, and the SCALAR SUITE moved every numeric
/// from one side to the other: an identity element is still borrowed — `String`'s `Output` is
/// `&'a String`, so a list of text copies nothing — and a numeric element is now a wrapper built
/// per element. That build is a `Copy` into a newtype and allocates nothing; the vector itself is
/// the only allocation, and it was there before.
macro_rules! collection_crosses {
  ($($marker:ident),+ $(,)?) => {
    $(
      impl<E, VM> ToGraphqlOutput<Vec<E>> for $marker<Vec<E>, VM>
      where
        E: ToGraphqlOutput,
      {
        type Output<'a>
          = Vec<<E as ToGraphqlOutput>::Output<'a>>
        where
          Vec<E>: 'a;

        #[inline]
        fn to_graphql_output(marked: &Vec<E>) -> Self::Output<'_> {
          marked
            .iter()
            .map(<E as ToGraphqlOutput>::to_graphql_output)
            .collect()
        }
      }
    )+
  };
}

collection_crosses!(ListMarker, SetMarker, QuantifiedMarker);

/// An `Option` is returned as an `Option` of what is under it — the nullable column's leg, and one
/// row over every `T`.
///
/// `Option<T::Output<'_>>` rather than `&Option<T>`, and the difference is not cosmetic: the inner
/// half is what gets PROJECTED, so a nullable `u128` column returns `Option<U128>` and not an
/// option of a type no schema has.
///
/// Keyed on the TYPE and not on [`NullableMarker`](crate::NullableMarker), because `Option` is not
/// the ambiguous fork: an optional value is an optional value in every reading, where a `Vec` is a
/// blob under one and a list under another.
impl<T> ToGraphqlOutput for Option<T>
where
  T: ToGraphqlOutput,
{
  type Output<'a>
    = Option<<T as ToGraphqlOutput>::Output<'a>>
  where
    Self: 'a;

  #[inline]
  fn to_graphql_output(marked: &Self) -> Self::Output<'_> {
    marked
      .as_ref()
      .map(<T as ToGraphqlOutput>::to_graphql_output)
  }
}

/// The row for a type async-graphql ALREADY faces: a reference to it IS its wire form.
///
/// ONE impl per type where this arm wrote two, and the deleted half is the retired trait's: what a
/// `Vec` of such a type crosses as is now read off the element's own
/// [`DefaultVecMarker`](crate::DefaultVecMarker) row, which every one of these types already has.
macro_rules! faces_itself {
  ($($ty:ty),+ $(,)?) => {
    $(
      impl ToGraphqlOutput for $ty {
        type Output<'a> = &'a Self;

        #[inline]
        fn to_graphql_output(marked: &Self) -> &Self {
          marked
        }
      }
    )+
  };
}

/// The row for a type whose wire form is a CARRIER: the value is built into the carrier on the way
/// out.
///
/// `Copy` is what the arm assumes and every row in it satisfies — the operands that cross this way
/// are the twelve numeric widths of the SCALAR SUITE and a duration, all of them registers. So what
/// a returned value pays is a move of its own bytes into a newtype and no allocation: the one
/// allocating carrier is [`HexBytes`], whose row is written out by hand against
/// [`BytesMarker`](crate::BytesMarker) rather than taken from this arm.
macro_rules! crosses_through {
  ($($ty:ty => $carrier:ty),+ $(,)?) => {
    $(
      impl ToGraphqlOutput for $ty {
        type Output<'a> = $carrier;

        #[inline]
        fn to_graphql_output(marked: &Self) -> $carrier {
          <$carrier>::from(*marked)
        }
      }
    )+
  };
}

// The types whose async-graphql face is already the one this crate wants: a boolean, a string, and
// the two scalars this crate mints itself.
faces_itself!(bool, String, Timestamp);

// The confidence, mirroring the INPUT side's row one file over so that the two directions cannot come
// to disagree — the reason the twelve numerics are mirrored below. It is ONE row over the width for
// the reason stated there, which is a rustc help block that would otherwise vary with the feature
// set.
//
// **IT RETURNS THE WIDTH'S OWN ROSTER SCALAR** — `f32`, `f64`, `f16`, `f128` — where it used to
// return itself under `Score`, `ScoreF64`, `ScoreF16` or `ScoreF128`. Those four are retired: a
// named scalar has to say something the roster does not, and what these said was the INTERVAL, which
// is a constructor's promise rather than a grammar and which a client could act on nowhere. So a
// confidence column and a plain float column of the same width publish one SDL scalar, and the
// interval reaches a reader through the FIELD's documentation and every operand through
// `Confidence::new`.
//
// It crosses BY VALUE where it used to hand back a reference, which is the `crosses_through!` arm's
// shape and costs a register move: a carrier owns its operand, and a confidence is `Copy` at every
// width it measures in.
impl<S: crate::ConfidenceWire> ToGraphqlOutput for Confidence<S> {
  type Output<'a>
    = <S as crate::ConfidenceWire>::Carrier
  where
    S: 'a;

  #[inline]
  fn to_graphql_output(marked: &Self) -> Self::Output<'_> {
    Self::Output::from(marked.get())
  }
}

// The twelve numerics, each RETURNED under the name of its own width — the SCALAR SUITE, mirrored
// here so that the two directions cannot come to disagree. `u8` is among them for its SCALAR row
// alone; the `Vec` of it is the blob row above, reached through `u8`'s own `DefaultVecMarker`.
//
// Four are HYBRID — a JSON number up to 2^53 − 1 and decimal text beyond it — and eight are JSON
// numbers at every value, which is `graphql::scalar`'s division and not this map's: a value past
// that bound loses its low bits to a client that reads every number as a double, and that is a fact
// about the four wide INTEGERS — `u32` fits a double exactly, and a float IS one.
crosses_through!(
  u8 => U8,
  u16 => U16,
  u32 => U32,
  u64 => U64,
  u128 => U128,
  i8 => I8,
  i16 => I16,
  i32 => I32,
  i64 => I64,
  i128 => I128,
  f32 => F32,
  f64 => F64,
);

/// **THE CARDINALITY RETURNS ON `u64`'s OWN SCALAR**, which is the whole of what its wire face is.
///
/// A [`Count`] is a `u64` that knows where it came from, and where it came from is a fact about
/// STORAGE — see the type's own note, where the invariant buys it a column on the two dialects with
/// no unsigned 64-bit type. **The wire has no such shortage.** `u64`'s roster scalar is already
/// HYBRID — a JSON number below 2^53 − 1 and decimal text at or above it — so a count of any
/// magnitude crosses exactly, and a scalar of its own would publish a second SDL name for one
/// form, telling a client nothing it could act on.
///
/// So the SDL a `counting` measure publishes is `u64!`, unchanged by the type that now fills it. The
/// arm is written out rather than taken from `crosses_through!` because that arm spends
/// `Carrier::from(*marked)` and [`U64`] converts from the bare width: the hop through
/// [`Count::get`] is the one line that differs, and it costs a register move.
impl ToGraphqlOutput for Count {
  type Output<'a> = U64;

  #[inline]
  fn to_graphql_output(marked: &Self) -> U64 {
    U64::from(marked.get())
  }
}

// The NETWORK family, returned as the canonical text its filter's operands are read in — the mirror
// of [`carrier`](super::carrier)'s own six rows, so the two directions cannot come to disagree about
// one column. Every one of them is `Copy`, so the arm's `*marked` costs a register move and the
// carrier is a newtype around it.
crosses_through!(
  ::std::net::Ipv4Addr => NetIpv4Addr,
  ::std::net::Ipv6Addr => NetIpv6Addr,
  ::std::net::IpAddr => NetIpAddr,
  ::std::net::SocketAddrV4 => NetSocketAddrV4,
  ::std::net::SocketAddrV6 => NetSocketAddrV6,
  ::std::net::SocketAddr => NetSocketAddr,
);

// The UUID, returned as the canonical hyphenated text its filter's operands are read in — the
// mirror of `carrier`'s own row, so the two directions cannot come to disagree about one column.
// `Copy`, as the six above are, so the arm's `*marked` costs a register move.
crosses_through!(::uuid::Uuid => HyphenatedUuid);

/// **THE PATTERN, returned through the same carrier its operands are read in** — the uuid row's
/// mirror one type over, so a pattern column's two directions cannot come to disagree.
///
/// Written out rather than taken from [`crosses_through!`], and the reason is the arm's own
/// sentence: that arm's `*marked` assumes [`Copy`], which every row in it is, and a `regex::Regex`
/// is not. So the value is CLONED, and what that costs is worth naming because it is paid per
/// returned row: `regex`'s clone bumps the `Arc` behind the compiled strategy and the `Arc<str>`
/// behind the pattern, then boxes one closure and allocates a fresh cache pool at the configured
/// capacity. **NOTHING IS RE-COMPILED** — the automaton is shared — so the price is a handful of
/// allocations and no parse.
///
/// Returning `&'a str` instead would have been free and is refused: it publishes the field as
/// `String!` where the same column's OPERANDS are read as `Regex`, and a schema whose input and
/// output disagree about a column's type is a schema a client cannot round-trip through. The named
/// scalar on both sides is what the allocation buys.
#[cfg(feature = "regex")]
impl ToGraphqlOutput for ::regex::Regex {
  type Output<'a> = RegexPattern;

  #[inline]
  fn to_graphql_output(marked: &Self) -> RegexPattern {
    RegexPattern::from(marked.clone())
  }
}

/// The row for a `NonZero` WIDTH: it is returned as the UNDERLYING INTEGER's own carrier, so a
/// `NonZeroU32` field publishes `u32!` exactly as a `u32` field does.
///
/// **This is the row door (b) was open on** (findit-studio/ingraph#377): the graphql activation is
/// all-or-nothing and demands this crossing of every published member, so a declaration carrying one
/// `NonZeroI32` could publish NOTHING — `E0277`, naming the trait, at the emitted face.
///
/// The width is spent through [`NonZero::get`](core::num::NonZero::get) and never through a
/// transmute or a cast: what the wire carries is the integer, and what the type adds is a value it
/// cannot be, which is a fact about the INPUT direction. The refusal lives there, at
/// [`ZeroOperand`](crate::ZeroOperand), where a client's own `0` is what would spend it — a value
/// coming OUT of a `NonZero` cannot be zero, so there is nothing here to refuse and the arm is
/// total.
macro_rules! nonzero_crosses {
  ($($ty:ty => $carrier:ty),+ $(,)?) => {
    $(
      impl ToGraphqlOutput for $ty {
        type Output<'a> = $carrier;

        #[inline]
        fn to_graphql_output(marked: &Self) -> $carrier {
          <$carrier>::from(marked.get())
        }
      }
    )+
  };
}

nonzero_crosses!(
  ::core::num::NonZeroU8 => U8,
  ::core::num::NonZeroU16 => U16,
  ::core::num::NonZeroU32 => U32,
  ::core::num::NonZeroU64 => U64,
  ::core::num::NonZeroU128 => U128,
  ::core::num::NonZeroI8 => I8,
  ::core::num::NonZeroI16 => I16,
  ::core::num::NonZeroI32 => I32,
  ::core::num::NonZeroI64 => I64,
  ::core::num::NonZeroI128 => I128,
);

/// **THE STATIC TEXT ROW, and it is an OUTPUT one with no INPUT twin** — the second half of door
/// (b), and the one place in this map where the mirror is deliberately one-sided.
///
/// A `&'static str` is what a declaration holds when the value is the PROGRAM's rather than the
/// row's: a fixed kind word, a build constant, a name minted at compile time. It returns as ordinary
/// text — `String`'s row borrows in exactly this way, and async-graphql faces `str` — so publishing
/// one costs no allocation and no clone.
///
/// # There is no [`ToGraphqlInput`](crate::ToGraphqlInput) row, and there cannot be
///
/// That trait's `cross` reads a wire value into the domain type, and the wire value is a `String`
/// built at parse time. Nothing turns one into a `&'static str`: the borrow outlives every buffer
/// the operand could have arrived in, and the only constructions that would type-check are a leak
/// (unbounded memory, driven by a client) or an interning table this crate would have to own. So the
/// absence is STRUCTURAL rather than a row nobody has written yet, and it is left absent rather than
/// faked.
///
/// **What that costs is stated where it bites**: a declared field of this type publishes and cannot
/// be FILTERED, because a filter's operand is written by a client and crosses inward. See
/// [`roster`](super::roster), where the door is recorded with the rest of what the roster does not
/// hold.
impl ToGraphqlOutput for &'static str {
  type Output<'a>
    = &'a str
  where
    Self: 'a;

  #[inline]
  fn to_graphql_output(marked: &Self) -> &str {
    marked
  }
}

// The temporal vocabulary. Four of jiff's types have async-graphql's own scalars (this crate's
// `jiff` feature turns that library's on), so they face themselves; the other three have none
// anywhere and cross through the carriers their filters already use.
#[cfg(feature = "jiff")]
faces_itself!(
  jiff::Timestamp,
  jiff::civil::Date,
  jiff::civil::Time,
  jiff::Zoned
);

#[cfg(feature = "jiff")]
crosses_through!(jiff::SignedDuration => JiffDuration);

// The wall clock and the displacement, mirroring the INPUT side's rows one file over so that the two
// directions cannot come to disagree about which carrier a value is written back through.
#[cfg(feature = "jiff")]
crosses_through!(
  jiff::civil::DateTime => JiffCivilDateTime,
  jiff::tz::Offset => JiffZoneOffset,
);

// The O(1)-clone text type, whose scalar this crate's own `smol_str` feature turns on in
// async-graphql.
#[cfg(feature = "smol_str")]
faces_itself!(smol_str::SmolStr);

/// The row for a BYTE VOCABULARY: the bytes are returned as hex, the form their filter reads them
/// in.
///
/// One copy per returned value, which is [`HexBytes`]'s own trade stated at the blob row above: the
/// carrier owns its bytes, and a return must not consume the row it came from. `AsRef<[u8]>` is what
/// every type in this arm already offers, so a row is a type and nothing else.
macro_rules! returns_as_hex {
  ($( $ty:ty => $carrier:ty ),+ $(,)?) => {
    $(
      impl ToGraphqlOutput for $ty {
        type Output<'a> = $carrier;

        #[inline]
        fn to_graphql_output(marked: &Self) -> $carrier {
          <$carrier>::from(<Self as AsRef<[u8]>>::as_ref(marked).to_vec())
        }
      }
    )+
  };
}

// THE OTHER HALF OF THE CLAIM. Every row here has a `BytesWire` or `TextWire` row in
// [`carrier`](super::carrier) and a `to_filter!` row in [`filter`](super::filter), which is what
// this module's own note promises — one row here beside one row there. Before them these types were
// declarable, filterable and returnable by NOBODY: a field of one compiled and reached a schema in
// neither direction.
//
// There are no gates left. `bytes` and `smol-bytes` are both unconditional dependencies — the first
// since its `Bytes` took the roster's default byte row, the second because it supplies the SQL
// family's buffer — so every row here is in every build.
returns_as_hex!(::bytes::Bytes => HexBytes);

returns_as_hex!(smol_bytes::Bytes => SmolBytes);

/// The FIXED-WIDTH row, one impl over every width — the return half of
/// [`BytesWire<[u8; N]>`](crate::BytesWire).
///
/// Hex, as the blob is, and for the reason the crossing gives: a digest is written that way
/// everywhere else it appears, so a client reading a hash and a thumbnail is reading one form.
///
/// The WIDTH is in the returned scalar's name, because the two directions have to agree about one
/// column: a field publishing `bytes` beside a filter over `Fixed16U8Array` would be the input and
/// the output disagreeing about what the column holds. `FixedU8Array<N>` assembles `Fixed{N}U8Array`
/// on both faces, so `storedDigest: Fixed16U8Array!` reads beside `Fixed16U8ArrayFilter`.
impl<const N: usize> ToGraphqlOutput for [u8; N] {
  type Output<'a> = FixedU8Array<N>;

  #[inline]
  fn to_graphql_output(marked: &Self) -> FixedU8Array<N> {
    FixedU8Array::from(marked.to_vec())
  }
}

/// The row for a UTF-8 VOCABULARY: the text is BORROWED, exactly as `String`'s row borrows.
///
/// The invariant these three maintain is what makes this legal — `Utf8Bytes` reads itself back
/// through `str::from_utf8_unchecked`, so `as_str` is a borrow rather than a validation — and it is
/// why the byte arm above copies where this one does not.
macro_rules! returns_as_str {
  ($($ty:ty),+ $(,)?) => {
    $(
      impl ToGraphqlOutput for $ty {
        type Output<'a> = &'a str;

        #[inline]
        fn to_graphql_output(marked: &Self) -> &str {
          marked.as_str()
        }
      }
    )+
  };
}

// The UTF-8 household, taking the TEXT face on both sides for the reason its `to_filter!` row takes
// it: the guarantee is the type's own, so a question about characters is one it can be asked.
returns_as_str!(smol_bytes::Utf8Bytes);

/// A witness that `T` crosses into an output position — the compile-level assertion, and nothing at
/// runtime.
///
/// It is the [`Marker`](crate::Marker)-style probe the wire faces are proved with: naming
/// `OutputCrossing::<SomeType>::WITNESS` is a demand for the row and nothing else, so a class that
/// lost its row fails where the witness is written rather than inside an expansion nobody can edit.
///
/// **The row and nothing else** is literal now that the seat is bare: this witness says a type HAS an
/// output form, not that a particular library can render one. Which library can is that library's
/// question, asked where it spends the form — a schema built over the class, or a bound written
/// beside this witness inside the binding's own gate. `wire_schema.rs` carries both halves for the
/// whole fork table, which is what keeps the pair from drifting apart.
///
/// The bound is the trait at its DEFAULT parameter, so a witness is a question about the thing a wire
/// face returns rather than about a marker that happens to mention it.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "async-graphql")]
/// # fn main() {
/// use ingraph::OutputCrossing;
///
/// // A type ALIAS resolves to the type it names, which is the whole of what makes this map
/// // alias-proof: the witness below is `u128`'s row, reached through a word no macro could match.
/// type Uuid7 = u128;
///
/// const _: OutputCrossing<Uuid7> = OutputCrossing::WITNESS;
/// const _: OutputCrossing<Vec<u8>> = OutputCrossing::WITNESS;
/// # }
/// # #[cfg(not(feature = "async-graphql"))]
/// # fn main() {}
/// ```
///
/// A type with no row is refused where the witness is written:
///
/// ```compile_fail
/// struct Unregistered;
///
/// const _: ingraph::OutputCrossing<Unregistered> = ingraph::OutputCrossing::WITNESS;
/// ```
pub struct OutputCrossing<T: ToGraphqlOutput + ?Sized>(PhantomData<fn() -> T>);

impl<T: ToGraphqlOutput + ?Sized> OutputCrossing<T> {
  /// The witness itself, and the only value of this type.
  pub const WITNESS: Self = Self(PhantomData);
}