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
//! The sealed identity vocabulary — [`Id`] — and the typed id written over it: [`TypedId`].
//!
//! A key field's type is chosen from a CLOSED set this crate owns, and that is a deliberate
//! exception to the rule everywhere else in this crate — an engine, a backend, a payload and a
//! reason label are all seams a downstream extends. An id is not, and the reason is the matrix on
//! the trait below: a member's ticket in is an ORDER-PRESERVING form on every backend, and no
//! downstream can establish that property for a type this crate's backends have never seen. A
//! vocabulary whose members are admitted by measurement cannot be extended by an `impl`.
//!
//! Extending it is therefore a request to the framework rather than a trait implementation, and the
//! seal is what makes the difference visible at the declaration instead of at the first backend
//! that cannot order the value.
//!
//! # The three admission laws
//!
//! **MEASURED** — a type this crate's backends were measured on keeps one order in every stored
//! form, and the matrix below is that measurement written down. **TRANSPARENT** — a type that HOLDS
//! a measured one and adds nothing a key can see borrows its whole admission, which is why an
//! `Arc<u64>` and the `u64` it holds resolve one file. **DELEGATED** — a type this crate will never
//! see makes the transparency claim FOR ITSELF through [`DelegatesId`], and the framework's own
//! derives write that claim, so a `#[derive(ingraph::Id)]` wrapper, a
//! `#[derive(ingraph::NewType)]` wrapper or a `#[derive(ingraph::Enum)]` vocabulary stands at a key
//! position with no extra word.
//!
//! The third law is the second one opened, not a hole in the first: a delegation is admitted on the
//! member it grounds in, and a chain that grounds in nothing measured is no id. What changed is WHO
//! may write the transparency claim, and `unsafe` is the price — the seal still refuses a bare
//! `impl Id`, and the assertion a delegation makes is stated where it can be audited.
//!
//! # `#[derive(ingraph::Id)]` is the third law's OWN DOOR, and the zero-ceremony one
//!
//! ```text
//! #[derive(ingraph::Id)]
//! #[repr(transparent)]
//! pub struct TrackId(uuid::Uuid);
//! ```
//!
//! That is the whole declaration. The derive is NARROW where the other two are wide — it takes a
//! `#[repr(transparent)]` tuple wrapper and refuses every other shape by name — and what it buys for
//! the narrowness is that the transparency contract closes BY CONSTRUCTION rather than by assertion.
//! *No second field, tag or width* is the shape law; *`delegate` is pure* is a field read; and *two
//! `Self`s are equal exactly when their delegates are* holds because the `PartialEq` on the type is
//! the one the device emitted, delegating, and a second is `E0119`. A hand `unsafe impl` still
//! carries all three as an obligation a reader has to check.
//!
//! It writes the rest of what an address needs as well — the identity kit, `Display`/`FromStr`, the
//! storage pair, a keyset position, a schema scalar under the type's own name, and the free
//! `#[repr(transparent)]` views `from_ref` and `from_slice` — because the register is a MEASUREMENT:
//! it is what two live products each hand-wrote, independently, before the door existed.
//!
//! Which door a wrapper wants is decided by what it IS rather than by what it holds.
//! `#[derive(ingraph::Id)]` equips an ADDRESS: no invariant beyond its inner's, no choice of faces,
//! and the casts that come with declaring so. `#[derive(ingraph::NewType)]` equips a VALUE: it takes
//! kit words, so a declaration installs the faces it names and no others, and it takes a
//! `scalar(check = "…")` or `scalar(parse = "…")` DOOR — which is the road for a wrapper whose values
//! are a checked subset of its inner's, and which the id door's `from_ref` would walk straight
//! around. Both write the key row, so a type takes ONE of them; two would be `E0119` on this very
//! trait.
//!
//! [`TypedId`] answers the other half of the question. The vocabulary says what an id may BE; the
//! wrapper says what an id ADDRESSES, by carrying the addressed type in its own. It is here because
//! it is written OVER the vocabulary — one framework type generic in both, so a target's identity
//! rides in the type with no newtype minted per entity. It is a MEMBER, on the pointer-delegation
//! law: transparent to the id it holds, so every backend form and the whole of the order are that
//! id's.

extern crate alloc;

use core::{
  fmt,
  hash::{Hash, Hasher},
  marker::PhantomData,
};

use crate::Identifiable;

// The STORAGE SEAM, which is a fact about the VOCABULARY rather than about columns: its rows are
// exactly this module's members, and the audit that keeps them exactly that reads the member list
// below. Ungated, as the vocabulary is — `IdColumn<Db>` puts no bound on `Db` and names no driver.
mod column;

pub use column::IdColumn;

