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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! What one slot of a cursor holds, and how it crosses the opaque boundary: [`CursorValue`] — the
//! byte form a value has everywhere, [`DialectCursor`] — the byte form it has at ONE dialect, and
//! [`CursorCodec`], the seat a declaration mounts either of them at.
//!
//! # The codec belongs to the TYPE, which is this crate's rule and not a new one
//!
//! [`BeU64::to_blob`](crate::BeU64::to_blob) and its five siblings are inherent and public *so that
//! a shared name does not acquire two meanings*: every backend's carrier row calls the type's own
//! method rather than writing `to_be_bytes` again, and a `BeU64` column therefore holds the same
//! bytes whichever backend wrote it. A cursor is a third reader of the same values, and it joins on
//! the same terms — the three big-endian rows below delegate to `to_blob`/`from_blob` and encode
//! nothing of their own.
//!
//! What this trait adds is the half a [`Carrier`](crate::Carrier) row has not got. A carrier binds:
//! it is one direction, and the bytes it produces are the ENGINE's rather than this crate's. A
//! cursor needs BOTH directions, and it needs the pair to be one authority, because the string a
//! client hands back has to become the value it was minted from.
//!
//! # A PAGE CURSOR IS SESSION-LIVED STATE, and that is what bounds who has to agree
//!
//! **The portable-token doctrine is retired.** A cursor was once held to be readable by any engine —
//! *the string a client hands back was minted by a process that may have been talking to another
//! dialect* — and that made one byte form per value the only coherent answer. It is not what a page
//! token IS. A cursor is short-lived PAGINATION STATE: a client walks a list, hands back what the
//! last page ended at, and stops. It is not a durable id, nothing stores it, and nothing is expected
//! to still hold one tomorrow. **Switching a deployment's storage engine invalidates the tokens
//! outstanding at that moment**, which is the same class of event as changing an order — a thing the
//! signature already refuses on — and it is survivable for exactly the reason a cursor is not an id.
//!
//! So the agreement a byte form owes is bounded by the ENGINE it was minted at, and
//! [`DialectCursor`] is that boundary written down: a value may have one form at SQLite and another
//! at PostgreSQL, and each engine's page-walk reads its own. What a household actually has — a dense
//! hand-written form per store, which is the common case rather than the exotic one — becomes
//! spellable instead of being flattened into one form that fits none of them.
//!
//! **A token handed to the wrong engine refuses, and nothing new was added to make it refuse.** No
//! dialect tag rides the frame, no envelope wraps it, and the byte count is unchanged. The
//! refusal is the one that was always there: the receiving engine's codec is handed bytes it did not
//! write, and a codec that returns a plausible value for such bytes is the defect this trait's whole
//! contract is about. It answers [`None`], and the caller reports
//! [`CursorError::Value`](crate::CursorError::Value) at the slot's own position — the same sentence a
//! mangled token has always earned. Self-description would buy a *better message* for a case that is
//! already refused, at the cost of bytes in every token and a second vocabulary to keep true.
//!
//! # FAITHFUL, not order-preserving
//!
//! The big-endian storage forms exist because *equal-length big-endian blobs compare bytewise
//! exactly as the numbers do* — an index over such a column is an index over the numeric order.
//! Nothing here needs that. A cursor's values are never compared as bytes: they are BOUND as
//! parameters and compared by the engine, in the column's own type, under the column's own
//! collation. So the only requirement on this encoding is that it round-trips, and `f64` — which
//! has no order-preserving byte form at all — is a member for exactly that reason.
//!
//! # Rows for a value the crate does not ship
//!
//! One impl. A storage type with a [`Carrier`](crate::Carrier) row and no row here can be filtered
//! on and cannot be paged past, which is a compile error at the cursor rather than a page that
//! resumes at the wrong row.
//!
//! [`Score`](crate::Score) and [`Temporal`](crate::Temporal) are deliberately absent. Each is one
//! impl when something asks: nothing does yet, and a row written ahead of its caller is a codec
//! nobody has checked against a real column.
//!
//! **The BSON id pair's caller has arrived.** `#[derive(ingraph::Id)]`'s coverage probe named nine
//! sealed members that store (`IdColumn` ✅) but cannot be wrapped because this trait had no row for
//! them — the six `core::net` addresses, `SmolStr` and the BSON pair — and their rows are below,
//! beside the six addresses'.
//!
//! # A COLLECTION boundary is one slot whose bytes have INNER structure
//!
//! A collection column is an order subject — PostgreSQL's native array ordering is this framework's
//! own pin, [`compare_collections`](crate::query::compare_collections) — so a page can be resumed at
//! one, and the boundary value is the row's whole list. The frame does not change to carry it: the
//! version stays `1` and a slot is still `presence | length | bytes`. What the list adds is INSIDE
//! those bytes, and this trait is what interprets them:
//!
//! ```text
//! count    4 bytes, big-endian     how many elements follow
//! elements                         fixed-width each raw; var-width each length-prefixed (4 bytes BE)
//! ```
//!
//! **No frame-level tag and no version bump**, and that is a ruling rather than an economy. A LIST
//! tag in the frame would duplicate what the order's own term subject already states, minting a
//! refusal that exists only because the second record can disagree with the first; the frame's
//! grammar stays type-free, so a future structured value is *a value whose bytes have inner
//! structure* rather than a new frame word. Self-description buys nothing here either — only the
//! minting server decodes, which the signature check enforces, and every other slot's bytes are
//! already unreadable without the order.
//!
//! A malformed inner frame refuses in the existing per-slot family: [`read_cursor`](CursorValue::read_cursor)
//! answers [`None`] and the decode raises [`CursorError::Value`](crate::CursorError::Value) at the
//! slot's own position. A truncated count, a short element, an element the element's own row refuses
//! and trailing bytes past the last element are all that shape.
//!
//! **There is no size ceiling.** A boundary is a row's own stored value, bounded by what the API
//! already returned to the client that is handing it back — so a fence here would refuse a page over
//! a row the same query served.
//!
//! ## The element WIDTH is never restated
//!
//! A fixed-width element writes its bytes raw, so the payload divides evenly into `count` chunks and
//! each chunk is handed to the ELEMENT's own [`read_cursor`](CursorValue::read_cursor), which checks
//! its own width — a chunking that does not divide, or divides into chunks the element refuses, is a
//! refusal. So the encoding has ONE authority per element type, which is this module's rule and not
//! a new one, and a width written here as a second record could not drift from it because there is
//! none.
//!
//! `Vec<u8>` is the one shape where a reader must be careful, and the two readings are two TYPES: a
//! `Vec<u8>` is a byte column, verbatim, and a collection OF byte strings is `Vec<Vec<u8>>`. That is
//! also why the rows below are a table of element types rather than one blanket impl — `u8` has a
//! row, so `impl<E: CursorValue> CursorValue for Vec<E>` would be `E0119` against the byte column.
//! The table is the same one PostgreSQL's array strategy names, for the reason the next section
//! gives.
//!
//! ## Which element types have a row, and why that list and no other
//!
//! Exactly the elements a collection boundary can BE: the ones PostgreSQL stores in a native array —
//! `PgCollectionStorage`'s array rows — intersected with the ones this trait already encodes. `i8`,
//! `u8`, `u16`, `u32`, [`Score`](crate::Score) and the three big-endian forms reach an EDGE TABLE on
//! PostgreSQL, so a boundary over them is refused one layer out and a codec here would have no
//! caller; `Duration`, `PgInterval` and `time`'s three ride the array and have no row on this trait
//! at all, so a collection of one is the same missing row a SCALAR of it already is.

