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
//! What each shipped row encodes, and what it refuses.
//!
//! The requirement is FAITHFULNESS and nothing else — a cursor's value is bound as a parameter and
//! compared by the engine, never compared as bytes — so the assertions are round trips over the
//! extremes of each type rather than over an ordering. The floats are where that difference is
//! visible: `-0.0` and `0.0` have two encodings here and one numeric value, which is exactly right
//! for a codec and would be wrong for a storage form.

use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};

use smol_bytes::Utf8Bytes;

use super::CursorValue;
use crate::{BeI128, BeU64, BeU128};

/// `value` through both directions of its own row.
fn round_trip<V: CursorValue + PartialEq + core::fmt::Debug>(value: V) -> Vec<u8> {
  let mut bytes = Vec::new();
  value.write_cursor(&mut bytes);
  assert_eq!(V::read_cursor(&bytes).as_ref(), Some(&value));
  bytes
}

/// The integers, at both ends of their range and at the zero between them, in big-endian — the byte
/// order every durable number in this crate takes.
#[test]
fn the_integers_round_trip_big_endian() {
  assert_eq!(round_trip(0i8), [0]);
  assert_eq!(round_trip(i8::MIN), [0x80]);
  assert_eq!(round_trip(-1i64), [0xff; 8]);
  assert_eq!(round_trip(1i64), [0, 0, 0, 0, 0, 0, 0, 1]);
  assert_eq!(round_trip(u64::MAX), [0xff; 8]);
  assert_eq!(round_trip(u128::MAX), [0xff; 16]);
  assert_eq!(round_trip(i128::MIN).len(), 16);
  assert_eq!(round_trip(u16::MAX), [0xff, 0xff]);
  assert_eq!(round_trip(0u32), [0, 0, 0, 0]);
  assert_eq!(round_trip(i16::MAX), [0x7f, 0xff]);
  assert_eq!(round_trip(u8::MAX), [0xff]);
  assert_eq!(round_trip(i32::MIN), [0x80, 0, 0, 0]);
}

/// A width that is not the type's is REFUSED rather than zero-extended into a plausible value — the
/// bytes are a client's, and four of them are not an `i64`.
#[test]
fn an_integer_of_the_wrong_width_is_refused() {
  assert_eq!(<i64 as CursorValue>::read_cursor(&[0; 4]), None);
  assert_eq!(<i64 as CursorValue>::read_cursor(&[0; 9]), None);
  assert_eq!(<u8 as CursorValue>::read_cursor(&[]), None);
}

/// The floats round-trip EXACTLY, which is faithfulness rather than order: the two zeros keep their
/// two encodings, and a NaN keeps its payload.
#[test]
fn the_floats_round_trip_bit_for_bit() {
  assert_eq!(round_trip(1.5f64), 1.5f64.to_be_bytes());
  assert_ne!(round_trip(0.0f64), round_trip(-0.0f64));
  assert_eq!(round_trip(f32::MAX), f32::MAX.to_be_bytes());

  let mut bytes = Vec::new();
  f64::NAN.write_cursor(&mut bytes);
  let read = <f64 as CursorValue>::read_cursor(&bytes).expect("a NaN's bytes are eight");
  assert!(read.is_nan());
  assert_eq!(read.to_bits(), f64::NAN.to_bits());
}

/// A boolean is one byte and exactly two of its values. A third byte is a client's and `true` is
/// not what it means.
#[test]
fn a_boolean_is_one_byte_and_two_values() {
  assert_eq!(round_trip(true), [1]);
  assert_eq!(round_trip(false), [0]);
  assert_eq!(<bool as CursorValue>::read_cursor(&[2]), None);
  assert_eq!(<bool as CursorValue>::read_cursor(&[0, 0]), None);
  assert_eq!(<bool as CursorValue>::read_cursor(&[]), None);
}