/// A type admissible as a key field — the sealed identity vocabulary.
///
/// Sealed: the member list below is the whole of it, and it is closed on purpose (see the module
/// note). The trait carries no methods — what an id OWES is per-backend, so each backend states its
/// own duty over this vocabulary and none of them is stated here.
///
/// # The members, and what each is admitted on
///
/// | member | gate | admitted because |
/// |---|---|---|
/// | `i8` … `i128` | — | fixed width, two's-complement order every backend agrees on |
/// | `u8` … `u128` | — | fixed width; the wide end already ships a big-endian storage form |
/// | `NonZero*` (all ten) | — | transparent over their integer member — same width, same order |
/// | [`uuid::Uuid`] | — | fixed 16 bytes, canonical rendering; ALL versions, since a v7 is a
///   generation policy and not a type |
/// | `bson::Uuid` | `mongo` | the BSON-side wrapper of the same 16 bytes |
/// | `bson::ObjectId` | `mongo` | fixed 12 bytes — the fixed-width bytes case |
/// | `[u8; N]` | — | fixed width ONLY, which is the half of "bytes" that keeps a uniform order |
/// | `String`, [`Utf8Bytes`](smol_bytes::Utf8Bytes) | — | text, at the cost of the escape a filesystem segment takes |
/// | `SmolStr` | `smol_str` | the same text member, under the feature that supplies the type |
/// | `Arc<T>`, `Rc<T>`, `Box<T>` over a member | — | transparent to the pointee — same width, same order, and the SAME ADDRESS. Written as [`DelegatesId`], which is where that law now lives |
/// | [`TypedId<I, E>`](TypedId) over a member, where `E` declares it back | — | transparent to the id it holds, by the same law: the entity marker is a type-level fact that reaches no stored byte |
/// | ANY type asserting [`DelegatesId`] over a member | — | the same law, claimed from outside this crate: the framework's `Id`, `NewType` and `Enum` derives write the claim, and a hand `unsafe impl` may |
/// | `Ipv4Addr`, `Ipv6Addr` | — | fixed 4 and 16 bytes, and std's order IS the big-endian octet order |
/// | `IpAddr` | — | the tagged pair of those two, at a fixed width |
/// | `SocketAddrV4`, `SocketAddrV6` | — | an address plus its port, and — for v6 — its `flowinfo` and `scope_id` |
/// | `SocketAddr` | — | the tagged pair of those two |
///
/// # What is NOT a member, and why
///
/// | excluded | measured reason |
/// |---|---|
/// | `Vec<u8>` and every variable-length byte string | the orders DIVERGE: a SQL blob compares
///   lexicographically while MongoDB's `BinData` compares LENGTH FIRST, so one backlog cursor would
///   walk two different orders. `[u8; N]` is the same data at one width, where the two agree |
/// | `usize` / `isize` | platform width is not a contract, and an id PERSISTS — a key written on a
///   64-bit host must still be the same key on a 32-bit one |
/// | `bool` | a two-value identity is not an identity |
/// | temporal types | an instant collides (two events at one nanosecond) and carries a zone hazard;
///   a time-ordered id is an integer of nanoseconds, which IS a member |
///
/// # The admission matrix
///
/// A member's ticket in is an order-preserving form on EVERY backend, so the matrix is the
/// vocabulary's acceptance artifact rather than documentation of it. The traps are named where they
/// are, because each is a form that looks obvious and misorders:
///
/// | member | SQL column | MongoDB | fs segment | order |
/// |---|---|---|---|---|
/// | `i8`…`i64` | the native signed integer | `Int32` / `Int64` | decimal, `-` in the verbatim range | ✓ |
/// | `i128` | [`BeI128`](crate::BeI128) → the byte column | 16-byte `BinData` — **NOT `Decimal128`**, whose order is numeric-with-NaN rather than bytewise | decimal | ✓ via the big-endian form |
/// | `u8`…`u32` | the next signed integer up, losslessly | `Int32` / `Int64` | decimal | ✓ (the widening is exact) |
/// | `u64` | [`BeU64`](crate::BeU64) → the byte column | **`BeU64` as fixed-8 `BinData`, NOT a cast to `Int64`** — every value past `i64::MAX` becomes negative and sorts BELOW zero, so the cast inverts the top half of the range against the bottom | decimal | ✓ only via the Be form |
/// | `u128` | [`BeU128`](crate::BeU128) → the byte column | 16-byte `BinData`, for the reason `u64` cannot cast | decimal | ✓ via the big-endian form |
/// | `NonZero*` | as its integer member | as its integer member | as its integer member | ✓ inherited |
/// | [`uuid::Uuid`] | native `uuid` or the 16 bytes | `BinData` subtype 4 | canonical lowercase hyphenated | ✓ (fixed width, and the rendering is bytewise-monotone) |
/// | `bson::Uuid` | the same 16 bytes | the same subtype 4 | as [`uuid::Uuid`] | ✓ |
/// | `bson::ObjectId` | the 12 bytes | `ObjectId`, which compares bytewise | lowercase hex, 24 chars | ✓ |
/// | `[u8; N]` | the byte column | `BinData` — equal length, so length-first degenerates to bytewise | lowercase hex, 2N chars | ✓ |
/// | text | the native text column | `String` | the escape below | ✓ up to the engine's collation, which is the engine's to document per dialect |
/// | `Arc<T>`/`Rc<T>`/`Box<T>` | as `T` | as `T` | as `T` | ✓ inherited — the pointer is not part of the value |
/// | a [`DelegatesId`] type | as its `Inner` at every id duty | the same | the same | ✓ inherited, and the inheritance is what the `unsafe` asserts |
/// | [`TypedId<I, E>`](TypedId) | as its `I` | as its `I` | as its `I` | ✓ inherited — the entity marker is `PhantomData`, so it is not part of the value either, and a typed id addresses the row its bare `I` does |
/// | `Ipv4Addr` | the 4 octets | fixed-4 `BinData` | dotted quad | ✓ — MEASURED: std's `Ord` is the big-endian octet order (`10.0.0.0 > 9.255.255.255`), so the bytes ARE the order |
/// | `Ipv6Addr` | the 16 octets | fixed-16 `BinData` | 32 lowercase hex characters | ✓ — measured the same way (`1:: > 0:ffff::`) |
/// | `IpAddr` | 17 bytes: a tag then the address, V4 zero-extended | fixed-17 `BinData` | the inner form | ✓ — MEASURED: std ranks by DISCRIMINANT FIRST (`V4::MAX < V6::MIN`), which a leading tag byte reproduces. **The naked 1+4 / 1+16 form is the trap**: it is VARIABLE width, so MongoDB's length-first `BinData` order decides before the tag does — here it happens to agree (5 < 17, and V4 is the lower tag), and relying on that coincidence is what the fixed 17 refuses to do |
/// | `SocketAddrV4` | 6 bytes: the octets then the port big-endian | fixed-6 `BinData` | `<dotted quad>_<port>` | ✓ — MEASURED: address before port |
/// | `SocketAddrV6` | 26 bytes: the octets, the port, `flowinfo`, `scope_id`, each big-endian | fixed-26 `BinData` | `<32 hex>_<port>_<flowinfo>_<scope_id>` | ✓ — MEASURED: address, then port, then `flowinfo`, then `scope_id`, and **all four participate in `Eq` and `Hash`**, so all four are part of the ADDRESS. Dropping the last two is the trap: two ids Rust calls unequal would share one file |
/// | `SocketAddr` | 27 bytes: a tag then the V6 form, V4 zero-extended | fixed-27 `BinData` | the inner form | ✓ — MEASURED discriminant-first, as `IpAddr` is |
///
/// Two cells were MEASURED rather than reasoned, because std's order is not derivable from the type.
/// Both enums rank by discriminant before payload, so every V4 sorts below every V6 — and
/// `SocketAddrV6`'s `flowinfo` and `scope_id` both participate in `Eq`, `Hash` and `Ord`, which is
/// what puts them in the address rather than in a comment. Postgres's `INET` is deliberately NOT
/// reached for: its ordering is the engine's rather than provably ours, and a byte column keeps the
/// matrix checkable.
///
/// The one cell that surprised the measurement is `u8`…`u32`: they are the only unsigned members
/// that need no big-endian carrier, because each widens LOSSLESSLY into the next signed integer and
/// the widening is order-preserving. `u64` has no signed type above it to widen into, which is
/// exactly where the trap starts.
///
/// # A filesystem segment is verbatim or escaped, and never ambiguous
///
/// The rendering is the FILESYSTEM BACKEND's rather than this vocabulary's, and it is summarised
/// here because the matrix's last column cannot be read without it: a segment is written verbatim
/// when it matches `[a-z0-9_-]+` and does not begin with `=`, and otherwise as `=` followed by the
/// lowercase RFC 4648 base32 of its UTF-8 bytes. Single-case on both sides, because the product's
/// own filesystem is case-insensitive and a two-case range would let two distinct text ids collide
/// into one path. Every non-text member above renders verbatim by construction.
///
/// # Examples
///
/// A member resolves the bound:
///
/// ```
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<u64>();
/// admits::<uuid::Uuid>();
/// admits::<[u8; 16]>();
/// admits::<String>();
/// ```
///
/// A variable-length byte string does not — the exclusion whose reason is that two backends order
/// it differently:
///
/// ```compile_fail,E0277
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<Vec<u8>>();
/// ```
///
/// Nor does a platform-width integer, which is a different exclusion with a different reason:
///
/// ```compile_fail,E0277
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<usize>();
/// ```
///
/// And the seal holds against a downstream type, which is what makes the set CLOSED rather than
/// merely small — the refusal is the unnameable supertrait, not a missing impl:
///
/// ```compile_fail,E0277
/// struct MyId(u64);
///
/// impl ingraph::Id for MyId {}
/// ```
///
/// What a downstream type takes INSTEAD is the delegation door, and the door is the whole of it: a
/// type that holds a member and adds nothing a key can see says so once, and is admitted.
///
/// ```
/// struct MyId(u64);
///
/// // SAFETY: `MyId` holds a `u64` and nothing else — every id duty reads that `u64`.
/// unsafe impl ingraph::DelegatesId for MyId {
///   type Inner = u64;
///
///   fn delegate(&self) -> &u64 {
///     &self.0
///   }
/// }
///
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<MyId>();
/// ```
///
/// The chain still has to GROUND in a measured member, which is what keeps the third law from being
/// a hole in the first: a delegation onto an excluded type is legal, inert, and no id.
///
/// ```compile_fail,E0277
/// struct MyId(Vec<u8>);
///
/// // SAFETY: transparent to the `Vec<u8>` — which is not a member, so nothing is admitted.
/// unsafe impl ingraph::DelegatesId for MyId {
///   type Inner = Vec<u8>;
///
///   fn delegate(&self) -> &Vec<u8> {
///     &self.0
///   }
/// }
///
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<MyId>();
/// ```
#[diagnostic::on_unimplemented(
  message = "`{Self}` is not part of this crate's id vocabulary",
  label = "not an id",
  note = "KEY ADMISSION COMES FREE WITH THE DERIVES, and a WRAPPER has a door of its own: \
          `#[derive(ingraph::Id)]` over a `#[repr(transparent)]` tuple struct admits `{Self}` and \
          equips it whole, from one word. A VALUE that is not an address takes \
          `#[derive(ingraph::NewType)]` and a VOCABULARY takes `#[derive(ingraph::Enum)]` — all \
          three write the row, with no extra word",
  note = "a key field is otherwise one of: an integer (`i8`…`i128`, `u8`…`u128`, or a `NonZero` of \
          one), `uuid::Uuid`, a fixed-width `[u8; N]`, text (`String` or `Utf8Bytes`), a network \
          address (`IpAddr`, `Ipv4Addr`, `Ipv6Addr`, `SocketAddr`, `SocketAddrV4`, \
          `SocketAddrV6`), an `Arc`/`Rc`/`Box` of any of those, a `TypedId` over one whose entity \
          names that very wrapper as its own `Id`, or — under their features — `SmolStr`, \
          `bson::Uuid` and `bson::ObjectId`",
  note = "for a type no derive can mint, the HAND road is `unsafe impl ingraph::DelegatesId for \
          {Self}` naming the member it holds — the transparency assertion, whose contract is on \
          that trait. `impl ingraph::Id` is not a road: the vocabulary is SEALED, and a member's \
          own ticket in is a MEASUREMENT this crate made. Variable-length bytes, `usize`/`isize`, \
          `bool` and temporal types are excluded for measured reasons — see the `Id` module note"
)]
pub trait Id: sealed::Sealed {}