use smol_bytes::Utf8Bytes;

use super::LENGTH;
use crate::{BeI128, BeU64, BeU128, Count};

/// The bytes one cursor slot's value crosses the opaque boundary as.
///
/// # Why a write rather than a returned buffer
///
/// A cursor holds several values and encodes them into one frame, so a row that appends allocates
/// nothing per slot where one returning a `Vec` allocates per slot and copies. It is
/// [`Backend::write_column`](crate::Backend::write_column)'s arrangement, for its reason.
///
/// # The framing is the CURSOR's, and a row must not add its own
///
/// Each slot is already length-delimited by the frame, so [`read_cursor`](Self::read_cursor) is
/// handed exactly the bytes [`write_cursor`](Self::write_cursor) produced — no more and no fewer. A
/// row for a variable-length value therefore writes the value and nothing else; a row that added a
/// length of its own would be a second frame inside the first.
///
/// # Both directions, or it is a bind helper
///
/// The pair is what makes the encoding an authority rather than a one-way convenience — the
/// standard the blob carriers hold, where [`Decode`](sqlx::Decode) is implemented *because a
/// carrier that can only write is a bind helper rather than a carrier*.
///
/// # The unimplemented note names the COMPOSITE case, because that is the one with two answers
///
/// Every stored column a record does not flatten is an ORDER SUBJECT, and an order subject is a
/// cursor slot — so a missing row here is reported at the declaration that stores the type rather
/// than at a page. For a scalar the repair is the row itself. For a value occupying columns of its
/// own it is a DECISION, and the note states both halves of it: a group of fields has no order until
/// its declaration asserts one, and a holder that wants no such assertion can lay the columns out
/// bare instead, which takes the value out of the order entirely.
#[diagnostic::on_unimplemented(
  message = "`{Self}` is no position in an order: it has no cursor value",
  label = "this column would be a page's boundary",
  note = "a value occupying COLUMNS OF ITS OWN has no order until its declaration asserts one — \
          write `cursor` on the `#[ingraph::fields]` that declares it, which says the fields' \
          declared order is the one legitimate total order over the value",
  note = "…or take the column out of the order: `<db>(flatten)` lays its columns out in \
          the holder's own namespace, and a flattened column is no order subject and therefore no \
          cursor slot",
  note = "a SCALAR that reaches this note is missing its own row — the pair is `write_cursor` and \
          `read_cursor`, and a row that only writes is a bind helper rather than a codec"
)]
pub trait CursorValue: Sized {
  /// Append this value's cursor bytes to `out`.
  fn write_cursor(&self, out: &mut Vec<u8>);

  /// The value `bytes` holds, or [`None`] where they are not this type's encoding.
  ///
  /// A cursor is a string a CLIENT hands back, so the bytes are arbitrary and a row checks its own
  /// width, its own charset and its own domain. Returning a plausible value for bytes this type
  /// did not write is how a forged cursor becomes a page.
  fn read_cursor(bytes: &[u8]) -> Option<Self>;
}