/// The three big-endian storage forms reach their OWN codec, so a cursor and a column hold the same
/// bytes. [`BeI128`]'s sign flip is the witness: a row here that wrote the inner integer's bytes
/// would disagree with the column for every negative value.
#[test]
fn the_storage_forms_use_their_own_codec() {
  assert_eq!(round_trip(BeU64(1)), BeU64(1).to_blob());
  assert_eq!(round_trip(BeU128(1)), BeU128(1).to_blob());
  assert_eq!(round_trip(BeI128(-1)), BeI128(-1).to_blob());

  assert_ne!(
    BeI128(-1).to_blob(),
    (-1i128).to_be_bytes(),
    "the sign flip is what a second encoding here would lose"
  );
  assert_eq!(<BeU64 as CursorValue>::read_cursor(&[0; 7]), None);
}

/// A uuid is its sixteen bytes in its own canonical order, and a shorter string is refused.
#[test]
fn a_uuid_is_its_sixteen_bytes() {
  let id = uuid::Uuid::from_bytes([
    0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
  ]);

  assert_eq!(round_trip(id), *id.as_bytes());
  assert_eq!(<uuid::Uuid as CursorValue>::read_cursor(&[0; 15]), None);
}

/// Text is its UTF-8 bytes, and the validity is CHECKED coming back — the bytes are a client's, and
/// a lone continuation byte is not a `String`.
#[test]
fn text_round_trips_and_invalid_utf8_is_refused() {
  assert_eq!(round_trip("médià".to_owned()), "médià".as_bytes());
  assert_eq!(round_trip(String::new()), [] as [u8; 0]);
  assert_eq!(<String as CursorValue>::read_cursor(&[0x80]), None);

  assert_eq!(round_trip(Utf8Bytes::from("médià")), "médià".as_bytes());
  assert_eq!(<Utf8Bytes as CursorValue>::read_cursor(&[0x80]), None);
}

/// The crate's own text type and [`String`] encode ALIKE, so a column declared as either pages past
/// the same cursor.
#[test]
fn the_two_text_types_are_one_encoding() {
  let mut owned = Vec::new();
  "a red car".to_owned().write_cursor(&mut owned);
  let mut shared = Vec::new();
  Utf8Bytes::from("a red car").write_cursor(&mut shared);

  assert_eq!(owned, shared);
}

/// **THE ORDER IS `String`'s, NOT ASCII AND NOT CODEPOINT** — a page walks the CURSOR BYTES, so what
/// this pins is that sorting a set of `Utf8Bytes` by ITS cursor bytes reproduces the same order
/// sorting the equivalent `String`s by THEIRS does, at values chosen to catch a divergence a plain
/// ASCII sample would hide: a byte that sorts before `a`, a multi-byte UTF-8 sequence, and a prefix
/// relationship (`"café"` is a prefix of `"cafétéria"` in bytes, which is not true of either string's
/// CHAR count once the accent is counted).
#[test]
fn the_two_text_types_agree_on_order_not_only_on_one_encoding() {
  let words = ["", "\0", "a", "cafe", "café", "cafétéria", "café ", "zoo"];

  let mut by_string: Vec<&str> = words.to_vec();
  by_string.sort_by(|a, b| round_trip(String::from(*a)).cmp(&round_trip(String::from(*b))));

  let mut by_utf8bytes: Vec<&str> = words.to_vec();
  by_utf8bytes
    .sort_by(|a, b| round_trip(Utf8Bytes::from(*a)).cmp(&round_trip(Utf8Bytes::from(*b))));

  assert_eq!(
    by_string, by_utf8bytes,
    "a page cursor built over either type must walk the same sequence"
  );
  // And that shared order is `str`'s own `Ord`, which is what a caller sorting by EITHER type
  // actually means to ask for.
  let mut by_str_ord = words.to_vec();
  by_str_ord.sort_unstable();
  assert_eq!(by_string, by_str_ord);
}