/// The seal. Public inside a private module, so the bound is nameable from this crate's own
/// backends and unnameable — hence unimplementable — from outside it.
mod sealed {
  pub trait Sealed {}
}

/// **UNSAFE TO IMPLEMENT.** The TRANSPARENCY ASSERTION: `Self` holds an [`Id`] and adds nothing a
/// key can see, so every id duty may read [`delegate`](Self::delegate) INSTEAD of `Self`.
///
/// # Safety
///
/// Implementing this trait asserts that at every duty the id vocabulary decides — the filesystem
/// segment, the identity a key is found by, and the order that identity walks in — `Self` and
/// `*self.delegate()` are the SAME VALUE: two `Self`s are equal exactly when their delegates are,
/// [`delegate`](Self::delegate) is pure and returns the same inner for the same `Self` every time,
/// and `Self` carries no second field, tag or width that a key would have to distinguish. That is
/// the same law `Arc<T>` and [`TypedId<I, E>`](TypedId) are admitted under — *transparent means the
/// SAME ADDRESS* — said by a type this crate cannot see. Break it and two distinct keys share one
/// stored row, which is corruption rather than a compile error, and that is why the word is
/// `unsafe`.
///
/// **The framework's own derives write this impl and uphold it BY CONSTRUCTION**:
/// `#[derive(ingraph::NewType)]` delegates to the one value the declaration wraps, and
/// `#[derive(ingraph::Enum)]` to the vocabulary's own canonical word — a `static` per member, and,
/// where the declaration carries an `#[ingraph(other)]` escape, the word that escape is already
/// holding. In both shapes the words are distinct by construction: a closed roster's are checked
/// distinct at the declaration, and an open one's door routes every word a member names to that
/// member before it ever builds an escape. A hand impl carries the obligation the roster's
/// transparent members were audited on, and nothing weaker.
///
/// # Admission is a CONSEQUENCE, and the chain grounds in a measured member
///
/// [`Inner`](Self::Inner) takes no bound, so this trait may be asserted over anything and the derives
/// mint it unconditionally — a `#[derive(ingraph::NewType)] struct Ratio(f64)` says the true thing
/// about itself and is simply not an id, because [`Id`] is granted only where the delegate is one
/// too. Chains compose: an `Arc<MyId>` is admitted when `MyId` is, and a delegation onto an excluded
/// type is legal, inert, and refused at the KEY POSITION, which is where a reader can act on it.
///
/// # Examples
///
/// The whole of the hand road — one impl, and a wrapper is a key:
///
/// ```
/// struct Sha256([u8; 32]);
///
/// // SAFETY: the digest and nothing else — every id duty reads those thirty-two bytes.
/// unsafe impl ingraph::DelegatesId for Sha256 {
///   type Inner = [u8; 32];
///
///   fn delegate(&self) -> &[u8; 32] {
///     &self.0
///   }
/// }
///
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<Sha256>();
/// admits::<std::sync::Arc<Sha256>>();
/// ```
// The notes are written to read correctly at BOTH sites rustc surfaces them: on the wrapper a
// declarer wrote, and — one link further down a chain — on the type that wrapper delegates TO. So
// neither of them tells the reader to write an impl `for {Self}`: at the second site `{Self}` is the
// DELEGATE, which is either excluded by measurement or a type the orphan rule forbids implementing
// for, and an instruction to implement it there would be advice that cannot be taken.
#[diagnostic::on_unimplemented(
  message = "`{Self}` does not delegate to an id, so it cannot stand at a key position",
  label = "no delegation",
  note = "KEY ADMISSION COMES FREE WITH THE DERIVES: `#[derive(ingraph::Id)]` on a \
          `#[repr(transparent)]` wrapper, `#[derive(ingraph::NewType)]` on a value and \
          `#[derive(ingraph::Enum)]` on a vocabulary each write this impl for you, with no extra \
          word — reach for the derive before reaching for this trait. The first also UPHOLDS the \
          contract by construction, the shape being checked and the identity kit emitted rather \
          than left to a hand to keep in step",
  note = "the HAND road is for a type your own crate declares that no derive can mint: \
          `unsafe impl ingraph::DelegatesId` on the wrapper, naming the member it holds. It is \
          `unsafe` because it ASSERTS transparency — see the trait's contract",
  note = "where `{Self}` is the type something else DELEGATES TO, this is the chain failing to \
          ground: a delegation is admitted on the measured member it bottoms out in, and \
          `{Self}` is not one. Variable-length bytes, `usize`/`isize`, `bool` and temporal types are \
          excluded for measured reasons, and no `impl` can add them — see `ingraph::Id`"
)]
pub unsafe trait DelegatesId {
  /// The id this type IS, wearing its own name.
  ///
  /// Unbounded on purpose — see *Admission is a consequence*. What makes a delegation an id is that
  /// this type is one, and the framework asks that question where the key is spent.
  type Inner;