/// A byte form written by a TYPE OTHER THAN THE VALUE'S — the seat a household mounts its own
/// cursor codec at.
///
/// # What it is for, and why the framed default is not enough
///
/// The emission's own row for a declared composite frames each member behind four bytes of length
/// (see [`write_member`]), because *`u32` and `String` are the same tokens to a macro* and a
/// generated read that assumed widths would return a plausible value for bytes the type never wrote.
/// A HOUSEHOLD knows the widths. One that already hand-wrote a dense byte form — eight flat bytes for
/// a rate's two halves, no lengths, no count — had no way to say so, and kept a parallel hand kit
/// beside the declaration to keep it. This trait is that sentence: the declaration names the codec,
/// and the emission's [`CursorValue`] row delegates to it instead of framing.
///
/// A household that writes no such word rides the framed default byte for byte. Nothing here changes
/// what an undecorated declaration emits.
///
/// # ONE implementor, because encode and decode are DUALS
///
/// The seat could have been two function words — an `encode = "…"` beside a `decode = "…"`, the
/// shape the whole-value transform seat takes. It is not, and the reason is that the two halves are
/// not independent: a byte form IS the pair, and a pair that disagrees is a codec that mints tokens
/// nothing reads. Two words let a household name an encoder from one type and a decoder from
/// another, and no check at the declaration could catch it — the signatures would both be right. One
/// implementor makes the mismatch UNREPRESENTABLE, which is the same standard [`CursorValue`] holds
/// its own rows to: *a row that only writes is a bind helper rather than a codec*.
///
/// It is an associated-function pair rather than a method pair because a codec is a TYPE a
/// declaration names and never a value it holds — there is no codec to construct at a cursor's write,
/// and a `&self` would be a parameter with one legal argument.
///
/// # `decode` IS HANDED ATTACKER BYTES
///
/// A page token is a string a CLIENT hands back, and a client may have written it. So `bytes` is
/// arbitrary input and never trusted state, and an implementor CHECKS: its own width, its own
/// charset, its own domain. **Returning a plausible value for bytes this codec did not write is how a
/// forged cursor becomes a page** — the same sentence [`read_cursor`](CursorValue::read_cursor)
/// carries, restated here because this seat is where an application's own code takes the obligation
/// over. For a fixed-width form the whole check is the length: eight flat bytes are eight, and a
/// client's seven or nine are refused rather than zero-extended into a position the order never had.
///
/// The refusal is [`None`] and there is no error type here, which is a ruling rather than an
/// economy. A refused decode joins the road the framed row already takes: the caller turns it into
/// [`CursorError::Value`](crate::CursorError::Value) at the slot's own position, which is the one
/// sentence a mangled token earns. An error face of this trait's own would be a second vocabulary for
/// one refusal, reachable from one seat and not the other.
///
/// # `encode` appends, and the framing is still the CURSOR's
///
/// `out` is the frame's buffer, exactly as [`write_cursor`](CursorValue::write_cursor)'s is, and the
/// slot is already length-delimited around whatever this writes — so a codec writes the value and
/// nothing else, and `decode` is handed exactly the bytes `encode` produced. A length of its own
/// would be a second frame inside the first.
///
/// # The word is `encode`/`decode` at ONE VALUE, where [`Cursor`](crate::Cursor)'s is at the FRAME
///
/// [`Cursor::encode`](crate::Cursor::encode) produces the one base64url string a client ever holds,
/// over every slot at once. This pair is one slot's bytes, before any of that. The two never meet at
/// a call site — one is an inherent method on a cursor, the other an associated function of a codec
/// named at a declaration — and the layer is named here so the shared word is a deliberate pair
/// rather than an accident.
///
/// # No `on_unimplemented` here, because the report belongs to the MOUNT
///
/// A missing row is always reported at the declaration that named the codec, through the witness the
/// expansion mints at that seat — spanned at the string the author wrote, in the seat's own words. A
/// second sentence on the trait would be one that never fires there and could drift from the one that
/// does.
pub trait CursorCodec<T> {
  /// Append `value`'s cursor bytes to `out`.
  fn encode(value: &T, out: &mut Vec<u8>);

  /// The value `bytes` holds, or [`None`] where they are not this codec's encoding.
  ///
  /// The bytes are a CLIENT's. See the trait note: this checks its own width, its own charset and
  /// its own domain, and a plausible value for bytes it did not write is a forged cursor honoured.
  fn decode(bytes: &[u8]) -> Option<T>;
}

/// **WHICH DIALECT** a byte form belongs to — the markers [`DialectCursor`] is keyed on.
///
/// # Markers rather than the drivers' own backend types
///
/// `ToDatabaseComparison<V, Db>` is keyed on `sqlx::Sqlite` and its siblings, because what a
/// comparison RENDERS is the driver's business. A cursor's bytes are not: this module is compiled
/// under no backend's feature at all, for the reason the crate note gives — *a position in a written
/// order names no database* — and keying the seam on a driver type would have made a value's cursor
/// row exist only in builds that compiled that driver in, which is a feature set deciding what a
/// declaration MEANS.
///
/// So the key is a marker this crate owns and always ships. A record's page walk names the marker for
/// the dialect its statement is written in; a declaration names the same marker for the store it
/// mounted a codec at; and neither mention is gated, so a household's refusals read the same in every
/// build.
///
/// They are deliberately NOT called what the drivers call themselves, and the module path is the
/// disambiguation: `dialect::Sqlite` is *which store's bytes*, `sqlx::Sqlite` is *which driver's
/// statement*, and a shared bare name would leave a reader to guess which question is being asked.
pub mod dialect {
  /// SQLite.
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  pub struct Sqlite;

  /// PostgreSQL.
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  pub struct Postgres;

  /// MySQL.
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  pub struct Mysql;

  /// MongoDB.
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  pub struct Mongo;
}