/// A byte column is verbatim, with nothing to check — every byte string is one, including the empty
/// one.
#[test]
fn a_byte_column_is_verbatim() {
  assert_eq!(round_trip(vec![0u8, 0xff, 0x80]), [0, 0xff, 0x80]);
  assert_eq!(round_trip(Vec::<u8>::new()), [] as [u8; 0]);
}

/// A FIXED-width collection is the count and then the elements RAW — nothing between them, because
/// the width is the element's own and needs no second record.
#[test]
fn a_fixed_width_collection_is_the_count_and_the_elements_raw() {
  assert_eq!(
    round_trip(vec![1i32, -1]),
    [0, 0, 0, 2, 0, 0, 0, 1, 0xff, 0xff, 0xff, 0xff]
  );
  assert_eq!(round_trip(vec![true, false]), [0, 0, 0, 2, 1, 0]);
  assert_eq!(round_trip(vec![i16::MIN]), [0, 0, 0, 1, 0x80, 0]);
  assert_eq!(round_trip(vec![1.5f64]), {
    let mut expected = vec![0, 0, 0, 1];
    expected.extend_from_slice(&1.5f64.to_be_bytes());
    expected
  });
}

/// A VARIABLE-width collection length-prefixes each element, and the prefix is the LIST's rather
/// than the element row's — a `String` still writes its bytes and nothing else.
#[test]
fn a_variable_width_collection_length_prefixes_each_element() {
  assert_eq!(
    round_trip(vec!["hd".to_owned(), String::new()]),
    [0, 0, 0, 2, 0, 0, 0, 2, b'h', b'd', 0, 0, 0, 0]
  );
  assert_eq!(
    round_trip(vec![vec![0xffu8], Vec::new(), vec![1, 2]]),
    [0, 0, 0, 3, 0, 0, 0, 1, 0xff, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2]
  );
}

/// The EMPTY collection is the legal least boundary — a collection has no null state, so its slot is
/// always PRESENT and the empty list is a value rather than an absence.
///
/// Four bytes of zero and nothing else, in both families.
#[test]
fn the_empty_collection_is_a_value_and_not_an_absence() {
  assert_eq!(round_trip(Vec::<i64>::new()), [0, 0, 0, 0]);
  assert_eq!(round_trip(Vec::<String>::new()), [0, 0, 0, 0]);
  assert_eq!(round_trip(Vec::<Vec<u8>>::new()), [0, 0, 0, 0]);
}

/// A collection of BYTE STRINGS and a byte column are two types and two encodings — which is the
/// whole of why the list rows are a table rather than a blanket impl.
#[test]
fn a_list_of_byte_strings_is_not_a_byte_column() {
  let mut column = Vec::new();
  vec![1u8, 2].write_cursor(&mut column);
  let mut list = Vec::new();
  vec![vec![1u8, 2]].write_cursor(&mut list);

  assert_eq!(column, [1, 2]);
  assert_ne!(column, list);
}