  /// The delegate: the inner value every id duty reads in place of `self`.
  ///
  /// Named for what it hands back rather than for the field it hands back FROM. `inner` and
  /// `as_inner` are spellings a declaring crate already owns on its own newtypes — `Utf8Bytes` has
  /// an `as_inner`, and a product's wrapper commonly has both — so a trait method under either name
  /// would compete with the accessor an author already wrote. `delegate` is this trait's own word
  /// and collides with nothing.
  fn delegate(&self) -> &Self::Inner;
}

/// The ONE door into the vocabulary that is not a measured row: a delegation whose delegate is
/// itself an id.
///
/// One blanket rather than two roads, because two roads into one trait is `E0119` — and the road
/// that survives is this one, since the measured rows are CONCRETE and a concrete row and a
/// bounded blanket are disjoint wherever the bound is knowably unmet. The seal rides the same
/// bound, so the two halves stay ONE set: a delegation that is admitted here is sealed here, and a
/// bare `impl Id` is still the unnameable supertrait's refusal.
impl<T> sealed::Sealed for T
where
  T: DelegatesId,
  T::Inner: Id,
{
}

/// [`do_not_recommend`](diagnostic::do_not_recommend) was WEIGHED HERE AND DECLINED, and the
/// measurement is worth keeping.
///
/// Marked, every refusal below this blanket lands on [`Id`] with its own sentence — which reads well
/// for a delegation grounded in an excluded type. It also FLATTENS the one refusal this module
/// documents at length: [`TypedId`]'s entity mismatch is `E0271` on the projection equality,
/// naming what the entity declared beside what was written, and marking the blanket turns it into a
/// plain `E0277` naming neither. A better message for one case is not worth a worse one for the case
/// a type exists to produce, so the blanket stays unmarked and [`DelegatesId`]'s own notes are
/// written to read correctly wherever rustc surfaces them.
impl<T> Id for T
where
  T: DelegatesId,
  T::Inner: Id,
{
}