/// The byte form a value has AT ONE DIALECT — what a page-walk on `Db` actually spends.
///
/// `Db` is one of [`dialect`]'s markers rather than a driver's backend type — see that module for
/// why this seam names no driver.
///
/// # Why the dialect is a parameter at all
///
/// Because a page cursor is session-lived state rather than a durable id, and the module note above
/// is the ruling: an engine only ever has to read the tokens it minted, so a value is free to have a
/// dense hand-written form at one store and another at the next. That is the ordinary case in a
/// corpus that stores the same value in several engines, and one form flattened across all of them
/// fits none of them well.
///
/// # A row is FREE for anything with a [`CursorValue`], which is nearly everything
///
/// The blanket below gives every type whose bytes are the same everywhere a row at *every* dialect,
/// delegating straight to [`CursorValue`]. Every scalar this crate ships, every generated vocabulary,
/// every newtype and every fragment that mounts nothing is covered by it and states nothing.
///
/// A type that DOES vary per dialect opts out by having no [`CursorValue`] row at all, and writes one
/// impl of this trait per dialect it serves. The two are mutually exclusive by coherence and that is
/// the design rather than a constraint worked around: a value either has one byte form or it has one
/// per engine, and a type carrying both would leave *which one does a page spend* answered in two
/// places. Measured, not assumed — the blanket and a downstream per-dialect row coexist because a
/// local type's [`CursorValue`] row can only be written by the crate that owns the type, and the
/// same two rows on ONE type are `E0119`.
///
/// # What a MISSING row means, and why it is honest
///
/// A per-dialect type answers only the dialects it named. A record storing such a value in a dialect
/// the value never declared is `E0277` here, at the declaration that stores it — which is this tier's
/// existing sentence about a fragment naming the dialects it is BUILT for, arriving one seat over.
#[diagnostic::on_unimplemented(
  message = "`{Self}` is no position in an order at `{Db}`: it has no cursor bytes there",
  label = "this column would be a page's boundary in that database",
  note = "a value occupying COLUMNS OF ITS OWN has no order until its declaration asserts one — \
          write `cursor` on the `#[ingraph::fields]` that declares it, which says the fields' \
          declared order is the one legitimate total order over the value",
  note = "…or take the column out of the order: `<db>(flatten)` lays its columns out in the \
          holder's own namespace, and a flattened column is no order subject and therefore no \
          cursor slot",
  note = "a value that DID assert one and still reaches this note has bytes of its own per \
          dialect, and answers only the dialects it named — add this one to `record(…)`, bare to \
          ride the framed default there or as `<db>(cursor = \"…\")` to mount a codec",
  note = "a SCALAR that reaches this note is missing its own row — the pair is `write_cursor` and \
          `read_cursor`, and a row that only writes is a bind helper rather than a codec"
)]
pub trait DialectCursor<Db>: Sized {
  /// Append this value's cursor bytes for `Db` to `out`.
  fn write_cursor_at(&self, out: &mut Vec<u8>);

  /// The value `bytes` holds at `Db`, or [`None`] where they are not this dialect's encoding.
  ///
  /// **Bytes minted at another engine reach here**, because a client may hand a token back after a
  /// deployment moved, and they are refused by the ordinary width and domain checks rather than by a
  /// tag: see the module note. There is nothing to add for that case — a codec that answers [`None`]
  /// for bytes it did not write is already the whole contract.
  fn read_cursor_at(bytes: &[u8]) -> Option<Self>;
}

/// **ONE BYTE FORM IS EVERY DIALECT'S BYTE FORM** — the row every ordinary value reaches this trait
/// through.
///
/// It is what keeps the per-dialect seam free at the call site: a record's cursor slot asks for
/// [`DialectCursor`] at its own backend, and an `i64`, a `String`, a generated vocabulary and a
/// fragment that mounted nothing all answer without a word.
impl<Db, T: CursorValue> DialectCursor<Db> for T {
  #[inline]
  fn write_cursor_at(&self, out: &mut Vec<u8>) {
    self.write_cursor(out);
  }

  #[inline]
  fn read_cursor_at(bytes: &[u8]) -> Option<Self> {
    Self::read_cursor(bytes)
  }
}

/// The fixed-width integers, big-endian — the byte order every durable number in this crate takes.
///
/// The width is CHECKED on the way back, which is what `try_into` on a slice buys: a client's four
/// bytes are not an `i64` and are refused rather than zero-extended into a plausible one.
macro_rules! integer_values {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl CursorValue for $ty {
        #[inline]
        fn write_cursor(&self, out: &mut Vec<u8>) {
          out.extend_from_slice(&self.to_be_bytes());
        }

        #[inline]
        fn read_cursor(bytes: &[u8]) -> Option<Self> {
          Some(Self::from_be_bytes(bytes.try_into().ok()?))
        }
      }
    )+
  };
}

integer_values!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);

/// The `NonZero*` family, through their underlying integer's own row — no dialect anywhere in this
/// trait, so all TEN widths get one, where the SQL carrier and read rows stop at eight (see
/// `comparison::sql::carrier` and `column::assemble` for why `i128`/`u128` themselves have no live
/// dialect to round-trip through).
///
/// `.get()` writes the wrapped integer's own bytes and nothing else — the same delegation
/// [`Carrier`](crate::Carrier)'s `NonZero*` row makes, one direction over. Coming back, a decoded `0`
/// is not a new refusal this row invents: it is the SAME *forged cursor* answer [`bool`]'s row above
/// already gives a third byte — `read_cursor` returns [`None`], which the caller already turns into
/// [`CursorError::Value`](crate::CursorError::Value) named at the slot's own position.
macro_rules! nonzero_values {
  ($( $ty:ty => $inner:ty ),+ $(,)?) => {
    $(
      impl CursorValue for $ty {
        #[inline]
        fn write_cursor(&self, out: &mut Vec<u8>) {
          self.get().write_cursor(out);
        }

        #[inline]
        fn read_cursor(bytes: &[u8]) -> Option<Self> {
          Self::new(<$inner as CursorValue>::read_cursor(bytes)?)
        }
      }
    )+
  };
}

nonzero_values! {
  core::num::NonZeroI8 => i8,
  core::num::NonZeroI16 => i16,
  core::num::NonZeroI32 => i32,
  core::num::NonZeroI64 => i64,
  core::num::NonZeroI128 => i128,
  core::num::NonZeroU8 => u8,
  core::num::NonZeroU16 => u16,
  core::num::NonZeroU32 => u32,
  core::num::NonZeroU64 => u64,
  core::num::NonZeroU128 => u128,
}