/// **The inner frame is CHECKED, and each refusal is the count disagreeing with the bytes.**
///
/// A cursor is a string a client had, so the count is a client's number: it drives a walk over bytes
/// that are already here and never reserves any. Dropping it, overstating it, understating it or
/// truncating the payload are four ways to be handed a frame that is not one, and every one of them
/// is [`None`] — which the decode raises as `CursorError::Value` at the slot's own position.
///
/// The mutation this pins: dropping the count from `write_cursor`, or writing a wrong one, makes the
/// round trip above disagree and lands here as an accepted forgery.
#[test]
fn a_malformed_inner_frame_is_refused() {
  type Fixed = Vec<i32>;
  type Varying = Vec<String>;

  // The count itself is not there.
  assert_eq!(<Fixed as CursorValue>::read_cursor(&[]), None);
  assert_eq!(<Fixed as CursorValue>::read_cursor(&[0, 0, 0]), None);
  assert_eq!(<Varying as CursorValue>::read_cursor(&[0, 0]), None);

  // The count is larger than the payload holds.
  assert_eq!(<Fixed as CursorValue>::read_cursor(&[0, 0, 0, 1]), None);
  assert_eq!(
    <Fixed as CursorValue>::read_cursor(&[0, 0, 0, 2, 0, 0, 0, 1, 0, 0]),
    None,
    "six payload bytes are not two `i32`s"
  );
  assert_eq!(
    <Varying as CursorValue>::read_cursor(&[0, 0, 0, 1]),
    None,
    "a claimed element has not even a length"
  );
  assert_eq!(
    <Varying as CursorValue>::read_cursor(&[0, 0, 0, 1, 0, 0, 0, 4, b'h', b'd']),
    None,
    "and a length longer than the bytes behind it is the same refusal"
  );

  // The count is smaller than the payload holds, which is trailing bytes.
  assert_eq!(
    <Fixed as CursorValue>::read_cursor(&[0, 0, 0, 0, 1]),
    None,
    "an empty list owns no bytes at all"
  );
  assert_eq!(
    <Varying as CursorValue>::read_cursor(&[0, 0, 0, 0, 0, 0, 0, 1, b'h']),
    None
  );
  assert_eq!(
    <Varying as CursorValue>::read_cursor(&[0, 0, 0, 1, 0, 0, 0, 1, b'h', b'd']),
    None,
    "one element read, one byte nobody owns"
  );

  // A chunk that divides but is not the element's width is the ELEMENT's refusal, which is what
  // makes the equal division safe rather than a guess.
  assert_eq!(
    <Fixed as CursorValue>::read_cursor(&[0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0]),
    None,
    "four chunks of three bytes are not four `i32`s"
  );
  assert_eq!(
    <Vec<bool> as CursorValue>::read_cursor(&[0, 0, 0, 2, 1, 2]),
    None,
    "and a byte that is not a boolean is refused inside a list exactly as it is alone"
  );
  assert_eq!(
    <Varying as CursorValue>::read_cursor(&[0, 0, 0, 1, 0, 0, 0, 1, 0x80]),
    None,
    "an element's own domain check still runs — a lone continuation byte is no `String`"
  );
}

/// **The framework's own instant: twelve bytes, and the pair checked on the way back.**
///
/// A round trip over the extremes, exactly as the integer rows above take one — and one byte fewer
/// is refused rather than zero-extended, because the bytes are a client's.
#[test]
fn an_instant_round_trips_as_its_two_columns() {
  use crate::Timestamp;

  let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
  let before: Timestamp = "1969-12-31T23:59:58.5Z".parse().unwrap();

  assert_eq!(round_trip(at).len(), 12);
  assert_eq!(round_trip(before).len(), 12);
  assert_eq!(round_trip(Timestamp::MIN).len(), 12);
  assert_eq!(round_trip(Timestamp::MAX).len(), 12);
  assert_eq!(round_trip(Timestamp::UNIX_EPOCH), [0; 12]);

  // Eight big-endian bytes of seconds and then four of nanoseconds — the order the two columns are
  // in, so a frame written by one process reads back in another.
  let mut expected = at.as_second().to_be_bytes().to_vec();
  expected.extend_from_slice(&at.subsec_nanosecond().to_be_bytes());
  assert_eq!(round_trip(at), expected);
}

/// **A FORGED cursor is refused rather than turned into a page.** Eleven bytes are not an instant,
/// and neither is a well-formed twelve carrying a pair this encoding never writes — which is the
/// same check the SQL decode and the MongoDB read make, reached here through the third caller.
#[test]
fn a_forged_instant_cursor_is_refused() {
  use crate::Timestamp;

  assert!(<Timestamp as CursorValue>::read_cursor(&[0; 11]).is_none());
  assert!(<Timestamp as CursorValue>::read_cursor(&[0; 13]).is_none());

  // Twelve bytes, both halves legal integers, and a pair jiff would have RESOLVED: `(2, -999999999)`.
  let mut forged = 2i64.to_be_bytes().to_vec();
  forged.extend_from_slice(&(-999_999_999i32).to_be_bytes());
  assert_eq!(forged.len(), 12);
  assert!(<Timestamp as CursorValue>::read_cursor(&forged).is_none());

  // While the spelling this encoding DOES write is admitted, so the refusal is about the pair.
  let mut written = 1i64.to_be_bytes().to_vec();
  written.extend_from_slice(&1i32.to_be_bytes());
  assert_eq!(
    <Timestamp as CursorValue>::read_cursor(&written),
    Some("1970-01-01T00:00:01.000000001Z".parse().unwrap())
  );
}