macro_rules! id {
  ($($ty:ty),* $(,)?) => {
    $(
      impl sealed::Sealed for $ty {}
      impl Id for $ty {}
    )*
  };
}

/// THE member list, written once and read by every consumer that has to agree with it.
///
/// A callback macro rather than a set of invocations, because several files need the SAME list and a
/// vocabulary hand-synced across files is a vocabulary that drifts. Today's consumers:
///
/// - `id!` here, which writes each row's `Sealed` + `Id` pair — the admission itself.
/// - `store::fs`'s completeness audit, which instantiates its `Segment` bound at each row, so a
///   member admitted with no filesystem rendering is a compile error NAMING that member rather than
///   a surprise at whatever declaration first spells it in a key.
/// - `store::field`'s crossability audit, which instantiates its [`Field`](crate::Field) bound at
///   each row, so a member admitted with no row is a compile error naming that member rather than a
///   surprise at whatever key first spells it. It REPLACED `store::tantivy`'s shipped-parity audit
///   over the same list, and the obligation got stronger when it moved: that one said the shipped
///   engine paired the shipped vocabulary, where this one says the vocabulary is crossable AT ALL —
///   a row is engine-blind, so one here is the only row a member needs to reach every engine there
///   is.
///
/// Every path is written in full, because a row resolves at the CONSUMER's site rather than here.
///
/// # The gated rows carry their own gate
///
/// `#[cfg]` rides the invocation, exactly as it rode the `id!` calls this list replaces, so each
/// consumer sees the member set of ITS OWN build: a `--no-default-features` audit is complete over a
/// vocabulary without the BSON pair, and the `mongo` one is complete over a vocabulary with it.
/// Neither consumer states a feature of its own.
///
/// # What this list does NOT carry
///
/// The five GENERIC rows — `Arc<T>`, `Rc<T>`, `Box<T>`, `[u8; N]` and [`TypedId<I, E>`](TypedId) —
/// are `impl`s over a PARAMETER rather than types, so no list of types can emit them: each is
/// written out below under the law it is admitted on, and the audit reaches each through a witness
/// leaf. That is not a hole in the audit — a parameterised row is bounded on what it holds, so the
/// only thing one can fail is EXISTING, and one instantiation settles that.
///
/// **THIS LIST IS THE MEASURED HALF, and it is the only half a completeness audit can be written
/// over.** Four of those five are [`DelegatesId`] impls today, and so is every type a downstream
/// admits: a delegation's duties are answered by the one blanket each duty writes over the bridge,
/// so there is nothing per-type left for an audit to check. What a consumer audits here is the set a
/// delegation chain must BOTTOM OUT IN, which is exactly why the list did not grow.
macro_rules! for_each_id_member {
  ($callback:ident) => {
    $callback!(i8, i16, i32, i64, i128);
    $callback!(u8, u16, u32, u128);
    // `u64` ALONE, for the reason `id::column`'s own module note names: it is the first member
    // stored PER `Db` rather than by one blind row (native on MySQL, the big-endian blob elsewhere),
    // so a consumer whose witness is `IdColumn`-shaped needs to ask it a different question than its
    // siblings above. The other three consumers here (`id!`, the segment audit, the field audit) do
    // not care — `u64` reaches them exactly as it did bundled — so splitting the line costs them
    // nothing and is what lets `id::column::audit_row!` answer only `u64` differently.
    $callback!(u64);
    $callback!(
      core::num::NonZeroI8,
      core::num::NonZeroI16,
      core::num::NonZeroI32,
      core::num::NonZeroI64,
      core::num::NonZeroI128,
      core::num::NonZeroU8,
      core::num::NonZeroU16,
      core::num::NonZeroU32,
      core::num::NonZeroU64,
      core::num::NonZeroU128,
    );
    $callback!(uuid::Uuid);
    $callback!(String, smol_bytes::Utf8Bytes);

    // The network family, all six of std's. Each is admitted on a MEASURED order rather than an
    // assumed one — see the matrix: the two enums rank by discriminant before payload, and
    // `SocketAddrV6` carries two fields beyond the obvious pair that are part of its identity.
    $callback!(
      core::net::IpAddr,
      core::net::Ipv4Addr,
      core::net::Ipv6Addr,
      core::net::SocketAddr,
      core::net::SocketAddrV4,
      core::net::SocketAddrV6,
    );

    // The text member under the feature that supplies the type — the crate's own text type is
    // structural and needs no gate, so this is the one text row that has one.
    #[cfg(feature = "smol_str")]
    $callback!(smol_str::SmolStr);

    // The BSON-side pair. Both are fixed-width and both are what a MongoDB-stored declaration
    // already holds, so the vocabulary reads "all uuid" generously rather than making a declarer
    // convert at every key.
    #[cfg(feature = "mongo")]
    $callback!(bson::Uuid, bson::oid::ObjectId);
  };
}