/// **THE CARDINALITY, THROUGH `u64`'s OWN ROW** — eight bytes big-endian, the whole magnitude, with
/// no dialect anywhere in it.
///
/// The `NonZero*` family's delegation one paragraph up, with the return leg simpler: a `NonZero`
/// re-establishes its invariant coming back and refuses a decoded `0`, and a [`Count`](crate::Count)
/// has none to re-establish — every `u64` is a cardinality, what the newtype states being where a
/// value CAME FROM rather than which values it admits.
///
/// **The bytes are the FULL width and not the stored one**, which is the split the float rows below
/// already name: a cursor is a faithful round trip of the RUST value, and the narrowing into an
/// `i64` is the BIND's — [`Carrier`](crate::Carrier)'s row on SQLite and PostgreSQL — applied to
/// whatever this hands back. A codec that narrowed here too would be the same decision made twice,
/// in two places free to disagree.
impl CursorValue for Count {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    self.get().write_cursor(out);
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    <u64 as CursorValue>::read_cursor(bytes).map(Self::new)
  }
}

/// The floats, through their IEEE 754 bit patterns.
///
/// `to_be_bytes` on a float IS the bit pattern, so the round trip is exact for every value a column
/// can hold — including the signed zeros, whose two encodings a numeric comparison would lose, and
/// every NaN payload. That is faithfulness rather than order: the bytes of a negative float sort
/// ABOVE a positive one, which would be wrong for a storage form and is irrelevant here, since a
/// cursor's value is bound and compared by the engine.
macro_rules! float_values {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl CursorValue for $ty {
        #[inline]
        fn write_cursor(&self, out: &mut Vec<u8>) {
          out.extend_from_slice(&self.to_be_bytes());
        }

        #[inline]
        fn read_cursor(bytes: &[u8]) -> Option<Self> {
          Some(Self::from_be_bytes(bytes.try_into().ok()?))
        }
      }
    )+
  };
}

float_values!(f32, f64);

/// One byte, and only its two legal values — a third byte is a client's, and `true` is not what it
/// means.
impl CursorValue for bool {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.push(u8::from(*self));
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    match bytes {
      [0] => Some(false),
      [1] => Some(true),
      _ => None,
    }
  }
}

/// The three big-endian storage forms, through their OWN codec.
///
/// `to_blob` / `from_blob` rather than the inner integer's bytes, which is the rule the SQL family's
/// `blob_carrier!` follows for the same reason: a second encoding here would agree with the storage
/// form today and be free to stop, and [`BeI128`]'s sign flip is exactly the sort of thing it would
/// stop agreeing about.
macro_rules! blob_values {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl CursorValue for $ty {
        #[inline]
        fn write_cursor(&self, out: &mut Vec<u8>) {
          out.extend_from_slice(&self.to_blob());
        }

        #[inline]
        fn read_cursor(bytes: &[u8]) -> Option<Self> {
          Self::from_blob(bytes)
        }
      }
    )+
  };
}

blob_values!(BeU64, BeU128, BeI128);

/// A uuid's sixteen bytes, in its own canonical order.
///
/// `as_bytes` / `from_slice` rather than the hyphenated rendering: the bytes are half the width and
/// the rendering is for a filesystem segment, which is a different boundary with a different reason.
impl CursorValue for uuid::Uuid {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Self::from_slice(bytes).ok()
  }
}

/// Text, as its UTF-8 bytes — and the validity is CHECKED coming back, because the bytes are a
/// client's.
impl CursorValue for String {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    core::str::from_utf8(bytes).ok().map(str::to_owned)
  }
}

/// The crate's own text type, on [`String`]'s terms — one encoding for both, so a column declared as
/// either pages past the same cursor.
impl CursorValue for Utf8Bytes {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_str().as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Self::try_from(bytes).ok()
  }
}

/// **A COMPILED PATTERN PAGES AS ITS PATTERN TEXT**, on [`String`]'s terms — the same bytes the
/// column holds and the same bytes it sorts by, so a boundary means what the `ORDER BY` above it
/// meant.
///
/// # Coming back is a COMPILE, and the refusal is the honest [`None`]
///
/// A cursor's bytes are a CLIENT's: they were handed out, kept, and handed back, and nothing
/// promises the text inside is still a pattern this build compiles. So the read is `Regex::new` and
/// a failure answers [`None`], which is exactly the contract's own arm for *these bytes are not a
/// value of this type* — the same answer the UTF-8 check one row up gives a client's malformed text.
/// It is never a panic and never a pattern minted around the failure.
///
/// **THE VALUE IT REBUILDS IS NOT USED AS A PATTERN**, which is what makes the cost acceptable: a
/// boundary is bound as a comparison operand and compared as text. The compile is paid to honour the
/// type, and a build that finds it too dear pages by a column whose value is its bytes.
#[cfg(feature = "regex")]
impl CursorValue for regex::Regex {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_str().as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Self::new(core::str::from_utf8(bytes).ok()?).ok()
  }
}

/// A byte column, verbatim. Nothing to check: every byte string is one.
///
/// A collection OF byte strings is `Vec<Vec<u8>>` and reaches the list rows below — the two readings
/// are two types, which is what keeps one blob and one list of blobs from being the same bytes.
impl CursorValue for Vec<u8> {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self);
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Some(bytes.to_vec())
  }
}

/// The inner frame's head: how many elements follow.
///
/// Big-endian in four bytes, which is the slot length prefix's own width one frame in — the same
/// choice for the same reason, every durable number in this crate being big-endian.
///
/// A count that does not fit `u32` saturates, exactly as the slot's own length does. It is
/// unreachable from a real boundary — a row holding four billion elements has not been served to the
/// client that would hand the cursor back — and saturating rather than wrapping is what keeps the
/// unreachable case a REFUSAL on the way in rather than a shorter list that decodes.
fn write_count(count: usize, out: &mut Vec<u8>) {
  out.extend_from_slice(&u32::try_from(count).unwrap_or(u32::MAX).to_be_bytes());
}

/// The count `bytes` opens with, and the elements after it — or [`None`] where the frame ends inside
/// the count.
///
/// The number is a CLIENT's, so it is used to drive a walk over bytes that are already here and
/// never to reserve any: a list that is not there refuses instead of allocating.
fn read_count(bytes: &[u8]) -> Option<(usize, &[u8])> {
  let (count, rest) = bytes.split_at_checked(LENGTH)?;
  let count = u32::from_be_bytes(count.try_into().ok()?);
  Some((usize::try_from(count).ok()?, rest))
}