/// **The twelve bytes ARE the two ordinary scalar slots' bytes** — the reconciliation between the
/// value this row writes and the `(secs, nanos)` sequence the composite ordering compares.
///
/// The two readings of a composite term met here, and they turned out to be ONE encoding at two
/// granularities: an `i64` slot's eight big-endian bytes followed by an `i32` slot's four are
/// byte-for-byte what this row produces. What differs is only where the cursor FRAME puts its
/// length delimiters — once around the pair, because the term is one subject and the cursor holds
/// one slot per term.
///
/// So nothing had to be chosen between them. The order's fixed-width sequence is the term's
/// COLUMNS, the cursor's slot is the term's VALUE, and this is the pin that says the bytes agree.
#[test]
fn an_instants_twelve_bytes_are_its_two_scalar_slots() {
  use crate::Timestamp;

  for instant in [
    "2026-08-09T21:14:03.123456789Z"
      .parse::<Timestamp>()
      .unwrap(),
    "1969-12-31T23:59:58.5Z".parse().unwrap(),
    Timestamp::UNIX_EPOCH,
    Timestamp::MIN,
    Timestamp::MAX,
  ] {
    let mut whole = Vec::new();
    instant.write_cursor(&mut whole);

    let mut halves = Vec::new();
    instant.as_second().write_cursor(&mut halves);
    instant.subsec_nanosecond().write_cursor(&mut halves);

    assert_eq!(whole, halves, "{instant}");
    assert_eq!(whole.len(), size_of::<i64>() + size_of::<i32>());
  }
}

// =====================================================================================================
// THE SECOND GATE'S ROSTER — the six `core::net` addresses, `SmolStr` and the BSON pair. Hand-picked
// extremes and refusals first, then the seeded property that stands behind every one of them: encoded
// bytes compare exactly as the type's own `Ord` does.
// =====================================================================================================

/// The four octets, raw — including a pair that would trip an ASCII-text sort (`10.*` against
/// `9.*`), which is exactly the byte form and not a rendering.
#[test]
fn an_ipv4_address_is_its_four_octets() {
  assert_eq!(round_trip(Ipv4Addr::new(10, 0, 0, 1)), [10, 0, 0, 1]);
  assert_eq!(round_trip(Ipv4Addr::UNSPECIFIED), [0, 0, 0, 0]);
  assert_eq!(round_trip(Ipv4Addr::BROADCAST), [0xff, 0xff, 0xff, 0xff]);
  assert!(Ipv4Addr::new(9, 255, 255, 255) < Ipv4Addr::new(10, 0, 0, 0));
  assert_eq!(<Ipv4Addr as CursorValue>::read_cursor(&[0; 3]), None);
  assert_eq!(<Ipv4Addr as CursorValue>::read_cursor(&[0; 5]), None);
}

/// The sixteen octets, raw — `Ipv6Addr::cmp` compares `segments()` (eight big-endian `u16`s)
/// rather than the octets directly, and this pins that the two readings of the same bytes agree.
#[test]
fn an_ipv6_address_is_its_sixteen_octets() {
  let addr: Ipv6Addr = "2001:db8::1".parse().unwrap();
  assert_eq!(round_trip(addr), addr.octets());
  assert_eq!(round_trip(Ipv6Addr::UNSPECIFIED), [0; 16]);
  assert_eq!(<Ipv6Addr as CursorValue>::read_cursor(&[0; 15]), None);
}