pub(crate) use for_each_id_member;

for_each_id_member!(id);

// Pointer delegation, and the law is the one `NonZero` established: transparent means the SAME
// ADDRESS, so an `Arc<u64>` and the `u64` it holds resolve one file. A pointer is how a value is
// HELD and not part of what it IS, so admitting it costs the vocabulary nothing.
//
// Written as `DelegatesId` rather than as a pair of hand rows, and the rewrite is where the third
// admission law came from: these three WERE the transparency claim, stated in impls only this file
// could write. Naming the claim is what let a downstream make it — and it costs nothing here, since
// admission still arrives through the one blanket above and the duty rows below are now one row
// each instead of three.
//
// SAFETY: a pointer is not part of the value. `*self` IS the pointee, at the same equality, the same
// order and the same address.
unsafe impl<T: Id> DelegatesId for alloc::sync::Arc<T> {
  type Inner = T;

  #[inline]
  fn delegate(&self) -> &T {
    self
  }
}

/// SAFETY: as [`Arc`](alloc::sync::Arc), whose note is the whole reason.
unsafe impl<T: Id> DelegatesId for alloc::rc::Rc<T> {
  type Inner = T;

  #[inline]
  fn delegate(&self) -> &T {
    self
  }
}

/// SAFETY: as [`Arc`](alloc::sync::Arc), whose note is the whole reason.
unsafe impl<T: Id> DelegatesId for alloc::boxed::Box<T> {
  type Inner = T;

  #[inline]
  fn delegate(&self) -> &T {
    self
  }
}

// A fixed width, and that is the whole of the admission: at one length MongoDB's length-first
// `BinData` order and a SQL blob's lexicographic order are the same order. `Vec<u8>` is this data
// without the width, which is why it is excluded rather than merely unimplemented.
impl<const N: usize> sealed::Sealed for [u8; N] {}
impl<const N: usize> Id for [u8; N] {}