/// A collection whose elements are FIXED-WIDTH: the count, then each element's bytes raw.
///
/// Coming back, the payload is divided into `count` equal chunks and each is handed to the element's
/// own row — see the module note for why the width is never restated here. A payload that does not
/// divide is trailing bytes or a short element, and both are the same refusal; a chunk that divides
/// but is not the element's width is refused by the element, which is what makes the division safe
/// rather than a guess.
macro_rules! fixed_list_values {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl CursorValue for Vec<$ty> {
        fn write_cursor(&self, out: &mut Vec<u8>) {
          write_count(self.len(), out);
          for element in self {
            element.write_cursor(out);
          }
        }

        fn read_cursor(bytes: &[u8]) -> Option<Self> {
          let (count, rest) = read_count(bytes)?;
          if count == 0 {
            // An EMPTY list is the legal least boundary, so it decodes — and anything after the
            // count is trailing bytes rather than an element the count did not admit.
            return rest.is_empty().then(Self::new);
          }
          // An empty payload under a non-zero count is a short element, and it is tested with the
          // divisibility because `0 % n` is `0`: without it the chunk width below would be zero,
          // which `chunks_exact` panics on rather than refuses.
          if rest.is_empty() || rest.len() % count != 0 {
            return None;
          }
          rest
            .chunks_exact(rest.len() / count)
            .map(<$ty as CursorValue>::read_cursor)
            .collect()
        }
      }
    )+
  };
}

fixed_list_values!(bool, i16, i32, i64, f32, f64);

/// ONE value of several sharing a buffer, behind its own four-byte big-endian length.
///
/// # The framing belongs to the HOLDER, never to the row
///
/// [`CursorValue`]'s contract is that a row is handed exactly the bytes it wrote, so a row for a
/// variable-length value writes the value and nothing else — a length of its own would be a second
/// frame inside the first. Whoever puts SEVERAL values in one buffer is the party that has to
/// delimit them, and this is that party's spelling: the list rows below hold several elements, a
/// generated COMPOSITE holds several columns, and both frame their members the same way rather than
/// each inventing a delimiter.
///
/// Public because a generated composite is written outside this crate. A downstream type holding
/// several values reaches the same pair, and a hand-written one may too.
///
/// # Fixed-width members pay four bytes each, and that is the price of being TOTAL
///
/// A composite whose members are all fixed-width could divide its payload by their widths instead —
/// which is what the framework's own instant does. An EMISSION cannot: `u32` and `String` are the
/// same tokens to a macro, so a generated row that assumed fixed widths would read a plausible value
/// out of bytes the type never wrote, and *returning a plausible value for bytes this type did not
/// write is how a forged cursor becomes a page*. Four bytes a member buys a read that refuses.
pub fn write_member<T: CursorValue>(value: &T, out: &mut Vec<u8>) {
  // The length is written after the bytes are, for the reason the slot's is: a row appends and only
  // the buffer knows how much it appended.
  let at = out.len();
  out.extend_from_slice(&[0; LENGTH]);
  value.write_cursor(out);
  let length = u32::try_from(out.len() - at - LENGTH).unwrap_or(u32::MAX);
  out[at..at + LENGTH].copy_from_slice(&length.to_be_bytes());
}

/// The next member out of `rest`, advancing it past the bytes that member owned — or [`None`] where
/// the frame ends inside the length, inside the payload, or inside the member's own reading.
///
/// The `&mut &[u8]` is what makes a walk over several members a straight line: each call takes what
/// it owns and leaves the tail, so a caller reads its members in order and then asks whether
/// anything is left. Bytes left over are bytes no member owns, which is a frame this type did not
/// write.
pub fn read_member<T: CursorValue>(rest: &mut &[u8]) -> Option<T> {
  let (length, tail) = rest.split_at_checked(LENGTH)?;
  let length = usize::try_from(u32::from_be_bytes(length.try_into().ok()?)).ok()?;
  let (member, tail) = tail.split_at_checked(length)?;
  let read = T::read_cursor(member)?;
  *rest = tail;
  Some(read)
}

/// A collection whose elements are VARIABLE-WIDTH: the count, then each element behind its own
/// four-byte big-endian length.
///
/// The per-element framing is [`write_member`]'s and [`read_member`]'s — one authority for *several
/// values in one buffer*, shared with every generated composite, so a change to the delimiter moves
/// both at once.
macro_rules! varying_list_values {
  ($( $ty:ty ),+ $(,)?) => {
    $(
      impl CursorValue for Vec<$ty> {
        fn write_cursor(&self, out: &mut Vec<u8>) {
          write_count(self.len(), out);
          for element in self {
            write_member(element, out);
          }
        }

        fn read_cursor(bytes: &[u8]) -> Option<Self> {
          let (count, mut rest) = read_count(bytes)?;
          let mut elements = Self::new();
          for _ in 0..count {
            elements.push(read_member::<$ty>(&mut rest)?);
          }
          // Everything the count claimed has been read, so anything left is bytes no element owns.
          rest.is_empty().then_some(elements)
        }
      }
    )+
  };
}

varying_list_values!(String, Vec<u8>);