/// A discriminant byte, then the inner — `0` for `V4`, `1` for `V6`, matching std's
/// declaration-order `Ord` (`V4` is declared first).
#[test]
fn an_ip_address_is_a_tag_then_the_inner() {
  let v4 = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
  assert_eq!(round_trip(v4), [0, 10, 0, 0, 1]);

  let addr: Ipv6Addr = "2001:db8::1".parse().unwrap();
  let mut expected = vec![1];
  expected.extend_from_slice(&addr.octets());
  assert_eq!(round_trip(IpAddr::V6(addr)), expected);

  assert!(
    round_trip(IpAddr::V4(Ipv4Addr::BROADCAST)) < round_trip(IpAddr::V6(Ipv6Addr::UNSPECIFIED)),
    "every V4 sorts below every V6, regardless of either address",
  );
  assert_eq!(<IpAddr as CursorValue>::read_cursor(&[2, 0, 0, 0, 0]), None);
  assert_eq!(<IpAddr as CursorValue>::read_cursor(&[]), None);
}

/// The address, then the port big-endian — address before port, MEASURED at
/// `core::net::SocketAddrV4`'s own field declaration order.
#[test]
fn a_socket_v4_is_the_address_then_the_port_big_endian() {
  let socket = SocketAddrV4::new(Ipv4Addr::new(10, 0, 0, 1), 8080);
  assert_eq!(round_trip(socket), [10, 0, 0, 1, 0x1f, 0x90]);
  assert!(
    SocketAddrV4::new(Ipv4Addr::new(1, 0, 0, 0), 1)
      < SocketAddrV4::new(Ipv4Addr::new(1, 0, 0, 1), 0),
    "the address outweighs the port",
  );
  assert_eq!(<SocketAddrV4 as CursorValue>::read_cursor(&[0; 5]), None);
}

/// The address, the port, the flow label and the scope id, in that order — MEASURED at
/// `core::net::SocketAddrV6`'s own field declaration order, which is the one a caller reading only
/// `Display`'s `addr:port` would miss the last two of.
#[test]
fn a_socket_v6_is_the_address_the_port_the_flowinfo_and_the_scope_id() {
  let ip: Ipv6Addr = "2001:db8::1".parse().unwrap();
  let socket = SocketAddrV6::new(ip, 443, 7, 9);
  let mut expected = ip.octets().to_vec();
  expected.extend_from_slice(&443u16.to_be_bytes());
  expected.extend_from_slice(&7u32.to_be_bytes());
  expected.extend_from_slice(&9u32.to_be_bytes());
  assert_eq!(round_trip(socket), expected);

  // `flowinfo`/`scope_id` participate in `Ord` — two sockets equal on address and port alone still
  // compare unequal, and this is the row that must not have dropped either field to agree.
  assert!(SocketAddrV6::new(ip, 443, 0, 9) < SocketAddrV6::new(ip, 443, 1, 0));
  assert!(SocketAddrV6::new(ip, 443, 7, 0) < SocketAddrV6::new(ip, 443, 7, 1));
  assert_eq!(<SocketAddrV6 as CursorValue>::read_cursor(&[0; 25]), None);
}

/// A discriminant byte, then the inner — [`IpAddr`]'s row, one type over.
#[test]
fn a_socket_address_is_a_tag_then_the_inner() {
  let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 80));
  let v6 = SocketAddr::V6(SocketAddrV6::new("::1".parse().unwrap(), 80, 0, 0));
  let (a, b) = (round_trip(v4), round_trip(v6));
  assert_eq!(a[0], 0);
  assert_eq!(b[0], 1);
  assert!(a < b, "every V4 sorts below every V6, discriminant-first");
  assert_eq!(<SocketAddr as CursorValue>::read_cursor(&[2]), None);
}