/// An id AND WHAT IT ADDRESSES: `I` is the stored id, `E` the thing that id names.
///
/// `TypedId<uuid::Uuid, Scene>` and `TypedId<uuid::Uuid, Keyframe>` are different types over the
/// same sixteen bytes, and that difference is the whole of what this type is for.
///
/// # The loss it repairs
///
/// A `ref` field carries `<Target as Identifiable>::Id`, and the forward equation
/// [`refers_to`](crate::refers_to) is that sentence as a bound. Where two targets are addressed by
/// the SAME vocabulary member the equation cannot tell them apart: a field really holding a
/// keyframe's id satisfies a `ref` naming `Scene` and compiles, because both ids are `uuid::Uuid`.
/// Putting the target INTO the id's type is what makes that `E0271` naming both entities — the
/// refusal a per-entity key struct used to give for free.
///
/// # One framework type, and nothing generated
///
/// The alternative is a newtype per entity with these six impls rewritten under each name. Here `E`
/// is the entity type ITSELF: there is no name to mint, and an entity this crate will never see is
/// admitted by being written in the parameter. Every impl below is written ONCE, generically over
/// `I` — so STORAGE AND WIRE SEE ONLY `I`, each impl delegating to it, and the marker reaches no
/// column.
///
/// `I` takes no bound here, as [`Identifiable::Id`](crate::Identifiable::Id) takes none: what an id
/// must satisfy is asked where it is SPENT — a bind asks for a carrier row, and the equation below
/// asks for nothing at all.
///
/// The name is `TypedId` and not the shorter one because [`Id`] is this module's vocabulary trait,
/// and a trait and a struct cannot share one name.
///
/// # Adopted by construction, never mandated
///
/// A declaration whose id is a bare `u64` is as good as one whose id is a `TypedId<u64, _>`: the
/// framework ships the type and no policy about it. What takes it by construction is the
/// schema-driven line, where entity types are generated beside the ids addressing them — a hand
/// author chooses, per record.
///
/// # `E` implements nothing, and infects nothing
///
/// The marker is held as `PhantomData<fn() -> E>`, the spelling every marker in this crate carries,
/// so `E` contributes no auto-trait, variance or drop obligation: the wrapper is [`Send`] and
/// [`Sync`] on its `I` alone, at an `E` that is neither. And [`Clone`], [`Copy`], [`PartialEq`],
/// [`Eq`], [`Hash`] and [`Debug`](fmt::Debug) are written out bounding `I`, where a derive would
/// state each over `E` as well — an entity type with no impls at all still has an id that copies.
///
/// # Examples
///
/// The equation binds the target's own id, and what discriminates is the type:
///
/// ```
/// use ingraph::{Identifiable, TypedId, refers_to};
///
/// struct Scene {
///   id: TypedId<uuid::Uuid, Scene>,
/// }
///
/// struct Keyframe {
///   id: TypedId<uuid::Uuid, Keyframe>,
/// }
///
/// impl Identifiable for Scene {
///   type Id = TypedId<uuid::Uuid, Scene>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// impl Identifiable for Keyframe {
///   type Id = TypedId<uuid::Uuid, Keyframe>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// let raw = uuid::Uuid::from_u128(7);
/// let scene = Scene {
///   id: TypedId::new(raw),
/// };
///
/// // The entity hands out the wrapper, and the wrapper hands out what a column binds.
/// assert_eq!(scene.id().id(), raw);
///
/// refers_to::<TypedId<uuid::Uuid, Scene>, Scene>();
/// ```
///
/// The same block with one line changed, refused: a field holding a KEYFRAME's id is not a `ref` at
/// `Scene`, and the error names both types. With bare `uuid::Uuid` on both sides this is what
/// compiles.
///
/// ```compile_fail,E0271
/// use ingraph::{Identifiable, TypedId, refers_to};
///
/// struct Scene {
///   id: TypedId<uuid::Uuid, Scene>,
/// }
///
/// struct Keyframe {
///   id: TypedId<uuid::Uuid, Keyframe>,
/// }
///
/// impl Identifiable for Scene {
///   type Id = TypedId<uuid::Uuid, Scene>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// impl Identifiable for Keyframe {
///   type Id = TypedId<uuid::Uuid, Keyframe>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// let raw = uuid::Uuid::from_u128(7);
/// let scene = Scene {
///   id: TypedId::new(raw),
/// };
///
/// // The entity hands out the wrapper, and the wrapper hands out what a column binds.
/// assert_eq!(scene.id().id(), raw);
///
/// refers_to::<TypedId<uuid::Uuid, Keyframe>, Scene>();
/// ```
pub struct TypedId<I, E> {
  id: I,
  // `fn() -> E` rather than a bare `E`, so the marker contributes neither an auto-trait nor a
  // variance obligation — the same spelling, for the same reason, as the `Db` marker every
  // comparison kind carries.
  entity: PhantomData<fn() -> E>,
}

impl<I, E> TypedId<I, E> {
  /// The id `id`, as the address of an `E`.
  #[inline]
  #[must_use]
  pub const fn new(id: I) -> Self {
    Self {
      id,
      entity: PhantomData,
    }
  }

  /// The stored id, BORROWED — the half every id shape can answer.
  #[inline]
  #[must_use]
  pub const fn id_ref(&self) -> &I {
    &self.id
  }