/// **A CONFIDENCE PAGES AS THE WIDTH IT MEASURES IN**, and the read RE-VALIDATES.
///
/// The width's own row writes the bytes — the two IEEE carriers through their bit patterns — and a
/// confidence inherits the encoding rather than restating it: the two are one number, and a second
/// spelling here is a second thing to keep in agreement. The interval is checked coming back for
/// [`NormCoord`](crate::NormCoord)'s reason at its own cursor: a cursor is a string a CLIENT hands
/// back, so a forged one must not become a value the type says cannot exist.
///
/// # It is a row written WITH its caller, which is what this module's note asks
///
/// The list of deliberate absences above names `Score` — *a row written ahead of its caller is a
/// codec nobody has checked against a real column*. **The caller has arrived.**
/// [`Detection`](crate::Detection) holds a confidence in a column a declaration can name, and every
/// stored column a record does not flatten is an ORDER SUBJECT. Without this row that declaration is
/// `E0277` at the field, which is the compile error a page resuming at the wrong row would otherwise
/// have become.
///
/// The bound is the membership rule spelled as a bound, exactly as this type's width, carrier,
/// admission and decode rows spell theirs: a confidence pages wherever the width it measures in
/// does. `half::f16` and `rust_decimal::Decimal` have no row on this trait, so those two widths
/// have none here either — which is the bound saying so rather than a second table.
impl<S: crate::ConfidenceCarrier + CursorValue> CursorValue for crate::Confidence<S> {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    CursorValue::write_cursor(&self.get(), out);
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    <S as CursorValue>::read_cursor(bytes).and_then(Self::new)
  }
}

/// **The framework's own instant: twelve bytes, both of its columns, and the pair CHECKED on the
/// way back.**
///
/// The first row here whose value spans more than one column, and the caller that asks for it is
/// the storability audit — a record storing a `Timestamp` cannot be paged past without it, which is
/// the compile error this row answers rather than a page that resumes at the wrong row. It is
/// therefore a row written WITH its caller, which is the standard the module note holds `Score` and
/// `Temporal` to while they wait for theirs.
///
/// FIXED WIDTH — eight big-endian bytes of seconds and four of nanoseconds — so a client's eleven
/// are refused rather than zero-extended into a plausible instant. That is the discipline the
/// integer rows above follow, applied to a value of two of them, and it is the derive corpus's own
/// composite row read one type over.
///
/// The recomposition is [`from_parts`](crate::Timestamp::from_parts)'s, which makes this row the
/// THIRD caller of one authority — the SQL decode and the MongoDB read are the other two — and the
/// reason it matters here is the trait's own: *returning a plausible value for bytes this type did
/// not write is how a forged cursor becomes a page*. A pair jiff would have normalised is exactly
/// such a value, so it is refused here as it is refused there.
impl CursorValue for crate::Timestamp {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(&self.as_second().to_be_bytes());
    out.extend_from_slice(&self.subsec_nanosecond().to_be_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (second, nanosecond) = bytes.split_at_checked(size_of::<i64>())?;
    Self::from_parts(
      i64::from_be_bytes(second.try_into().ok()?),
      i32::from_be_bytes(nanosecond.try_into().ok()?),
    )
    .ok()
  }
}

/// **THE SECOND GATE'S ROSTER, PART ONE: THE SIX `core::net` ADDRESSES.**
///
/// Every row below is MEASURED against std's own `Ord`, read off
/// `library/core/src/net/{ip_addr,socket_addr}.rs` in the toolchain this crate builds with, rather
/// than assumed from the type's shape — the law the per-member table this section answers to states:
/// **encoded-byte comparison == the type's own `Ord`**, the same three-way equality
/// [`uuid::Uuid`]'s row already lives by. A cursor's own contract asks only for a faithful round
/// trip (see the module note), so this is a STRONGER promise made deliberately for the id
/// vocabulary's sake — an id inner's cursor bytes should walk the same order its column does — and
/// this module's own `tests` submodule is where the promise is checked over many values rather than
/// a handful.
///
/// # `Ipv4Addr` and `Ipv6Addr`: the octets, as-is
///
/// `Ipv4Addr::cmp` is `self.octets.cmp(&other.octets)` — a `[u8; 4]` compared elementwise — so the
/// four octets, written raw, ARE the order.
///
/// `Ipv6Addr::cmp` is `self.segments().cmp(&other.segments())` — eight `u16` groups, compared
/// NUMERICALLY — but `segments()` is documented to hold each group `u16::from_be`, i.e. two
/// big-endian octets per group: comparing eight big-endian pairs group-by-group is the same total
/// order as comparing all sixteen octets byte-by-byte, since within a tied pair the numeric
/// comparison IS the lexicographic one. So the sixteen octets, written raw, are this order too — a
/// second encoding here would be free to disagree with `segments()`'s reading of the same bytes,
/// where writing the octets directly cannot.
impl CursorValue for core::net::Ipv4Addr {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(&self.octets());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Some(Self::from(<[u8; 4]>::try_from(bytes).ok()?))
  }
}

impl CursorValue for core::net::Ipv6Addr {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(&self.octets());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Some(Self::from(<[u8; 16]>::try_from(bytes).ok()?))
  }
}

/// `IpAddr`: one discriminant byte, then the inner's own cursor bytes.
///
/// `#[derive(Ord)]` on this enum ranks by VARIANT DECLARATION ORDER before payload — `V4` is
/// declared first in `core::net::IpAddr`, so every `V4` sorts below every `V6` regardless of the
/// address inside either. A leading `0`/`1` tag reproduces exactly that: two encoded values first
/// differ at byte zero whenever their variants differ, which decides the comparison before either
/// inner's bytes are ever reached, and a shared variant reduces to the inner rows above — which are
/// already this order.
///
/// The two variants encode to DIFFERENT LENGTHS (five bytes and seventeen) and that is harmless
/// here where it would be a trap for a fixed-width column: a cursor slot is its own frame, holding
/// exactly what this row wrote, and byte-lexicographic comparison decides at the first differing
/// byte — the tag — well before length could matter. `IdColumn`'s admission matrix names the
/// FIXED-width form as the one a variable-width `BinData` column needs, for a comparison that
/// decides by LENGTH first; this trait's comparison is never that one (see the module's "faithful,
/// not order-preserving" note), so the naked variable-width form is the right one here and not the
/// trap.
impl CursorValue for core::net::IpAddr {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::V4(inner) => {
        out.push(0);
        inner.write_cursor(out);
      }
      Self::V6(inner) => {
        out.push(1);
        inner.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (&tag, rest) = bytes.split_first()?;
    match tag {
      0 => core::net::Ipv4Addr::read_cursor(rest).map(Self::V4),
      1 => core::net::Ipv6Addr::read_cursor(rest).map(Self::V6),
      _ => None,
    }
  }
}