/// The compact text member, mirroring [`String`]'s own row byte for byte.
#[cfg(feature = "smol_str")]
#[test]
fn a_smol_str_mirrors_strings_own_encoding() {
  use smol_str::SmolStr;

  assert_eq!(round_trip(SmolStr::new("médià")), "médià".as_bytes());
  assert_eq!(round_trip(SmolStr::new("")), [] as [u8; 0]);
  assert_eq!(<SmolStr as CursorValue>::read_cursor(&[0x80]), None);

  // The identical bytes `String`'s row writes for the same text — a column declared as either text
  // member pages past one cursor.
  let mut smol = Vec::new();
  SmolStr::new("a red car").write_cursor(&mut smol);
  let mut owned = Vec::new();
  "a red car".to_owned().write_cursor(&mut owned);
  assert_eq!(smol, owned);
}

/// The BSON uuid: its sixteen bytes, mirroring [`uuid::Uuid`]'s own row byte for byte.
#[cfg(feature = "mongo")]
#[test]
fn a_bson_uuid_is_its_sixteen_bytes_mirroring_uuids_row() {
  let raw = [
    0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
  ];
  let id = bson::Uuid::from_bytes(raw);
  assert_eq!(round_trip(id), raw);
  assert_eq!(<bson::Uuid as CursorValue>::read_cursor(&[0; 15]), None);

  let mut mirrored = Vec::new();
  uuid::Uuid::from_bytes(raw).write_cursor(&mut mirrored);
  assert_eq!(round_trip(id), mirrored);
}

/// The object id: its twelve bytes, as-is.
#[cfg(feature = "mongo")]
#[test]
fn a_bson_object_id_is_its_twelve_bytes() {
  let raw = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  let id = bson::oid::ObjectId::from_bytes(raw);
  assert_eq!(round_trip(id), raw);
  assert_eq!(
    <bson::oid::ObjectId as CursorValue>::read_cursor(&[0; 11]),
    None
  );
}

// -----------------------------------------------------------------------------------------------
// THE PROPERTY: encoded-byte comparison == the type's own `Ord`, seeded and checked over many
// generated values rather than the handful pinned by hand above.
//
// This workspace carries no `quickcheck`/`proptest` dependency (see `ingraph/Cargo.toml`'s own
// feature-word note), so the house style for a SEEDED property check is a hand-rolled SplitMix64
// (Vigna 2015; public domain) advanced from a FIXED constant: a failure here is reproducible from
// the seed alone, exactly what "seeded" is asked for, without a new dependency this workspace would
// carry for nine rows in one file.
// -----------------------------------------------------------------------------------------------

/// A small, deterministic generator — not a cryptographic one, and not meant to be; only that a
/// fixed seed always produces the same sequence.
struct SplitMix64(u64);

impl SplitMix64 {
  fn next(&mut self) -> u64 {
    self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
    let mut z = self.0;
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
  }

  fn next_u16(&mut self) -> u16 {
    self.next() as u16
  }

  fn next_u32(&mut self) -> u32 {
    self.next() as u32
  }

  fn next_u128(&mut self) -> u128 {
    (u128::from(self.next()) << 64) | u128::from(self.next())
  }

  fn next_bool(&mut self) -> bool {
    self.next() & 1 == 1
  }
}

/// Sorting `values` by their CURSOR BYTES reproduces the same sequence sorting them by their own
/// `Ord` does — the id vocabulary's three-way-equality law, over generated values instead of a
/// handful chosen by hand.
#[track_caller]
fn assert_byte_order_matches_ord<V: CursorValue + Ord + Clone + core::fmt::Debug>(values: &[V]) {
  let mut by_ord = values.to_vec();
  by_ord.sort();

  let mut by_bytes = values.to_vec();
  by_bytes.sort_by_cached_key(|value| {
    let mut bytes = Vec::new();
    value.write_cursor(&mut bytes);
    bytes
  });

  assert_eq!(
    by_bytes, by_ord,
    "sorting by cursor bytes must reproduce the type's own Ord"
  );
}