  /// The stored id BY VALUE, where the id is [`Copy`].
  ///
  /// The pair [`Identifiable`](crate::Identifiable) states over an entity, stated here inherently:
  /// one language wherever an id is reached, and the gate on the METHOD so a text-keyed id still
  /// borrows.
  #[inline]
  #[must_use]
  pub const fn id(&self) -> I
  where
    I: Copy,
  {
    *self.id_ref()
  }
}

/// Written rather than derived, because `#[derive(Clone)]` would bound `E: Clone` — and `E` is a
/// marker this struct holds only as `PhantomData<fn() -> E>`, which is [`Clone`] at every `E`. The
/// five impls below are hand-written for the same reason, each stating its bound over `I` alone.
impl<I: Clone, E> Clone for TypedId<I, E> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      id: self.id.clone(),
      entity: PhantomData,
    }
  }
}

impl<I: Copy, E> Copy for TypedId<I, E> {}

/// Two ids are equal when their STORED ids are. The marker takes no part because it holds no value —
/// two `TypedId`s that reach this impl already share one `E`, the type having said so.
impl<I: PartialEq, E> PartialEq for TypedId<I, E> {
  #[inline]
  fn eq(&self, other: &Self) -> bool {
    self.id == other.id
  }
}

impl<I: Eq, E> Eq for TypedId<I, E> {}

/// The same field [`PartialEq`] reads, which is what keeps the two agreeing: a map keyed by an id
/// finds the entry an equal id put there.
impl<I: Hash, E> Hash for TypedId<I, E> {
  #[inline]
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.id.hash(state);
  }
}

/// The stored id under the wrapper's name, and the phantom is not in it: a derive would print the
/// marker field beside the id, where what it marks is already in the TYPE a reader was shown.
impl<I: fmt::Debug, E> fmt::Debug for TypedId<I, E> {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_tuple("TypedId").field(&self.id).finish()
  }
}

/// A typed id is a member exactly when the entity it addresses DECLARES IT BACK: `E`'s own
/// [`Identifiable::Id`](crate::Identifiable::Id) has to be this very wrapper, so at a `Scene`
/// addressed by `TypedId<uuid::Uuid, Scene>` the type `TypedId<String, Scene>` cannot join the
/// vocabulary at all. The tie lives HERE and nowhere else — the forward equation still reads
/// `<Target as Identifiable>::Id` and has learned nothing about the wrapper.
///
/// # Examples
///
/// The wrapper over a member, at an entity that names it:
///
/// ```
/// use ingraph::{Identifiable, TypedId};
///
/// struct Scene {
///   id: TypedId<uuid::Uuid, Scene>,
/// }
///
/// impl Identifiable for Scene {
///   type Id = TypedId<uuid::Uuid, Scene>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<TypedId<uuid::Uuid, Scene>>();
/// ```
///
/// A wrapper carries no id past the seal: an excluded `I` is excluded wrapped, because membership
/// is delegated to the id HELD rather than granted a second time at the wrapper.
///
/// ```compile_fail,E0277
/// use ingraph::{Identifiable, TypedId};
///
/// struct Scene {
///   id: TypedId<Vec<u8>, Scene>,
/// }
///
/// impl Identifiable for Scene {
///   type Id = TypedId<Vec<u8>, Scene>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<TypedId<Vec<u8>, Scene>>();
/// ```
///
/// And the tie itself, which is the refusal the wrapper exists for: `Scene` is addressed by a
/// `uuid::Uuid`, so the same entity under a `String` is no id. `E0271` rather than the `E0277` every
/// other refusal here carries, and MEASURED — the unmet predicate is the projection equality, so the
/// error names what `Scene` declared beside what was written, which is the more useful of the two.
///
/// ```compile_fail,E0271
/// use ingraph::{Identifiable, TypedId};
///
/// struct Scene {
///   id: TypedId<uuid::Uuid, Scene>,
/// }
///
/// impl Identifiable for Scene {
///   type Id = TypedId<uuid::Uuid, Scene>;
///
///   fn id_ref(&self) -> &Self::Id {
///     &self.id
///   }
/// }
///
/// fn admits<I: ingraph::Id>() {}
///
/// admits::<TypedId<String, Scene>>();
/// ```
///
/// # Written as a DELEGATION, which is what it always was
///
/// The row states `Inner = I` and hands back [`id_ref`](TypedId::id_ref), so admission and the seal
/// both arrive through the one blanket the third law is written on. The bound is unchanged and both
/// refusals above still land where they did — the excluded `I` as `E0277` on the delegate's own
/// membership, the mismatched entity as `E0271` on this impl's projection equality.
///
/// SAFETY: the marker is `PhantomData<fn() -> E>`, so it holds no value and reaches no stored byte.
/// A typed id IS the id it holds, at the same equality, order and address; what `E` discriminates is
/// types, and no id duty looks at types.
unsafe impl<I, E> DelegatesId for TypedId<I, E>
where
  I: Id,
  E: Identifiable<Id = TypedId<I, E>>,
{
  type Inner = I;

  #[inline]
  fn delegate(&self) -> &I {
    self.id_ref()
  }
}

#[cfg(test)]
mod tests;