/// `SocketAddrV4`: the address, then the port big-endian.
///
/// MEASURED at `core::net::SocketAddrV4`'s own declaration: `#[derive(Ord)]` over
/// `{ ip: Ipv4Addr, port: u16 }`, in FIELD DECLARATION ORDER — address before port, exactly the
/// order this row writes them in. The port is big-endian for the reason every integer in this file
/// is: two's-complement/unsigned bytewise order over an unsigned width is its numeric order, so a
/// port comparison inside a tied address is decided the same way `u16`'s own row decides it.
impl CursorValue for core::net::SocketAddrV4 {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    self.ip().write_cursor(out);
    out.extend_from_slice(&self.port().to_be_bytes());
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (ip, port) = bytes.split_at_checked(4)?;
    let ip = core::net::Ipv4Addr::read_cursor(ip)?;
    let port = u16::from_be_bytes(port.try_into().ok()?);
    Some(Self::new(ip, port))
  }
}

/// `SocketAddrV6`: the address, the port, the flow label and the scope id — in that order, all four
/// big-endian.
///
/// MEASURED at `core::net::SocketAddrV6`'s own declaration: `#[derive(Ord)]` over
/// `{ ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32 }`, in FIELD DECLARATION ORDER — the
/// trap this row does NOT fall into is stopping at the address and port a caller might expect from
/// the type's own `Display`: `flowinfo` and `scope_id` both participate in std's `Eq`, `Hash` and
/// `Ord`, so two values Rust calls unequal would share one cursor position if either were dropped
/// here.
impl CursorValue for core::net::SocketAddrV6 {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    self.ip().write_cursor(out);
    out.extend_from_slice(&self.port().to_be_bytes());
    out.extend_from_slice(&self.flowinfo().to_be_bytes());
    out.extend_from_slice(&self.scope_id().to_be_bytes());
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (ip, rest) = bytes.split_at_checked(16)?;
    let ip = core::net::Ipv6Addr::read_cursor(ip)?;
    let (port, rest) = rest.split_at_checked(2)?;
    let port = u16::from_be_bytes(port.try_into().ok()?);
    let (flowinfo, scope_id) = rest.split_at_checked(4)?;
    let flowinfo = u32::from_be_bytes(flowinfo.try_into().ok()?);
    let scope_id = u32::from_be_bytes(scope_id.try_into().ok()?);
    Some(Self::new(ip, port, flowinfo, scope_id))
  }
}

/// `SocketAddr`: one discriminant byte, then the inner's own cursor bytes — [`IpAddr`](core::net::IpAddr)'s
/// row, one type over.
///
/// MEASURED the same way: `core::net::SocketAddr` derives `Ord` over `V4` declared before `V6`, so
/// a leading tag reproduces discriminant-first ranking for the same reason it does at `IpAddr`, and
/// the variable total length between the two variants (six bytes against twenty-six) is harmless
/// for the same reason: the tag is byte zero, and byte-lexicographic comparison decides there
/// whenever the variants differ.
impl CursorValue for core::net::SocketAddr {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    match self {
      Self::V4(inner) => {
        out.push(0);
        inner.write_cursor(out);
      }
      Self::V6(inner) => {
        out.push(1);
        inner.write_cursor(out);
      }
    }
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let (&tag, rest) = bytes.split_first()?;
    match tag {
      0 => core::net::SocketAddrV4::read_cursor(rest).map(Self::V4),
      1 => core::net::SocketAddrV6::read_cursor(rest).map(Self::V6),
      _ => None,
    }
  }
}

/// **THE SECOND GATE'S ROSTER, PART TWO: THE COMPACT TEXT MEMBER.**
///
/// [`String`]'s row, on [`SmolStr`](smol_str::SmolStr)'s own terms — raw UTF-8, the same framing,
/// re-checked coming back for the reason every text row in this file re-checks it: the bytes are a
/// client's. This is not a new encoding invented for the type; it is the one row this trait already
/// has for text, read through `SmolStr`'s own `as_str`/`From<&str>` pair instead of `String`'s
/// `as_bytes`/`to_owned` — the same bytes either way, which is what lets a column declared as either
/// text member page past one cursor (see [`Utf8Bytes`](smol_bytes::Utf8Bytes)'s row above, which
/// makes the identical argument for the crate's own text type).
#[cfg(feature = "smol_str")]
impl CursorValue for smol_str::SmolStr {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_str().as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    core::str::from_utf8(bytes).ok().map(Self::from)
  }
}

/// **THE SECOND GATE'S ROSTER, PART THREE: THE BSON PAIR.**
///
/// `bson::Uuid` is `#[derive(Ord)]` over one field — a `uuid::Uuid` — so its whole order is that
/// type's, and [`uuid::Uuid`]'s own row above is exactly this encoding: the sixteen bytes, raw.
/// Mirrored rather than re-derived, so a `bson::Uuid` id and a `uuid::Uuid` id page past
/// byte-identical cursors.
#[cfg(feature = "mongo")]
impl CursorValue for bson::Uuid {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(&self.bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Some(Self::from_bytes(bytes.try_into().ok()?))
  }
}

/// `bson::oid::ObjectId` is `#[derive(Ord)]` over one field — a bare `[u8; 12]` — so its order is
/// that array's own elementwise comparison: the twelve bytes, raw, are the whole of it.
#[cfg(feature = "mongo")]
impl CursorValue for bson::oid::ObjectId {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(&self.bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Some(Self::from_bytes(bytes.try_into().ok()?))
  }
}

#[cfg(test)]
mod tests;