/// The seed every property test below advances from, XORed per test so the nine draws are
/// independent sequences rather than nine prefixes of one.
const SEED: u64 = 0x1D5C_0DE0_1D5C_0DE0;

/// How many values each property test generates.
const SAMPLES: usize = 256;

#[test]
fn ipv4_addresses_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED);
  let values: Vec<Ipv4Addr> = (0..SAMPLES)
    .map(|_| Ipv4Addr::from(rng.next_u32()))
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[test]
fn ipv6_addresses_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 1);
  let values: Vec<Ipv6Addr> = (0..SAMPLES)
    .map(|_| Ipv6Addr::from(rng.next_u128()))
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[test]
fn ip_addresses_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 2);
  let values: Vec<IpAddr> = (0..SAMPLES)
    .map(|_| {
      if rng.next_bool() {
        IpAddr::V4(Ipv4Addr::from(rng.next_u32()))
      } else {
        IpAddr::V6(Ipv6Addr::from(rng.next_u128()))
      }
    })
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[test]
fn socket_v4_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 3);
  let values: Vec<SocketAddrV4> = (0..SAMPLES)
    .map(|_| SocketAddrV4::new(Ipv4Addr::from(rng.next_u32()), rng.next_u16()))
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[test]
fn socket_v6_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 4);
  let values: Vec<SocketAddrV6> = (0..SAMPLES)
    .map(|_| {
      SocketAddrV6::new(
        Ipv6Addr::from(rng.next_u128()),
        rng.next_u16(),
        rng.next_u32(),
        rng.next_u32(),
      )
    })
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[test]
fn socket_address_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 5);
  let values: Vec<SocketAddr> = (0..SAMPLES)
    .map(|_| {
      if rng.next_bool() {
        SocketAddr::V4(SocketAddrV4::new(
          Ipv4Addr::from(rng.next_u32()),
          rng.next_u16(),
        ))
      } else {
        SocketAddr::V6(SocketAddrV6::new(
          Ipv6Addr::from(rng.next_u128()),
          rng.next_u16(),
          rng.next_u32(),
          rng.next_u32(),
        ))
      }
    })
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[cfg(feature = "smol_str")]
#[test]
fn smol_str_cursor_bytes_agree_with_ord() {
  use smol_str::SmolStr;

  let mut rng = SplitMix64(SEED ^ 6);
  const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _-.";
  let values: Vec<SmolStr> = (0..SAMPLES)
    .map(|_| {
      let len = (rng.next() % 24) as usize;
      let text: String = (0..len)
        .map(|_| ALPHABET[(rng.next() as usize) % ALPHABET.len()] as char)
        .collect();
      SmolStr::new(text)
    })
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[cfg(feature = "mongo")]
#[test]
fn bson_uuid_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 7);
  let values: Vec<bson::Uuid> = (0..SAMPLES)
    .map(|_| {
      let mut bytes = [0u8; 16];
      bytes[..8].copy_from_slice(&rng.next().to_be_bytes());
      bytes[8..].copy_from_slice(&rng.next().to_be_bytes());
      bson::Uuid::from_bytes(bytes)
    })
    .collect();
  assert_byte_order_matches_ord(&values);
}

#[cfg(feature = "mongo")]
#[test]
fn bson_object_id_cursor_bytes_agree_with_ord() {
  let mut rng = SplitMix64(SEED ^ 8);
  let values: Vec<bson::oid::ObjectId> = (0..SAMPLES)
    .map(|_| {
      let mut bytes = [0u8; 12];
      bytes[..8].copy_from_slice(&rng.next().to_be_bytes());
      bytes[8..].copy_from_slice(&rng.next().to_be_bytes()[..4]);
      bson::oid::ObjectId::from_bytes(bytes)
    })
    .collect();
  assert_byte_order_matches_ord(&values);
}