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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
//! The framework's OWN wire carriers: the types an operand crosses as, where the operand's Rust
//! type may not carry a foreign trait.
//!
//! # The TYPE is neutral and the CITIZENSHIP is gated
//!
//! A carrier is a newtype and two total conversions, and none of that names a GraphQL library. What
//! names one is the `#[Scalar]` impl — the CITIZENSHIP — and that is what rides the binding's
//! feature. The split is the law the projection seams follow: a map from a domain type to the form it
//! crosses as is one thing every binding shares, so nothing on the map's side may demand a
//! backend's trait; each backend asks for its own at ITS OWN consumption point, inside its own gate.
//!
//! So a build with no GraphQL library still has `U128` — it just has nothing to render it. A
//! second binding arrives as a second gated block here, over the same thirteen types.
//!
//! # Why a carrier exists at all
//!
//! `async_graphql::ScalarType` is foreign here and so is `u128`, so `impl ScalarType for u128` is
//! `E0117` in this crate and in every crate but async-graphql's own — and async-graphql 7.2 declines
//! the impl deliberately: `types/external/integers.rs` covers `i8`…`i64`, `u8`…`u64`, `usize`,
//! `isize` and stops. `Vec<u8>` is the same wall from the other side: it HAS a face — `[Int!]`, a
//! list of small integers — and that face answers the wrong question about a blob.
//!
//! So the operand crosses through a LOCAL newtype that carries the scalar, which is the arrangement
//! [`DurationFilter`](crate::DurationFilter) already proved for `jiff::SignedDuration`. What a
//! carrier is for is exactly one crossing: the Rust slot holds the DOMAIN value and the carrier
//! holds the WIRE form, whatever that turns out to be.
//!
//! An impossible impl is only the first reason a carrier exists. The second is that a face can be
//! possible and WRONG — `Vec<u8>`'s is — and the third arrived with the SCALAR SUITE below, where
//! ten Rust widths had a face that compiled, answered, and did not say which width it was.
//!
//! # These carriers are PUBLIC, where the duration's was private
//!
//! A filter's operand crosses INWARD, and a carrier serving only that can stay private — the filter
//! reads the wire type and hands the domain value on. An OUTPUT position crosses OUTWARD, and there
//! the carrier is what a resolver RETURNS, so it has to be a type the emitted face can name. Every
//! carrier here therefore has both legs — one `#[Scalar]` impl writes `InputType` AND `OutputType` —
//! and a total conversion in both directions.
//!
//! # THE SCALAR SUITE, and it is BINDING-SCOPED
//!
//! Twelve of the carriers below are one family: `U8 U16 U32 U64 U128`, `I8 I16 I32 I64 I128`,
//! `F32 F64` — one wrapper per Rust numeric width, each publishing its OWN SDL name. They exist
//! because async-graphql spends two names on TWELVE types: `types/external/integers.rs` publishes
//! `i8`…`i64`, `u8`…`u64`, `usize` and `isize` as `Int` — ten of them — and
//! `types/external/floats.rs` publishes both `f32` and `f64` as `Float`. A schema built through
//! those rows tells a client *this is a number* and nothing about which one, so a 64-bit id and a
//! byte read identically, and an `f32` currency and an `f64` currency are one SDL type that two
//! Rust types can be minted under silently.
//!
//! A THIRTEENTH joins them behind the `half` feature — [`F16`], IEEE binary16 — and it is the one
//! whose operand is not Rust's own. That is the whole reason it rides a word: the twelve above cost
//! a build nothing but their own newtypes, and this one costs a dependency, so it enters when a
//! declaration asks for it. It is explicitly the IEEE half and not `bfloat16`; the two are different
//! formats at one width, and `BF16` is a word left unspent for the second.
//!
//! # THE NAMES ARE THE ROSTER's, and this file is where the roster is spelled
//!
//! Each row's `#[Scalar(name = …)]` literal is the ONE place that width's wire name is written, and
//! the filter it publishes under is DERIVED from it — `u32` and `U32Filter` out of one `"u32"`.
//! That is the NAMING CONSTITUTION's first law made mechanical, and [`roster`](super::roster) is
//! where the law, the whole table and what is deliberately outside it are stated. The rows this
//! replaced spelled the two names in two files, so a rename could land on one of them.
//!
//! **The suite lives ONLY here, in the async-graphql binding's own trait implementations.** Every
//! other surface keeps the bare Rust type: a declaration says `u64`, a filter slot HOLDS a `u64`,
//! retrieve and storage carry a `u64`, and the wrapper appears at the crossing and nowhere before
//! it. That is the same split [`carrier`](super::carrier) states for the map — the TYPE is neutral
//! and the CITIZENSHIP is gated — read one level down: a wrapper is a wire form, and a wire form is
//! one backend's vocabulary.
//!
//! It stays thin for a reason on the record: a FIRST-PARTY GraphQL framework is planned, and it
//! will carry richer base types natively — so the widths this layer has to spell twelve wrappers to
//! say will be things that framework simply has. This layer is the one async-graphql needs, written
//! so that replacing it replaces nothing else: the suite is twelve newtypes and their `Into`s, the
//! crossing maps are unconditional, and nothing outside this file knows the wrappers exist.
//!
//! # THE NAMED VOCABULARIES beside the suite, and why they are PASCAL
//!
//! The suite spells WIDTHS, and a width is the framework's own reading of a Rust primitive — so
//! those names are lowercase and they are what [`roster`](super::roster)'s table holds. Everything
//! else this file mints is a NAMED TYPE wearing its own name, which law three of the constitution
//! puts in Pascal: the byte households (`U8Vector`, `SmolBytes`, `Fixed{N}U8Array`), the NETWORK
//! family below them (`Ipv4Addr`, `Ipv6Addr`, `IpAddr`, `SocketAddrV4`, `SocketAddrV6`,
//! `SocketAddr`), and `Uuid`.
//!
//! The derivation law is unchanged over them and needs nothing new to be: `UpperCamel(scalar)` on a
//! name already capital is that name, so `Ipv4Addr` derives `Ipv4AddrFilter` out of the one literal
//! its row is given. A lowercase snake spelling would have BROKEN that law rather than merely read
//! oddly — `capitalised` raises one byte, so `ipv4_addr` would derive `Ipv4_addrFilter`, and the
//! filter name would have to be a second literal somebody keeps in step.
//!
//! What each carrier is NAMED in Rust is a third thing again, and it is `Net` + the operand's own
//! word — [`NetIpv4Addr`] carries `std::net::Ipv4Addr` and publishes `Ipv4Addr`. That is
//! [`JiffDuration`](crate::JiffDuration)'s own construction (the crate of origin in front of the
//! type's word), and it is what keeps `ingraph`'s root re-exports from shadowing `std::net`'s
//! spellings for a crate that imports both.
//!
//! **The uuid row is where that construction had to be read for its PURPOSE rather than applied
//! letter for letter**, because the crate of origin and the type's word are the SAME word: `uuid` +
//! `Uuid` is a name nobody would write. The purpose is the anti-shadowing one — a crate importing
//! both `ingraph::*` and `uuid::Uuid` must not meet two `Uuid`s — so the carrier is named for the
//! WIRE FORM it carries instead, [`HyphenatedUuid`], which is [`HexBytes`]'s own construction one
//! household over. Recorded here so the next row that hits the collision reads the rule and not just
//! the precedent. The SDL name is unaffected and is `Uuid`, exactly as the address rows' are their
//! operands' words.
//!
//! # The lexical form is HYBRID for FOUR of them, and the boundary is a measurement
//!
//! A JSON number does not survive the trip at every width: `serde_json`'s number is a `u64`, an
//! `i64` or an `f64`, and a JavaScript client reads every number as a double — so a large value
//! arrives with its low bits rounded away and no error anywhere. Decimal text is exact at every
//! magnitude, which is what the big-number ecosystems settled on for the same reason.
//!
//! **Where the loss STARTS is [`SAFE`], and it is a fact about doubles rather than a policy.** 2^53
//! is exactly representable as a double and so is every integer below it; 2^53 + 1 is NOT, and
//! rounds to 2^53 — so a round trip through a double stops being injective AT 2^53, and the widest
//! integer that survives one is 2^53 − 1. That number is JavaScript's own `Number.MAX_SAFE_INTEGER`,
//! and it is where these four scalars change form.
//!
//! So the four overflow-risky widths — [`U64`], [`I64`], [`U128`], [`I128`] — encode as a JSON
//! NUMBER while `|v| ≤ 2^53 − 1` and as a decimal STRING beyond it. An id, a checksum and a
//! nanosecond timestamp cross as text because they have to; a count, an offset and a byte length
//! cross as the number they are, and a client does its arithmetic without parsing anything. The
//! DECODE side is liberal in both directions at every magnitude — a string is read at any value in
//! range, a number is read inside its own range — so a client that has only ever sent strings keeps
//! working and one that has only ever sent numbers does too.
//!
//! The other eight cross as JSON numbers unconditionally, and each for a measured reason rather than
//! for symmetry:
//!
//! - `U8`…`U32` and `I8`…`I32` fit a double EXACTLY at every value — the widest of them, `u32::MAX`,
//!   is 2^32 − 1 and so twenty-one bits short of [`SAFE`] — so the string form is unreachable and
//!   the branch is not written at all.
//! - `F32` and `F64` are the case where text would be actively WRONG. A JSON number IS a double to
//!   the client that reads it, and an `f64` is a double, so the wire form and the value are the
//!   same object; `f32` widens into one exactly. There is no 2^53 to be honest about here — the
//!   loss the four integers suffer is the loss of being an integer a double cannot name, and a
//!   float is not one.
//!
//! # The render is ALLOCATION-FREE up to the one string the wire type requires
//!
//! [`Digits`] writes into a `[u8; 40]` on the stack — 39 digits is `u128::MAX`, and 39 digits under
//! a sign is `i128::MIN` — so no intermediate buffer grows and none is thrown away. The one
//! allocation left is `async_graphql::Value::String`'s own: that variant holds a `String`, so a
//! rendered operand becomes one exactly-sized copy AT the boundary and nowhere before it.
//!
//! Stated that precisely because the honest saving is smaller than "zero allocation" sounds: `u128`'s
//! own `Display` also writes through a stack buffer, and `ToString` over it lands on one exact
//! allocation too (`String`'s first `push_str` reserves the length it is handed). What this saves is
//! the FORMATTING MACHINERY — a `Formatter`, the `Display` dispatch, the `fmt::Write` path — on a
//! render that runs once per operand and once per element of an `in` list, and it saves the
//! allocation entirely on the [`Display`] path, which writes into the caller's formatter directly.

#[cfg(feature = "async-graphql")]
use core::num::IntErrorKind;
use core::{convert::Infallible, fmt::Display};

use super::carrier::{Builtin, BytesWire, ScalarWire};
#[cfg(all(test, feature = "async-graphql"))]
use super::roster::Row;

#[cfg(all(test, feature = "async-graphql"))]
mod tests;

/// One 128-bit integer rendered into a stack buffer, digits last.
///
/// The buffer is 40 bytes because that is the widest either operand gets: `u128::MAX` is 39 digits
/// (`340282366920938463463374607431768211455`) and `i128::MIN` is 39 digits under a sign. Pinned by
/// the round-trip tests beside this module rather than by this sentence, since a buffer one byte
/// short would panic on exactly two values in the whole domain.
///
/// Written from the END, which is what makes one pass enough: division produces the LOW digit first
/// and the low digit belongs last, so filling backwards needs no reversal and no second buffer.
struct Digits {
  buffer: [u8; Self::WIDTH],
  /// Where the rendered text starts; everything before it is untouched.
  at: usize,
}

impl Digits {
  /// 39 digits, and room for the sign.
  const WIDTH: usize = 40;

  /// An unsigned operand's decimal digits.
  fn unsigned(mut value: u128) -> Self {
    let mut buffer = [0u8; Self::WIDTH];
    let mut at = Self::WIDTH;
    loop {
      at -= 1;
      // A remainder of ten is one digit, so the narrowing cast can lose nothing.
      buffer[at] = b'0' + (value % 10) as u8;
      value /= 10;
      if value == 0 {
        break;
      }
    }
    Self { buffer, at }
  }

  /// A signed operand's decimal digits, under a leading `-` where it is negative.
  ///
  /// The magnitude comes from [`i128::unsigned_abs`] and never from a negation: `-i128::MIN` is not
  /// an `i128`, so negating first would overflow on the one value a signed operand most needs to
  /// render.
  fn signed(value: i128) -> Self {
    let mut digits = Self::unsigned(value.unsigned_abs());
    if value.is_negative() {
      digits.at -= 1;
      digits.buffer[digits.at] = b'-';
    }
    digits
  }

  /// The rendered text, borrowed out of the stack buffer.
  fn as_str(&self) -> &str {
    core::str::from_utf8(&self.buffer[self.at..]).expect("digits and a sign are ASCII")
  }
}

/// One wire value read as text, or `None` where it is not a string.
///
/// What is wrong with a non-string is the SCALAR's to say — see [`refuse`] — so this answers the
/// narrower question and leaves the sentence to the caller.
#[cfg(feature = "async-graphql")]
fn text(value: &async_graphql::Value) -> Option<&str> {
  match value {
    async_graphql::Value::String(text) => Some(text.as_str()),
    _ => None,
  }
}

/// The sentence one refused STRING operand takes back, naming the scalar and what was wrong with
/// the operand.
///
/// [`IntErrorKind`] is read rather than the parse error's own message, which says *invalid digit
/// found in string* and never which bound was passed. Three sentences, each telling a client
/// something it can act on: which scalar refused, what the form is, and — for the two overflow
/// kinds — what the bound actually is, a range being the one fact a client cannot discover by
/// trying.
///
/// The SCALAR is named rather than its width described. `u64` and `u128` are two scalars in one
/// schema now, so *a 128-bit integer* would leave a client holding a refusal it cannot attribute to
/// the field that produced it.
///
/// It says *a string operand* rather than *this scalar crosses as text*, which is the correction the
/// hybrid encoding forced: a JSON number IS one of the two forms these four take, so a sentence
/// telling a client its number was never legal would be teaching the wrong grammar. What is still
/// true is that a STRING is decimal digits, and that is what a refused string is told.
#[cfg(feature = "async-graphql")]
fn refuse(scalar: &str, text: &str, kind: &IntErrorKind, range: &str, ceiling: &str) -> String {
  match kind {
    IntErrorKind::Empty => format!(
      "a `{scalar}` written as a string is decimal text and this one is empty — write the digits, \
       as in \"{ceiling}\""
    ),
    IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => {
      format!("`{text}` is outside `{scalar}`'s range ({range})")
    }
    _ => format!(
      "`{text}` is not a `{scalar}` — a string operand is DECIMAL TEXT ({range}), and a JSON number \
       is read too wherever it is whole and in range"
    ),
  }
}

/// The sentence one refused JSON NUMBER takes back at a hybrid width — a fraction, or a value the
/// scalar's own range does not hold.
///
/// It names the STRING form as the repair, which is the half a client needs and the half the number
/// form cannot supply: past [`SAFE`] a number is not merely refused here, it is a value no JSON
/// number could have carried intact in the first place.
#[cfg(feature = "async-graphql")]
fn refuse_number(scalar: &str, number: &async_graphql::Number, range: &str) -> String {
  format!(
    "`{number}` is not a `{scalar}` — a JSON number crosses as a WHOLE value inside the scalar's \
     range ({range}), and a value past {SAFE} is written as DECIMAL TEXT instead, which is exact in \
     both directions where a double is not"
  )
}

/// **THE ENCODING BOUNDARY** — the widest integer a JSON number delivers to a client intact, and
/// where the four hybrid scalars change form.
///
/// 2^53 − 1, which is JavaScript's own `Number.MAX_SAFE_INTEGER` and is a fact about IEEE doubles
/// rather than about that language: 2^53 is exactly representable and so is every integer below it,
/// but 2^53 + 1 is not and rounds to 2^53 — so the round trip stops being injective AT 2^53, and the
/// last integer that survives one is the value below it.
///
/// A `u128`, so the two signed widths compare their MAGNITUDE against it and the two unsigned ones
/// compare their value: one constant, four scalars, and no second spelling of the same number.
///
/// Behind the BINDING, like the two readers below it: what the number decides is a lexical form, and
/// a build with no GraphQL library has no wire for a form to be on.
#[cfg(feature = "async-graphql")]
pub(crate) const SAFE: u128 = (1 << 53) - 1;

/// One unsigned operand as a JSON number, or [`None`] where it is past [`SAFE`] and has to cross as
/// text.
///
/// The narrowing cannot fail and says so: [`SAFE`] is 2^53 − 1, which is twelve bits short of
/// `u64::MAX`, so every value reaching the cast is inside a `u64` by the guard above it.
#[cfg(feature = "async-graphql")]
fn safe_unsigned(value: u128) -> Option<async_graphql::Number> {
  (value <= SAFE).then(|| {
    async_graphql::Number::from(u64::try_from(value).expect("the safe range fits a `u64`"))
  })
}

/// One signed operand as a JSON number, or [`None`] where its MAGNITUDE is past [`SAFE`].
///
/// [`i128::unsigned_abs`] and never a negation, for [`Digits::signed`]'s own reason: `-i128::MIN` is
/// not an `i128`, so negating first would overflow on the one value most in need of the branch.
#[cfg(feature = "async-graphql")]
fn safe_signed(value: i128) -> Option<async_graphql::Number> {
  (value.unsigned_abs() <= SAFE).then(|| {
    async_graphql::Number::from(i64::try_from(value).expect("the safe range fits an `i64`"))
  })
}

/// One wire number read as a WHOLE value, or `None` where it carries a fraction.
///
/// `i128` is what both JSON integer arms widen into without loss — `serde_json`'s number is a `u64`
/// or an `i64` there — so one return type serves the signed and the unsigned narrow scalars and the
/// range check below is written once. `as_f64` is deliberately NOT consulted: `1.5` is not a whole
/// number, and reading it through a float would round it into one silently.
#[cfg(feature = "async-graphql")]
fn integral(number: &async_graphql::Number) -> Option<i128> {
  number
    .as_i64()
    .map(i128::from)
    .or_else(|| number.as_u64().map(i128::from))
}

/// Declare one carrier: the newtype, its two total conversions, and the operand behind it.
///
/// The conversions are what a crossing spends — a filter's slot holds the DOMAIN value, so an
/// operand is read through `Into<$domain>` on the way in and written through `From<$domain>` on the
/// way out — and they are total in both directions, a carrier being exactly its operand with a wire
/// face attached.
///
/// [`Display`] is NOT written here: each carrier renders through its own buffer, and the whole point
/// of the four text-carried integers is that they render without allocating. A macro arm taking a
/// rendering expression would have had to hand back a `String` to be uniform, which is the
/// allocation this module exists to avoid.
///
/// # THREE ARMS, and each one past the first is a derive list its operand cannot satisfy
///
/// A carrier derives what its operand has, `#[derive]` putting the bound on the field's type. `f32`
/// and `f64` have `PartialEq` and `PartialOrd` and no `Eq`, `Hash` or `Ord`, NaN being neither
/// equal to itself nor ordered against anything — so the total-order list is `E0277` on
/// [`F32`]/[`F64`] naming `Eq`, at the derive.
///
/// `bare` is that same fact one trait earlier, and `regex::Regex` is the operand that took it: a
/// compiled pattern has `Debug` and `Clone` and NONE of the rest — no `PartialEq`, so no `Eq` and no
/// `Hash`, and no `PartialOrd`. That is the engine's own silence and not an omission: two automata
/// built from different texts can accept exactly the same language, and `regex` declines to say
/// whether that makes them the same value. So the floats' list refuses here as well.
///
/// **The arms are ONE LAW read at three operands, not three policies.** A carrier may claim what its
/// operand claims and nothing more, so the list shrinks to fit rather than the operands being made
/// to fit the list — and weakening the first list to the third's would have taken `Eq`, `Hash` and
/// `Ord` from ten integer carriers that genuinely are hashable keys, whose schema-side collections
/// should stay collections.
///
/// Written as arms rather than as three macros because everything else about a carrier is shared.
/// A leading `#[…]` list is the row's own GATE, applied to every item the arm mints — the shape a
/// carrier whose OPERAND rides a feature needs, since a `pub struct` and its three impls have to
/// appear and disappear together. The twelve unconditional rows write no attribute at all.
macro_rules! carrier {
  ($( #[$gate:meta] )* $name:ident($domain:ty), $doc:literal) => {
    carrier!(@ [Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord]
      $( #[$gate] )* $name($domain), $doc);
  };

  ($( #[$gate:meta] )* partial $name:ident($domain:ty), $doc:literal) => {
    carrier!(@ [Debug, Clone, PartialEq, PartialOrd] $( #[$gate] )* $name($domain), $doc);
  };

  ($( #[$gate:meta] )* bare $name:ident($domain:ty), $doc:literal) => {
    carrier!(@ [Debug, Clone] $( #[$gate] )* $name($domain), $doc);
  };

  (@ [$($derive:ident),+ $(,)?] $( #[$gate:meta] )* $name:ident($domain:ty), $doc:literal) => {
    #[doc = $doc]
    #[doc = ""]
    #[doc = "A WIRE CARRIER: it exists so that the operand's own type does not have to implement a"]
    #[doc = "foreign trait it may not. Every filter slot it crosses into holds the domain value."]
    #[derive($($derive),+)]
    $( #[$gate] )*
    pub struct $name($domain);

    $( #[$gate] )*
    impl $name {
      /// The operand this carrier holds.
      #[inline]
      #[must_use]
      pub const fn get(&self) -> &$domain {
        &self.0
      }

      /// The operand, taken back out of the carrier.
      #[inline]
      #[must_use]
      pub fn into_inner(self) -> $domain {
        self.0
      }
    }

    $( #[$gate] )*
    impl From<$domain> for $name {
      #[inline]
      fn from(value: $domain) -> Self {
        Self(value)
      }
    }

    $( #[$gate] )*
    impl From<$name> for $domain {
      #[inline]
      fn from(carrier: $name) -> Self {
        carrier.0
      }
    }
  };
}

carrier!(
  U8(u8),
  "An unsigned 8-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
  U16(u16),
  "An unsigned 16-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
  U32(u32),
  "An unsigned 32-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
  U64(u64),
  "An unsigned 64-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);
carrier!(
  U128(u128),
  "An unsigned 128-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);

carrier!(
  I8(i8),
  "A signed 8-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
  I16(i16),
  "A signed 16-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
  I32(i32),
  "A signed 32-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
  I64(i64),
  "A signed 64-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);
carrier!(
  I128(i128),
  "A signed 128-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);

carrier!(
  #[cfg(feature = "half")]
  partial F16(half::f16),
  "A HALF-precision float on the wire — a JSON number, which a double holds one of exactly."
);

carrier!(
  partial F32(f32),
  "A single-precision float on the wire — a JSON number, which is what a double holds one of exactly."
);
carrier!(
  partial F64(f64),
  "A double-precision float on the wire — a JSON number, which IS a double."
);

carrier!(
  #[cfg(feature = "rust_decimal")]
  F128(rust_decimal::Decimal),
  "The widest float row on the wire — DECIMAL TEXT, exact at every magnitude its operand holds."
);

carrier!(
  HexBytes(Vec<u8>),
  "A byte string on the wire — lowercase hexadecimal, two characters per byte."
);

/// The DECIMAL SPELLING of one hybrid integer, written straight into the caller's formatter.
///
/// Only the four that can cross as text have one. A [`Display`] on `U8` would name a lexical form
/// that scalar has not got — it crosses as a JSON number at every value in its domain — so there is
/// no string of its for a `Display` to be about.
///
/// # It is the WIRE form only past [`SAFE`], and that is the hybrid encoding's own cost
///
/// The two questions *what is this value's decimal spelling* and *what does this carrier put on the
/// wire* were one question while the four crossed as text unconditionally. They are not now: inside
/// the safe range `to_value` answers a JSON number and this still answers the digits. The digits are
/// the honest answer for a `Display` — it is the value's spelling, which is what a Rust reader,
/// a log line and a refusal all want — and the wire form is `to_value`'s alone.
///
/// The operand widens into the buffer's own width before rendering, which is free and exact: every
/// unsigned domain here is a `u128` and every signed one an `i128`.
macro_rules! text_render {
  ($( $name:ident via $render:path ),+ $(,)?) => {
    $(
      impl Display for $name {
        #[inline]
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
          f.write_str($render(self.0.into()).as_str())
        }
      }
    )+
  };
}

text_render!(
  U64 via Digits::unsigned,
  U128 via Digits::unsigned,
  I64 via Digits::signed,
  I128 via Digits::signed,
);

/// The LOWERCASE HEX SPELLING of a byte carrier, written straight into the caller's formatter.
///
/// One body over every skin, because the spelling is the household's rather than the skin's: the
/// scalars differ in NAME and in nothing else, and a second rendering per skin would be a second
/// place for that claim to stop being true.
macro_rules! hex_render {
  ($( $name:ty ),+ $(,)?) => {
    $(
      impl Display for $name {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
          for byte in &self.0 {
            f.write_str(nibbles(*byte).as_str())?;
          }
          Ok(())
        }
      }
    )+
  };
}

hex_render!(HexBytes, U8Vector, SmolBytes);

impl<const N: usize> Display for FixedU8Array<N> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    for byte in &self.0 {
      f.write_str(nibbles(*byte).as_str())?;
    }
    Ok(())
  }
}

/// One `f64` off the wire, narrowed to the width [`F32`] holds.
///
/// A named function rather than a cast written into the macro, and for two reasons: it keeps the
/// two float rows one shape — [`F64`]'s row names `identity` in the same position — and it puts the
/// one lossy conversion in the file at a site a reader can find and a lint can be pointed at,
/// rather than inside an expansion nobody can annotate.
///
/// The narrowing is async-graphql's OWN, measured at `types/external/floats.rs`: its `f32` scalar
/// parses `n.as_f64()? as Self` too, so a value past `f32::MAX` becomes an infinity at both. Kept
/// deliberately — this round changes what a width is CALLED in a schema and not what it accepts,
/// and a stricter `F32` would be a semantic change riding in on a naming one.
///
/// No `#[expect]` rides on it: `clippy::cast_possible_truncation` is pedantic and allow-by-default,
/// and this workspace's lint tables turn no pedantic group on — so the expectation would go
/// UNFULFILLED, which `unfulfilled_lint_expectations` warns about and `ci/test-matrix.sh`'s
/// `-D warnings` turns into a failure.
#[cfg(feature = "async-graphql")]
pub(crate) fn narrowed(wide: f64) -> f32 {
  wide as f32
}

/// One `f64` off the wire, narrowed to the width [`F16`] holds.
///
/// [`narrowed`]'s twin one width down, and it is a NAMED CONVERSION rather than a cast for that
/// one's reason: the two float rows either side of it name `narrowed` and `identity` in the same
/// position, so the lossy directions are the ones a reader can find.
///
/// `half::f16::from_f64` is the crate's own round-to-nearest-even conversion, and it saturates the
/// way `as f32` does: a value past `f16::MAX` (65504) becomes an infinity rather than refusing —
/// which is `F32`'s shipped behaviour and async-graphql's before it, kept so that a width says what
/// it is READ at and adds no range of its own.
#[cfg(all(feature = "half", feature = "async-graphql"))]
pub(crate) fn halved(wide: f64) -> half::f16 {
  half::f16::from_f64(wide)
}

/// Uppercase the first byte of an ASCII name, at COMPILE TIME.
///
/// The whole of the amended derivation law's machinery: a filter name is `UpperCamel(scalar)` plus
/// `Filter`, the scalar names are ASCII and one word (`u64`, `f16`, `f128`), and `concat!` cannot
/// change a case. A `const fn` over the bytes can, and it keeps the row the SINGLE place either name
/// is written — which is the property the law is for.
///
/// `N` is the length the caller already knows, because a `const fn` cannot return a reference to a
/// buffer it made: the array is the return value, the caller binds it to a `const`, and
/// [`str::from_utf8`] reads that constant back as a `&'static str`.
const fn capitalised<const N: usize>(name: &str) -> [u8; N] {
  let source = name.as_bytes();
  assert!(source.len() == N, "the caller passes the name's own length");
  let mut raised = [0_u8; N];
  let mut at = 0;
  while at < N {
    raised[at] = source[at];
    at += 1;
  }
  raised[0] = raised[0].to_ascii_uppercase();
  raised
}

/// **THE DERIVATION, in one place** — `UpperCamel(scalar) + "Filter"`, out of the SAME literal the
/// `#[Scalar(name = …)]` citizenship was handed.
///
/// The scalar stays Rust-flavoured and lowercase (`u64`); its filter is an input OBJECT and takes
/// the Pascal every other type name in a schema takes (`U64Filter`), which is the 2026-08-18
/// amendment. Both names still come from one literal, so a row that renamed its scalar and forgot
/// its filter is not a state this file can be left in.
macro_rules! derived_filter {
  ($gql:literal) => {{
    const DERIVED: &str = concat!($gql, "Filter");
    const RAISED: [u8; DERIVED.len()] = capitalised::<{ DERIVED.len() }>(DERIVED);
    match ::core::str::from_utf8(&RAISED) {
      Ok(name) => name,
      Err(_) => panic!("a roster name is ASCII"),
    }
  }};
}

/// The framework's own reading of one ROSTER ROW: which carrier the operand crosses on, and — the
/// half this macro exists for — the input object it is published under, derived from the SAME
/// scalar literal the citizenship above was handed.
///
/// **The derivation is the constitution's first law**, and writing it as a derivation rather than as
/// a second literal is what makes a row the single place either name appears. The rows this replaced
/// spelled both — `i32 => "Int32Filter" via I32` beside `#[Scalar(name = "I32")]`, in two files —
/// so a renamed scalar and a forgotten filter were a state the tree could be left in and a test had
/// to catch. Now they cannot disagree; there is one literal.
///
/// See [`roster`](super::roster) for the table itself and for what is deliberately NOT in it.
macro_rules! builtin_reading {
  ($( $name:ident($domain:ty) : $gql:literal ),+ $(,)?) => {
    $(
      impl ScalarWire<$domain> for Builtin {
        const NAME: &'static str = derived_filter!($gql);

        type Carrier = $name;
        type Error = Infallible;

        #[inline]
        fn cross(carrier: $name) -> Result<$domain, Infallible> {
          Ok(<$name as Into<$domain>>::into(carrier))
        }

        #[inline]
        fn carry(operand: &$domain) -> $name {
          <$name>::from(operand.clone())
        }
      }
    )+
  };
}

/// One line of the ROSTER, for a row that has a filter — the three names the table commits to and
/// the two the binding actually emits, so the test between them is the table against the schema.
#[cfg(all(test, feature = "async-graphql"))]
macro_rules! filtered_row {
  ($name:ident($domain:ty) : $gql:literal) => {
    Row {
      rust: stringify!($domain),
      scalar: $gql,
      filter: Some(derived_filter!($gql)),
      scalar_face: || <$name as async_graphql::InputType>::type_name().into_owned(),
      filter_face: Some(|| {
        <crate::ScalarFilter<$domain> as async_graphql::InputType>::type_name().into_owned()
      }),
    }
  };
}

/// One line of the ROSTER for a row that is a SCALAR and nothing more — a width no declaration can
/// name as a column type, so there is no filter for the derivation to have produced.
///
/// Gated on the WORDS that have such a row rather than on the binding alone: every lone width rides
/// a vocabulary feature, so with none of them on there is no lone table for this to line, and an
/// ungated definition is an `unused_macros` warning the `-D warnings` lanes turn into a failure.
#[cfg(all(
  test,
  feature = "async-graphql",
  any(feature = "half", feature = "rust_decimal")
))]
macro_rules! lone_row {
  ($name:ident($domain:ty) : $gql:literal) => {
    Row {
      rust: stringify!($domain),
      scalar: $gql,
      filter: None,
      scalar_face: || <$name as async_graphql::InputType>::type_name().into_owned(),
      filter_face: None,
    }
  };
}

/// Declare the async-graphql citizenship of one HYBRID integer — the four whose domain runs past
/// what a JSON number delivers to a client intact.
///
/// `$render` is the stack buffer the operand widens into for the text half, `$safe` the reader that
/// answers a JSON number where the value is inside [`SAFE`], `$gql` the SDL name, and the braced
/// literals the scalar's own DESCRIPTION — which is where the grammar has to be said, `eq: u64`
/// telling a client nothing about the lexical forms its operand takes.
///
/// # ENCODE forks and DECODE does not, which is the asymmetry the law is written as
///
/// `to_value` answers ONE form per value — the number where the value survives a double, the digits
/// where it does not — so a client reading a field always gets the widest form that is lossless for
/// what it is holding. `parse` and `is_valid` accept BOTH at every value in range, which is Postel's
/// half of the same design: a client that has only ever sent strings keeps working, one that has
/// only ever sent numbers does too, and neither has to know where the boundary is.
///
/// The two halves are one reader each — [`text`] and [`integral`] — so the string leg and the number
/// leg cannot come to disagree with each other, and `is_valid` runs the same pair.
///
/// The scalar name is a LITERAL and the width names itself — `u64` for `u64` — which is the
/// constitution's first law read at this table: the framework's own vocabulary is Rust's, spelled
/// the way Rust spells it. A literal rather than `stringify!($domain)` because `$gql` also has to
/// reach the `#[Scalar]` ATTRIBUTE, and an attribute's arguments are not macro-expanded; the same
/// literal is what the row's filter name is DERIVED from, so the two cannot drift.
///
/// `rows = …` names the const this table publishes into [`roster`](super::roster), which is where
/// the emission-consistency test reads them.
macro_rules! hybrid_integer_scalar {
  (rows = $rows:ident; $(
    $name:ident($domain:ty) : $gql:literal via $render:path, safe = $safe:path
      { $( $doc:literal )+ }
  )+) => {
    builtin_reading!($( $name($domain) : $gql ),+);

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];

    $(
      $( #[doc = $doc] )+
      #[cfg(feature = "async-graphql")]
      #[async_graphql::Scalar(name = $gql)]
      impl async_graphql::ScalarType for $name {
        fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
          let range = || format!("{} … {}", <$domain>::MIN, <$domain>::MAX);
          if let Some(digits) = text(&value) {
            return match digits.parse() {
              Ok(operand) => Ok(Self(operand)),
              Err(error) => Err(async_graphql::InputValueError::custom(refuse(
                $gql,
                digits,
                core::num::ParseIntError::kind(&error),
                &range(),
                &<$domain>::MAX.to_string(),
              ))),
            };
          }
          // THE NUMBER LEG, read at EVERY magnitude the scalar's own range holds rather than only
          // inside the safe one. A number past 2^53 has already lost its low bits before this crate
          // sees it, so refusing it here would refuse a value nobody could have written correctly —
          // and would refuse it as if the client had a repair, which it does not. What it gets
          // instead is the value it actually sent, and an encode side that never hands one back.
          if let async_graphql::Value::Number(ref number) = value {
            return match integral(number).and_then(|whole| <$domain>::try_from(whole).ok()) {
              Some(operand) => Ok(Self(operand)),
              None => Err(async_graphql::InputValueError::custom(refuse_number(
                $gql, number, &range(),
              ))),
            };
          }
          Err(async_graphql::InputValueError::expected_type(value))
        }

        /// The SAME parser [`parse`](Self::parse) runs, which is what makes a document that
        /// validates a document that parses. async-graphql's default `is_valid` answers `true` for
        /// every value, so a scalar that narrows in `parse` alone ships a validator admitting what
        /// its own parser rejects — which its OWN integer scalars do: `is_valid` there is
        /// `matches!(value, Value::Number(n) if n.is_i64())` and never asks the range `parse`
        /// enforces, so `Int` validates `300` and refuses it one stage later.
        ///
        /// BOTH legs, because both parse: a validator that admitted one form would reject documents
        /// this scalar reads.
        #[inline]
        fn is_valid(value: &async_graphql::Value) -> bool {
          if let Some(digits) = text(value) {
            return digits.parse::<$domain>().is_ok();
          }
          matches!(
            value,
            async_graphql::Value::Number(number)
              if integral(number).is_some_and(|whole| <$domain>::try_from(whole).is_ok())
          )
        }

        /// The NUMBER inside [`SAFE`] and the DIGITS beyond it — one form per value, and the widest
        /// one that survives the trip.
        fn to_value(&self) -> async_graphql::Value {
          match $safe(self.0.into()) {
            Some(number) => async_graphql::Value::Number(number),
            None => async_graphql::Value::String(
              String::from($render(self.0.into()).as_str()),
            ),
          }
        }
      }
    )+
  };
}

hybrid_integer_scalar! {
  rows = HYBRID_ROWS;

  U64(u64) : "u64" via Digits::unsigned, safe = safe_unsigned {
    "An unsigned 64-bit integer — `42` as a JSON number, `\"18446744073709551615\"` as decimal text."
    ""
    "**HYBRID, and the boundary is 9007199254740991 — 2^53 − 1.** `serde_json`'s number is a `u64`,"
    "an `i64` or an `f64`, and a JavaScript client reads every number as a double, so an integer"
    "past that bound arrives with its low bits rounded away and no error anywhere: 2^53 + 1 is not"
    "representable and rounds to 2^53. Up to the bound a number is exact and a client can do"
    "arithmetic on it directly; past it the value crosses as decimal text, which is exact at every"
    "magnitude."
    ""
    "A value SENT in either form is read, at any magnitude the range holds — a string of digits"
    "always, a JSON number wherever it is whole and in range — so a client written against either"
    "form alone works unchanged. What comes BACK is the number below the bound and the string above"
    "it, never both for one value."
    ""
    "A value outside the range is REFUSED and never wrapped or clamped; so are a fraction, a"
    "boolean and an empty string. The refusal names the range, that being the one fact a client"
    "cannot discover by trying."
  }

  U128(u128) : "u128" via Digits::unsigned, safe = safe_unsigned {
    "An unsigned 128-bit integer — `42` as a JSON number,"
    "`\"340282366920938463463374607431768211455\"` as decimal text."
    ""
    "HYBRID at 2^53 − 1, for `u64`'s reason, over a domain most of which no client could hold under"
    "any encoding but text."
    ""
    "Both forms are read on the way in and one comes back per value. A value outside the range is"
    "REFUSED and never wrapped or clamped, and the refusal names the range."
  }

  I64(i64) : "i64" via Digits::signed, safe = safe_signed {
    "A signed 64-bit integer — `-42` as a JSON number, `\"-9223372036854775808\"` as decimal text."
    ""
    "HYBRID at a MAGNITUDE of 2^53 − 1, for `u64`'s reason: the bound is about how many bits a"
    "double carries, so it is symmetric about zero. A leading `-` is part of the value; a leading"
    "`+` is accepted in the string form and does not come back."
    ""
    "Both forms are read on the way in and one comes back per value. A value outside the range is"
    "REFUSED and never wrapped or clamped, and the refusal names the range."
  }

  I128(i128) : "i128" via Digits::signed, safe = safe_signed {
    "A signed 128-bit integer — `-42` as a JSON number,"
    "`\"-170141183460469231731687303715884105728\"` as decimal text."
    ""
    "HYBRID at a MAGNITUDE of 2^53 − 1, for `i64`'s reason. A leading `-` is part of the value; a"
    "leading `+` is accepted in the string form and does not come back."
    ""
    "Both forms are read on the way in and one comes back per value. A value outside the range is"
    "REFUSED and never wrapped or clamped, and the refusal names the range."
  }
}

/// Declare the async-graphql citizenship of one NUMBER-CARRIED integer — the six whose whole domain
/// a double holds exactly, so that text would buy a client nothing and cost it the arithmetic.
///
/// What these six buy is the NAME. async-graphql spells ten Rust types `Int`, so a schema built
/// through its rows cannot tell a byte from a 32-bit id, and a declaration that widened a column
/// changed no SDL at all.
macro_rules! number_integer_scalar {
  (rows = $rows:ident; $(
    $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }
  )+) => {
    builtin_reading!($( $name($domain) : $gql ),+);

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];

    $(
      $( #[doc = $doc] )+
      #[cfg(feature = "async-graphql")]
      #[async_graphql::Scalar(name = $gql)]
      impl async_graphql::ScalarType for $name {
        fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
          let async_graphql::Value::Number(ref number) = value else {
            return Err(async_graphql::InputValueError::expected_type(value));
          };
          match integral(number).and_then(|whole| <$domain>::try_from(whole).ok()) {
            Some(operand) => Ok(Self(operand)),
            None => Err(async_graphql::InputValueError::custom(format!(
              "`{number}` is not a `{}` — one crosses as a WHOLE JSON number ({} … {}), and a \
               value outside that range is refused rather than wrapped",
              $gql,
              <$domain>::MIN,
              <$domain>::MAX,
            ))),
          }
        }

        /// The SAME parser [`parse`](Self::parse) runs — see [`U64::is_valid`] for why the two
        /// halves share one notion of validity, and for the async-graphql row that does not.
        #[inline]
        fn is_valid(value: &async_graphql::Value) -> bool {
          matches!(
            value,
            async_graphql::Value::Number(number)
              if integral(number).is_some_and(|whole| <$domain>::try_from(whole).is_ok())
          )
        }

        #[inline]
        fn to_value(&self) -> async_graphql::Value {
          async_graphql::Value::Number(async_graphql::Number::from(self.0))
        }
      }
    )+
  };
}

number_integer_scalar! {
  rows = NUMBER_ROWS;

  U8(u8) : "u8" {
    "An unsigned 8-bit integer as a JSON number — `0` … `255`."
    ""
    "A NUMBER rather than text: the whole domain fits a double exactly, so there is no 2^53 to be"
    "honest about and text would cost a client the arithmetic. What the scalar carries is the"
    "WIDTH, which async-graphql's `Int` does not — it spells ten distinct Rust types."
    ""
    "A value outside the range is REFUSED and never wrapped or clamped, and so is a fraction."
  }

  U16(u16) : "u16" {
    "An unsigned 16-bit integer as a JSON number — `0` … `65535`."
    ""
    "A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
    "wrapped or clamped, and so is a fraction."
  }

  U32(u32) : "u32" {
    "An unsigned 32-bit integer as a JSON number — `0` … `4294967295`."
    ""
    "A NUMBER rather than text, for `u8`'s reason: `u32::MAX` is 2^32 − 1, twenty-one bits short"
    "of the 2^53 where a double starts dropping low bits. A value outside the range is REFUSED and"
    "never wrapped or clamped, and so is a fraction."
  }

  I8(i8) : "i8" {
    "A signed 8-bit integer as a JSON number — `-128` … `127`."
    ""
    "A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
    "wrapped or clamped, and so is a fraction."
  }

  I16(i16) : "i16" {
    "A signed 16-bit integer as a JSON number — `-32768` … `32767`."
    ""
    "A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
    "wrapped or clamped, and so is a fraction."
  }

  I32(i32) : "i32" {
    "A signed 32-bit integer as a JSON number — `-2147483648` … `2147483647`."
    ""
    "A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
    "wrapped or clamped, and so is a fraction."
  }
}

/// Declare the async-graphql citizenship of one FLOAT — the two widths that shared the name `Float`,
/// which is the SILENT half of the collision this suite exists to end.
///
/// `$narrow` reads a wire double into the row's own width and `$widen` writes one back, both as
/// PATHS rather than casts, so the lossy directions are named at [`narrowed`] and [`halved`] and the
/// other rows are `identity` and `f64::from` — conversions that cannot lose anything.
///
/// # Two public arms, because a width can be a SCALAR without being a COLUMN
///
/// `rows = …` is the ordinary one: the row joins the roster with a filter, so it mints
/// [`Builtin`]'s reading and its name derives. `lone rows = … under #[…]` is the arm for a width
/// nothing can DECLARE — [`F16`] is a wire form and no `to_filter!` row names `half::f16`, so there
/// is no filter for a derivation to have produced and the roster line says so with a `None`.
///
/// The `under` gate is the row's own second one, for [`carrier`](carrier!)'s reason at the
/// citizenship tier: a width whose OPERAND rides a feature needs `all(that feature, the binding)`,
/// and the arm already writes the binding's half. It rides the arm rather than each row because a
/// lone table is one word's worth of rows — the const it publishes has to disappear with them.
macro_rules! number_float_scalar {
  (rows = $rows:ident; $(
    $name:ident($domain:ty) : $gql:literal,
      narrow = $narrow:path, widen = $widen:path
      { $( $doc:literal )+ }
  )+) => {
    builtin_reading!($( $name($domain) : $gql ),+);

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];

    $(
      number_float_scalar!(@citizen $name($domain) : $gql,
        narrow = $narrow, widen = $widen { $( $doc )+ });
    )+
  };

  (lone rows = $rows:ident under #[$gate:meta]; $(
    $name:ident($domain:ty) : $gql:literal,
      narrow = $narrow:path, widen = $widen:path
      { $( $doc:literal )+ }
  )+) => {
    #[cfg(all(test, feature = "async-graphql"))]
    #[$gate]
    pub(crate) const $rows: &[Row] = &[ $( lone_row!($name($domain) : $gql) ),+ ];

    $(
      number_float_scalar!(@citizen #[$gate] $name($domain) : $gql,
        narrow = $narrow, widen = $widen { $( $doc )+ });
    )+
  };

  (@citizen $( #[$gate:meta] )* $name:ident($domain:ty) : $gql:literal,
      narrow = $narrow:path, widen = $widen:path
      { $( $doc:literal )+ }) => {
    $( #[doc = $doc] )+
    $( #[$gate] )*
    #[cfg(feature = "async-graphql")]
    #[async_graphql::Scalar(name = $gql)]
    impl async_graphql::ScalarType for $name {
      fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
        let async_graphql::Value::Number(ref number) = value else {
          return Err(async_graphql::InputValueError::expected_type(value));
        };
        match number.as_f64() {
          Some(wide) => Ok(Self($narrow(wide))),
          None => Err(async_graphql::InputValueError::custom(format!(
            "`{number}` is not a `{}` — one crosses as a JSON number",
            $gql,
          ))),
        }
      }

      /// The SAME reader [`parse`](Self::parse) runs — see [`U64::is_valid`].
      #[inline]
      fn is_valid(value: &async_graphql::Value) -> bool {
        matches!(value, async_graphql::Value::Number(number) if number.as_f64().is_some())
      }

      /// NaN and the two infinities have no JSON number, so a field holding one renders `null`.
      ///
      /// async-graphql's own `Float` does exactly this (`types/external/floats.rs`), and the
      /// signature admits nothing else: `to_value` answers a `Value` and has no arm to refuse in.
      fn to_value(&self) -> async_graphql::Value {
        match async_graphql::Number::from_f64($widen(self.0)) {
          Some(number) => async_graphql::Value::Number(number),
          None => async_graphql::Value::Null,
        }
      }
    }
  };
}

number_float_scalar! {
  lone rows = HALF_ROWS under #[cfg(feature = "half")];

  F16(half::f16) : "f16", narrow = halved, widen = f64::from {
    "A half-precision float as a JSON number — `0.82`, never `\"0.82\"`."
    ""
    "IEEE **binary16** — the format `half::f16` holds, one sign bit, five exponent bits and ten"
    "mantissa bits. It is NOT `bfloat16`: the two are different formats at one width, and this"
    "scalar is explicitly the IEEE one. A `BF16` scalar would be a second name for the second"
    "format, and the word is reserved for it."
    ""
    "A NUMBER and not text, for `f32`'s reason at a narrower width and with more room to spare: a"
    "JSON number IS a double to the client that reads it, and every binary16 value widens into one"
    "EXACTLY — eleven significant bits against a double's fifty-three — so there is no boundary to"
    "be honest about and no hybrid form."
    ""
    "A wire value past `f16::MAX` (65504) narrows to an infinity rather than refusing, which is the"
    "behaviour `f32` already carries for the same conversion: the scalar says what width a value is"
    "read at and does not add a range this framework would then have to defend."
    ""
    "**Behind the `half` cargo feature**, and both the type and this scalar arrive with it: a build"
    "that declares no half-precision value pays for no half-precision crate."
  }
}

number_float_scalar! {
  rows = FLOAT_ROWS;

  F32(f32) : "f32", narrow = narrowed, widen = f64::from {
    "A single-precision float as a JSON number — `0.82`, never `\"0.82\"`."
    ""
    "A NUMBER and not text, which is the one place this suite's 2^53 argument does NOT apply: a"
    "JSON number IS a double to the client that reads it, and an `f32` widens into one exactly."
    "What the scalar buys is the NAME — async-graphql publishes `f32` and `f64` both as `Float`,"
    "so two declarations measuring in the two widths were one SDL type a client could not tell"
    "apart."
    ""
    "A wire value past `f32::MAX` narrows to an infinity rather than refusing, which is"
    "async-graphql's own `Float` behaviour kept deliberately: this scalar changes what a width is"
    "called and not what it accepts."
  }

  F64(f64) : "f64", narrow = core::convert::identity, widen = core::convert::identity {
    "A double-precision float as a JSON number — `0.82`, never `\"0.82\"`."
    ""
    "A NUMBER and not text, and here the wire form and the value are the SAME object: a JSON number"
    "is a double, and so is this. Nothing is lost in either direction, so the text form the four"
    "wide integers take would be a cost with no honesty behind it."
    ""
    "What the scalar buys is the NAME — see `f32`, whose width shared this one's SDL type."
  }
}

/// One `f64` off the wire, read into the width [`F128`] holds.
///
/// [`narrowed`] and [`halved`]'s sibling in POSITION and its opposite in direction: this one WIDENS,
/// and `from_f64_retain` is the conversion that keeps the double's own value rather than rounding it
/// to a friendlier decimal. What arrives is exactly the double the client sent, which is the most a
/// number leg can honestly promise — a value a JSON number could not carry intact was already lost
/// before this crate saw it.
///
/// [`None`] where the double is a NaN or an infinity, neither of which a decimal has.
#[cfg(all(feature = "rust_decimal", feature = "async-graphql"))]
pub(crate) fn widened(wide: f64) -> Option<rust_decimal::Decimal> {
  rust_decimal::Decimal::from_f64_retain(wide)
}

/// The WIDEST float row's citizenship, and the second table of one — [`bytes_scalar!`]'s shape, for
/// its reason: `$gql` reaches a `#[Scalar]` attribute, so the literal and everything derived from it
/// have to sit inside one expansion.
///
/// It is written out rather than taken from [`number_float_scalar!`]'s `lone` arm because the wire
/// FORM is different in kind: the float arm's rows cross as JSON numbers and this one crosses as
/// DECIMAL TEXT, so `parse`, `is_valid` and `to_value` are three different bodies rather than three
/// different paths through one.
///
/// # No `ScalarWire` row, like [`F16`]
///
/// Nothing can DECLARE a column of this width — `to_filter!` names neither operand — so the roster
/// line carries a `None` where a filter name would be and this macro mints no reading. A width is a
/// wire form first; a column type is a second decision, and it is not this round's.
#[cfg(feature = "rust_decimal")]
macro_rules! decimal_scalar {
  (rows = $rows:ident; $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
    $( #[doc = $doc] )+
    #[cfg(feature = "async-graphql")]
    #[async_graphql::Scalar(name = $gql)]
    impl async_graphql::ScalarType for $name {
      fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
        if let Some(digits) = text(&value) {
          return match <$domain>::from_str_exact(digits) {
            Ok(operand) => Ok(Self(operand)),
            Err(error) => Err(async_graphql::InputValueError::custom(format!(
              "`{digits}` is not an `{}` — a string operand is DECIMAL TEXT inside \
               `{}` … `{}`, and this one is refused: {error}",
              $gql,
              <$domain>::MIN,
              <$domain>::MAX,
            ))),
          };
        }
        // THE NUMBER LEG, and it is liberal for the hybrid integers' reason: a client that has only
        // ever sent JSON numbers keeps working. What it gets is the DOUBLE's own value — a number
        // wider than a double had already lost its low bits before this crate saw it — so the leg
        // promises exactness about the wire value and never about the value the client meant.
        if let async_graphql::Value::Number(ref number) = value {
          return match number.as_f64().and_then(widened) {
            Some(operand) => Ok(Self(operand)),
            None => Err(async_graphql::InputValueError::custom(format!(
              "`{number}` is not an `{}` — a JSON number crosses inside `{}` … `{}` and cannot be a \
               NaN or an infinity, and a value needing more than a double's precision is written as \
               DECIMAL TEXT instead, which is exact in both directions",
              $gql,
              <$domain>::MIN,
              <$domain>::MAX,
            ))),
          };
        }
        Err(async_graphql::InputValueError::expected_type(value))
      }

      /// The SAME readers [`parse`](Self::parse) runs — see [`U64::is_valid`] for why the two halves
      /// share one notion of validity.
      #[inline]
      fn is_valid(value: &async_graphql::Value) -> bool {
        if let Some(digits) = text(value) {
          return <$domain>::from_str_exact(digits).is_ok();
        }
        matches!(
          value,
          async_graphql::Value::Number(number)
            if number.as_f64().and_then(widened).is_some()
        )
      }

      /// DECIMAL TEXT at every magnitude, and no number leg on the way out.
      ///
      /// The hybrid integers fork at 2^53 − 1 because below it a JSON number is exact AND useful to
      /// a client's arithmetic. There is no such range here: the operand is a base-ten value with a
      /// scale, and handing back `0.1` as a double would hand back a value that is not `0.1`. So the
      /// encode side is the exact form always, which is what the widest row is for.
      fn to_value(&self) -> async_graphql::Value {
        async_graphql::Value::String(self.0.to_string())
      }
    }

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const $rows: &[Row] = &[lone_row!($name($domain) : $gql)];
  };
}

#[cfg(feature = "rust_decimal")]
decimal_scalar! {
  rows = DECIMAL_ROWS;

  F128(rust_decimal::Decimal) : "f128" {
    "The widest float row, as DECIMAL TEXT — `\"0.1\"`, never `0.1`."
    ""
    "**IT IS NOT IEEE binary128, and the backing is TEMPORARY.** `f128` is the name the roster gives"
    "the widest float row; Rust's own `f128` is not stable, so the seat is held by"
    "`rust_decimal::Decimal` — a 96-bit mantissa under a base-ten scale, roughly 28 significant"
    "DECIMAL digits over ±7.9e28, where binary128 is a 113-bit significand over a binary exponent"
    "reaching ±1.2e4932. A client should read this scalar as *an exact decimal wider than a double*"
    "and not as a binary float of any width. **Behind the `rust_decimal` cargo feature.**"
    ""
    "TEXT in both directions on the way out, where the four wide integers fork at 2^53 − 1. The fork"
    "buys a client arithmetic on the values below the bound; there is no such range here, because"
    "the operand is base-ten and `0.1` has no double that IS it. So the exact form is the only form"
    "returned."
    ""
    "A JSON NUMBER is read on the way in — Postel's half, as at every hybrid width — and what it"
    "carries is the DOUBLE's own value. A number needing more precision than a double has already"
    "lost it before this crate sees it, so the number leg is exact about the wire value and says"
    "nothing about the value a client meant; a client that wants what it meant writes the text."
    ""
    "A string is DECIMAL TEXT and is read EXACTLY: excess precision is refused rather than rounded"
    "away, which is what `from_str_exact` buys over the rounding parse beside it. A value outside"
    "the range is refused, and so are a NaN and an infinity — a decimal has neither."
  }
}

/// The BLOB's row — the citizenship, [`Builtin`]'s byte reading, and the roster line, all out of one
/// scalar literal.
///
/// A macro for a table of ONE, and the reason is the same one the three numeric tables have: `$gql`
/// has to reach a `#[Scalar]` ATTRIBUTE, whose arguments no macro expands, so the only way the
/// filter name can be derived from the scalar name is for both to be inside one expansion. The
/// row this replaced spelled `"HexBytes"` in this file and `"BytesFilter"` in
/// [`carrier`](super::carrier), which under the derivation law is one name written twice.
///
/// The BYTES reading is keyed on the operand and not on the byte WIDTH — see
/// [`BytesWire`](super::carrier::BytesWire), where what that costs is stated.
macro_rules! bytes_scalar {
  // THE ROSTER ROW — the skin arm plus the roster line, which only the DEFAULT household has.
  (roster $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
    bytes_scalar!($name($domain) : $gql { $( $doc )+ });

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const BYTES_ROWS: &[Row] = &[Row {
      rust: stringify!($domain),
      scalar: $gql,
      filter: Some(derived_filter!($gql)),
      scalar_face: || <$name as async_graphql::InputType>::type_name().into_owned(),
      filter_face: Some(|| {
        <crate::BytesFilter<$domain> as async_graphql::InputType>::type_name().into_owned()
      }),
    }];
  };

  ($name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
    $( #[doc = $doc] )+
    #[cfg(feature = "async-graphql")]
    #[async_graphql::Scalar(name = $gql)]
    impl async_graphql::ScalarType for $name {
      fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
        let Some(hex) = text(&value) else {
          return Err(async_graphql::InputValueError::expected_type(value));
        };
        match read_hex(hex) {
          Some(bytes) => Ok(Self(bytes)),
          None => Err(async_graphql::InputValueError::custom(format!(
            "`{hex}` is not a byte string — bytes cross as an EVEN number of hex digits, two per \
             byte (`\"89504e47\"`), optionally under a `0x` prefix"
          ))),
        }
      }

      /// The same reader [`parse`](Self::parse) runs — see [`U64::is_valid`].
      #[inline]
      fn is_valid(value: &async_graphql::Value) -> bool {
        matches!(text(value), Some(hex) if read_hex(hex).is_some())
      }

      fn to_value(&self) -> async_graphql::Value {
        let mut hex = String::with_capacity(self.0.len() * 2);
        for byte in &self.0 {
          hex.push_str(nibbles(*byte).as_str());
        }
        async_graphql::Value::String(hex)
      }
    }

    // The row's own reading, under the DERIVED name — `UpperCamel("bytes") + "Filter"`, which is
    // `BytesFilter`, and which this row holds because the default byte household swapped on
    // 2026-08-18. The two legs go through `Vec<u8>` because the carrier is a blob and the operand is
    // whatever byte type the roster's row names; `Vec<u8>` itself is a NAMED vocabulary now and
    // takes its row beside the others, in `carrier`.
    impl BytesWire<$domain> for Builtin {
      const NAME: &'static str = derived_filter!($gql);

      type Carrier = $name;
      type Error = Infallible;

      #[inline]
      fn cross(carrier: $name) -> Result<$domain, Infallible> {
        Ok(<$domain>::from(::std::vec::Vec::from(carrier)))
      }

      #[inline]
      fn carry(operand: &$domain) -> $name {
        <$name>::from(<$domain as ::core::convert::AsRef<[u8]>>::as_ref(operand).to_vec())
      }
    }

  };
}

bytes_scalar! {
  roster HexBytes(::bytes::Bytes) : "bytes" {
    "A byte string as lowercase hexadecimal — `\"89504e470d0a1a0a\"`, two characters per byte."
    ""
    "An EVEN number of hex digits, `0`–`9` and `a`–`f`. Uppercase is accepted and a `0x` prefix is"
    "accepted; neither comes back — the rendered form is always lowercase and unprefixed, so"
    "`parse(render(b)) == b` holds while `render(parse(t))` is the CANONICAL spelling of `t` rather"
    "than `t` itself."
    ""
    "Hex rather than base64, and the reason is the operators this operand is written for. A byte"
    "column's filter carries `contains`/`notContains` over byte SUBSTRINGS, and the values a caller"
    "has to hand — a checksum, a magic number, a content id — are written in hex everywhere else"
    "they appear. Base64 is denser, and its three-byte grouping means no prefix of the encoded text"
    "is a prefix of the bytes, so a client would be composing substring operands in a form it cannot"
    "read."
    ""
    "**The name is the ROSTER's, and the encoding is this carrier's** — `bytes` is what the"
    "framework's DEFAULT blob operand publishes, and that operand is `bytes::Bytes`. Every OTHER"
    "byte vocabulary crosses in this same lowercase hex and under a scalar of its OWN name, so a"
    "`U8VectorFilter`'s `eq` reads `U8Vector` and never `bytes`. The grammar is one grammar — every"
    "skin parses and renders through `read_hex` and `nibbles`, which are written once."
  }
}

carrier!(
  U8Vector(Vec<u8>),
  "A `Vec<u8>` column's bytes — lowercase hexadecimal, two characters per byte."
);

bytes_scalar! {
  U8Vector(Vec<u8>) : "U8Vector" {
    "A `Vec<u8>` column, as lowercase hexadecimal — two characters per byte."
    ""
    "The grammar is `bytes`': an EVEN number of hex digits, either case, optionally `0x`-prefixed,"
    "rendered back lowercase and unprefixed. It is not a second grammar and cannot become one —"
    "every byte scalar in this schema is a thin skin over ONE reader and ONE renderer."
    ""
    "**A SCALAR OF ITS OWN, and the name is the point.** Every byte vocabulary crossed under the"
    "roster's `bytes` until 2026-08-19, so a schema published `U8VectorFilter { eq: bytes }` — an"
    "input object naming one household whose operand named another. A reader had to know that the"
    "two words described one wire form to read it as anything but a mistake. The wire form is still"
    "one; what each household publishes now is its own name for it."
  }
}

carrier!(
  SmolBytes(Vec<u8>),
  "A `smol_bytes::Bytes` column's bytes — lowercase hexadecimal, two characters per byte."
);

bytes_scalar! {
  SmolBytes(::smol_bytes::Bytes) : "SmolBytes" {
    "The `smol-bytes` blob vocabulary, as lowercase hexadecimal — two characters per byte."
    ""
    "`bytes`' grammar and `bytes`' reader — see [`U8Vector`] for why the household has a scalar of"
    "its own rather than sharing the roster's."
    ""
    "ONE name for the crate's whole immutable byte household: `smol_bytes::Bytes` is the root"
    "re-export of `shared::Bytes`, and the compact strategy beside it is an allocation choice rather"
    "than a wire form, so it publishes nothing of its own."
  }
}

/// The FIXED-WIDTH byte vocabulary's carrier — one type per WIDTH, and one scalar per width with it.
///
/// # The name is ASSEMBLED, which is why this row is written out
///
/// `#[async_graphql::Scalar(name = …)]` takes a LITERAL, and `Fixed{N}U8Array` is not one: the width
/// is a const parameter, so the name has to be built where `N` is in scope. That is the same shape
/// [`FixedBytesFilter`](crate::FixedBytesFilter) already assembles its own name in — `Fixed{N}` in
/// front of the reading's — so the operand and its filter decorate identically and neither writes a
/// literal per width.
///
/// It holds a `Vec<u8>` and NOT a `[u8; N]`, which keeps the width check where its refusal already
/// is: `BytesWire<[u8; N]>::cross` answers `WrongByteWidth` naming both numbers, and a carrier that
/// refused at parse time would answer the same question in the scalar's voice instead.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FixedU8Array<const N: usize>(Vec<u8>);

impl<const N: usize> From<Vec<u8>> for FixedU8Array<N> {
  #[inline]
  fn from(bytes: Vec<u8>) -> Self {
    Self(bytes)
  }
}

impl<const N: usize> From<FixedU8Array<N>> for Vec<u8> {
  #[inline]
  fn from(carrier: FixedU8Array<N>) -> Self {
    carrier.0
  }
}

/// The SDL name this width publishes — `Fixed16U8Array` at sixteen bytes.
#[cfg(feature = "async-graphql")]
fn fixed_u8_array_name<const N: usize>() -> std::borrow::Cow<'static, str> {
  std::borrow::Cow::Owned(std::format!("Fixed{N}U8Array"))
}

#[cfg(feature = "async-graphql")]
impl<const N: usize> async_graphql::ScalarType for FixedU8Array<N> {
  fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
    let Some(hex) = text(&value) else {
      return Err(async_graphql::InputValueError::expected_type(value));
    };
    match read_hex(hex) {
      Some(bytes) => Ok(Self(bytes)),
      None => Err(async_graphql::InputValueError::custom(format!(
        "`{hex}` is not a byte string — bytes cross as an EVEN number of hex digits, two per byte \
         (`\"89504e47\"`), optionally under a `0x` prefix"
      ))),
    }
  }

  #[inline]
  fn is_valid(value: &async_graphql::Value) -> bool {
    matches!(text(value), Some(hex) if read_hex(hex).is_some())
  }

  fn to_value(&self) -> async_graphql::Value {
    let mut hex = String::with_capacity(self.0.len() * 2);
    for byte in &self.0 {
      hex.push_str(nibbles(*byte).as_str());
    }
    async_graphql::Value::String(hex)
  }
}

// THE TWO FACES, written out for the reason the carrier is: `#[Scalar]` cannot expand over a const
// parameter, so what the attribute would have generated is here verbatim, with the ONE difference
// that earns the file — `type_name` assembles rather than borrows a literal.
//
// The bodies are the attribute's own, delegating to the `ScalarType` above; nothing here decides
// anything the macro would not have.
#[cfg(feature = "async-graphql")]
impl<const N: usize> async_graphql::InputType for FixedU8Array<N> {
  type RawValueType = Self;

  fn type_name() -> std::borrow::Cow<'static, str> {
    fixed_u8_array_name::<N>()
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
    registry.create_input_type::<Self, _>(async_graphql::registry::MetaTypeId::Scalar, |_| {
      fixed_u8_array_meta::<N>()
    })
  }

  fn parse(value: Option<async_graphql::Value>) -> async_graphql::InputValueResult<Self> {
    <Self as async_graphql::ScalarType>::parse(value.unwrap_or_default())
  }

  fn to_value(&self) -> async_graphql::Value {
    <Self as async_graphql::ScalarType>::to_value(self)
  }

  fn as_raw_value(&self) -> Option<&Self::RawValueType> {
    Some(self)
  }
}

#[cfg(feature = "async-graphql")]
impl<const N: usize> async_graphql::OutputType for FixedU8Array<N> {
  fn type_name() -> std::borrow::Cow<'static, str> {
    fixed_u8_array_name::<N>()
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
    registry.create_output_type::<Self, _>(async_graphql::registry::MetaTypeId::Scalar, |_| {
      fixed_u8_array_meta::<N>()
    })
  }

  async fn resolve(
    &self,
    _: &async_graphql::ContextSelectionSet<'_>,
    _field: &async_graphql::Positioned<async_graphql::parser::types::Field>,
  ) -> async_graphql::ServerResult<async_graphql::Value> {
    Ok(<Self as async_graphql::ScalarType>::to_value(self))
  }
}

/// ONE width's registry entry, shared by the two faces so a name can only be built one way.
#[cfg(feature = "async-graphql")]
fn fixed_u8_array_meta<const N: usize>() -> async_graphql::registry::MetaType {
  async_graphql::registry::MetaType::Scalar {
    name: fixed_u8_array_name::<N>().into_owned(),
    description: Some(std::format!(
      "A {N}-byte column, as lowercase hexadecimal — exactly {} characters. A value of any other \
       width is refused, naming both numbers, rather than padded or truncated.",
      N * 2
    )),
    is_valid: Some(std::sync::Arc::new(|value| {
      <FixedU8Array<N> as async_graphql::ScalarType>::is_valid(value)
    })),
    visible: None,
    inaccessible: false,
    tags: Vec::new(),
    specified_by_url: None,
    directive_invocations: Vec::new(),
    requires_scopes: Vec::new(),
  }
}

carrier!(
  NetIpv4Addr(::std::net::Ipv4Addr),
  "An IPv4 address on the wire — the dotted quad, `\"192.0.2.1\"`."
);

carrier!(
  NetIpv6Addr(::std::net::Ipv6Addr),
  "An IPv6 address on the wire — RFC 5952 canonical text, `\"2001:db8::1\"`."
);

carrier!(
  NetIpAddr(::std::net::IpAddr),
  "An IP address of EITHER version on the wire — whichever version's own canonical text."
);

carrier!(
  NetSocketAddrV4(::std::net::SocketAddrV4),
  "An IPv4 address and a port on the wire — `\"192.0.2.1:443\"`."
);

carrier!(
  NetSocketAddrV6(::std::net::SocketAddrV6),
  "An IPv6 address and a port on the wire — `\"[2001:db8::1]:443\"`, the address bracketed."
);

carrier!(
  NetSocketAddr(::std::net::SocketAddr),
  "An address and a port of EITHER version on the wire — whichever version's own canonical text."
);

carrier!(
  HyphenatedUuid(::uuid::Uuid),
  "A UUID on the wire — the canonical lowercase hyphenated text, \
   `\"018f3a2b-7c4d-7e1f-9a0b-1c2d3e4f5061\"`."
);

/// Declare the async-graphql citizenship of one PARSED TEXT vocabulary — a named type whose value
/// has exactly ONE canonical spelling, written by the operand's own [`Display`] and read back by the
/// operand's own `FromStr`.
///
/// `$gql` is the SDL name, `$grammar` the clause a refusal repairs with, and the braced literals the
/// scalar's own DESCRIPTION. The name is a LITERAL for [`hybrid_integer_scalar!`]'s reason — it has
/// to reach a `#[Scalar]` ATTRIBUTE, whose arguments no macro expands — and it is the same literal
/// the row's filter name is DERIVED from, so the two cannot drift.
///
/// # THE GRAMMAR IS SOMEBODY ELSE'S, and that is the whole argument for the arm
///
/// Every row here names a type whose `Display` and `FromStr` are a MATCHED PAIR ITS OWN CRATE
/// MAINTAINS: `Ipv4Addr` writes the dotted quad and reads one, `Ipv6Addr` writes RFC 5952 canonical
/// text — the longest zero run compressed, lowercase, no leading zeros — and reads every spelling
/// RFC 4291 admits; [`uuid::Uuid`] writes the RFC 9562 lowercase hyphenated form and reads that, the
/// simple, the braced and the URN. So `parse(render(v)) == v` holds by the operand's own contract,
/// and `render(parse(t))` is the CANONICAL spelling of `t` rather than `t` itself, which is exactly
/// the promise the byte households make about hex.
///
/// Writing a grammar of this crate's own instead would have been a second parser for a text form
/// somebody else already defines, and the two would disagree the first time either moved. The six
/// address rows were the arm's only users while every row was `std`'s; the `uuid` row is what proved
/// the argument was never about `std` but about who OWNS the spelling.
///
/// # No hybrid leg, and no NUMBER leg at all
///
/// An address IS its text. The four wide integers fork at [`SAFE`] because below it a JSON number is
/// exact AND useful to a client's arithmetic; there is no arithmetic here to buy, and the integer a
/// v4 address could be packed into is a form no client writes an address in. A wire value that is
/// not a string is refused as the wrong type.
macro_rules! parsed_text_scalar {
  (rows = $rows:ident; $(
    $name:ident($domain:ty) : $gql:literal, grammar = $grammar:literal
      { $( $doc:literal )+ }
  )+) => {
    builtin_reading!($( $name($domain) : $gql ),+);

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];

    $(
      $( #[doc = $doc] )+
      #[cfg(feature = "async-graphql")]
      #[async_graphql::Scalar(name = $gql)]
      impl async_graphql::ScalarType for $name {
        fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
          let Some(spelling) = text(&value) else {
            return Err(async_graphql::InputValueError::expected_type(value));
          };
          match spelling.parse::<$domain>() {
            Ok(operand) => Ok(Self(operand)),
            // The standard library's own refusal is DISCARDED and this sentence written instead:
            // `AddrParseError` renders *invalid IP address syntax* and names neither the scalar that
            // refused nor the form a repair takes, which are the two facts a client can act on.
            //
            // *`{gql}` text* rather than *an `{gql}`*, which is the one place the article would have
            // had to vary per row: `an Ipv4Addr` and `a SocketAddrV4` are not one sentence, and a
            // second literal per row for a grammatical article is a literal.
            Err(_) => Err(async_graphql::InputValueError::custom(format!(
              "`{spelling}` is not `{}` text — one crosses as {}, and a spelling outside that \
               grammar is REFUSED and never guessed at",
              $gql, $grammar,
            ))),
          }
        }

        /// The SAME parser [`parse`](Self::parse) runs, which is what makes a document that
        /// validates a document that parses — see [`U64::is_valid`] for the async-graphql row that
        /// does not.
        #[inline]
        fn is_valid(value: &async_graphql::Value) -> bool {
          matches!(text(value), Some(spelling) if spelling.parse::<$domain>().is_ok())
        }

        /// The operand's own CANONICAL spelling, which is what makes the round trip a fixed point.
        fn to_value(&self) -> async_graphql::Value {
          async_graphql::Value::String(self.0.to_string())
        }
      }
    )+
  };
}

parsed_text_scalar! {
  rows = NET_ROWS;

  NetIpv4Addr(::std::net::Ipv4Addr) : "Ipv4Addr", grammar = "the DOTTED QUAD — four decimal octets \
    under three dots, as in `\"192.0.2.1\"`" {
    "An IPv4 address as the DOTTED QUAD — `\"192.0.2.1\"`, never a packed integer."
    ""
    "Four decimal octets under three dots, each `0` … `255`. A LEADING ZERO is refused rather than"
    "read — `\"01.2.3.4\"` is not an address — which is the standard library's own rule and the right"
    "one: a leading zero means octal in some resolvers and decimal in others, so the same text names"
    "two hosts."
    ""
    "**A NAMED TYPE and not a roster width**, so the scalar is Pascal and its filter derives from it:"
    "`Ipv4AddrFilter`. The four-byte integer an address packs into is a REPRESENTATION and not a"
    "spelling — no client writes one, and a `u32` column already publishes that form under its own"
    "name."
    ""
    "A value outside the grammar is REFUSED and never guessed at; so is a JSON number, which is a"
    "value of the wrong type rather than a badly spelled address."
  }

  NetIpv6Addr(::std::net::Ipv6Addr) : "Ipv6Addr", grammar = "RFC 4291 TEXT — up to eight \
    colon-separated hextets, with at most one `::` run, as in `\"2001:db8::1\"`" {
    "An IPv6 address as RFC 5952 CANONICAL text — `\"2001:db8::1\"`."
    ""
    "Every spelling RFC 4291 admits is READ: upper or lower case, leading zeros, a `::` run anywhere,"
    "and the embedded-IPv4 tail. What comes BACK is the RFC 5952 canonical form and only that — the"
    "longest run of zero hextets compressed to `::`, lowercase, no leading zeros — so"
    "`\"2001:0DB8:0000:0000:0000:0000:0000:0001\"` is read and renders as `\"2001:db8::1\"`. An"
    "IPv4-mapped address keeps its dotted tail (`\"::ffff:192.0.2.1\"`), which is RFC 5952's own"
    "exception."
    ""
    "So `parse(render(a)) == a` holds always, and `render(parse(t))` is the CANONICAL spelling of `t`"
    "rather than `t` itself — the same promise the byte households make about hex."
    ""
    "A spelling outside the grammar is REFUSED and never guessed at."
  }

  NetIpAddr(::std::net::IpAddr) : "IpAddr", grammar = "an IPv4 DOTTED QUAD or an RFC 4291 IPv6 \
    text, as in `\"192.0.2.1\"` or `\"2001:db8::1\"`" {
    "An IP address of EITHER version — `\"192.0.2.1\"` or `\"2001:db8::1\"`."
    ""
    "**UNTAGGED**: the version is read off the spelling and never written beside it. Both are parsed"
    "on the way in, and what comes back is the canonical text of whichever version the value holds —"
    "the dotted quad for a v4 and the RFC 5952 form for a v6, exactly as [`Ipv4Addr`](NetIpv4Addr)"
    "and [`Ipv6Addr`](NetIpv6Addr) render their own."
    ""
    "A column that must be one version names that version's scalar instead, where the wrong version"
    "is refused at the parse rather than stored. This one is the column that holds either."
    ""
    "A spelling that is neither version is REFUSED and never guessed at."
  }

  NetSocketAddrV4(::std::net::SocketAddrV4) : "SocketAddrV4", grammar = "a DOTTED QUAD under a \
    colon and a port, as in `\"192.0.2.1:443\"`" {
    "An IPv4 address and a port — `\"192.0.2.1:443\"`."
    ""
    "The address is [`Ipv4Addr`](NetIpv4Addr)'s dotted quad and the port is a decimal `0` … `65535`,"
    "separated by a colon. Both halves are part of the value: a spelling with no port is not a socket"
    "address and is REFUSED rather than defaulted to zero."
  }

  NetSocketAddrV6(::std::net::SocketAddrV6) : "SocketAddrV6", grammar = "a BRACKETED IPv6 text \
    under a colon and a port, as in `\"[2001:db8::1]:443\"`" {
    "An IPv6 address and a port — `\"[2001:db8::1]:443\"`, the address bracketed."
    ""
    "The brackets are what make the port unambiguous: an IPv6 text is full of colons, so the address"
    "is delimited before the last one can be read as a separator. The address inside them is"
    "[`Ipv6Addr`](NetIpv6Addr)'s, read in every spelling and rendered canonical."
    ""
    "**A SCOPE ID crosses and a FLOWINFO does not**, and that is the operand's own `Display` rather"
    "than a choice made here. A non-zero scope is written and read back — `\"[fe80::1%3]:443\"` — and"
    "the flow label has no place in the text form at all, so a value carrying one renders without it"
    "and comes back as zero. Stated because it is the one row in this family whose round trip is not"
    "the identity on every value: a column that has to keep a flow label is not a column this scalar"
    "can hold."
  }

  NetSocketAddr(::std::net::SocketAddr) : "SocketAddr", grammar = "a DOTTED QUAD or a BRACKETED \
    IPv6 text under a colon and a port, as in `\"192.0.2.1:443\"` or `\"[2001:db8::1]:443\"`" {
    "An address and a port of EITHER version — `\"192.0.2.1:443\"` or `\"[2001:db8::1]:443\"`."
    ""
    "**UNTAGGED**, for [`IpAddr`](NetIpAddr)'s reason and with its shape: both forms are read, and"
    "what comes back is the canonical text of whichever version the value holds. The v6 half carries"
    "[`SocketAddrV6`](NetSocketAddrV6)'s scope-id note with it."
  }
}

// THE UUID, on the address family's own terms and through the same macro. It is the second user of
// `parsed_text_scalar!` and the first from outside `std`, which is what makes the pair-maintained
// argument above worth reading twice: `uuid`'s `Display` and `FromStr` are a matched pair the uuid
// crate maintains, exactly as `std::net`'s are one the standard library maintains, so the grammar is
// still SOMEBODY ELSE'S and still not a second parser written here.
//
// WHY IT IS TEXT AND NOT HEX. The byte households already publish a sixteen-byte column as bare
// lowercase hex, so `Fixed16U8Array` is a form this wire has. A uuid is not that column: the
// hyphenated rendering is the form every client library, every log line and every URL already
// carries, and RFC 9562 defines it. Publishing the naked hex would have made a client strip and
// reinsert four hyphens to talk to anything else it owns.
//
// The STORED form is a different question and is answered per backend — sixteen raw bytes in a
// `uuid`, a `binary(16)`, a `BLOB` or a subtype-4 `BinData`; see `column::stored`. Wire text and
// binary storage is the arrangement this crate wanted all along and could not have while the type
// had no column rows: text where a human reads it, bytes where an index does.
parsed_text_scalar! {
  rows = UUID_ROWS;

  HyphenatedUuid(::uuid::Uuid) : "Uuid", grammar = "the CANONICAL HYPHENATED form — 32 hexadecimal \
    digits in 8-4-4-4-12 groups, as in `\"018f3a2b-7c4d-7e1f-9a0b-1c2d3e4f5061\"`" {
    "A UUID as the CANONICAL LOWERCASE HYPHENATED text —"
    "`\"018f3a2b-7c4d-7e1f-9a0b-1c2d3e4f5061\"`, the form RFC 9562 defines and every client library"
    "already speaks."
    ""
    "**Every spelling the `uuid` crate parses is READ** — hyphenated, the unhyphenated 32-digit"
    "simple form, the braced Microsoft GUID `{…}` and the `urn:uuid:…` URN — in either case. What"
    "comes BACK is the lowercase hyphenated form and only that, so a round trip through this scalar"
    "CANONICALISES, which is the promise the address family makes about RFC 5952 and the byte"
    "households make about hex."
    ""
    "**A NAMED TYPE and not a roster width**, so the scalar is Pascal and its filter derives from it:"
    "`UuidFilter`. `Uuid` rather than `UUID` for the register's own reason — `Ipv4Addr` and"
    "`SocketAddrV6` are Rust-flavoured Pascal and not acronym shouts, and `UpperCamel` on a name"
    "already capital is that name, so one literal spells both."
    ""
    "**NO VERSION IS REQUIRED and none is refused.** A v4, a v7, a nil and a max are all UUIDs and"
    "this scalar reads them all: a version check is a fact about where a value CAME FROM, which a"
    "grammar cannot state and a constructor can. What ORDER means for a column of them is a storage"
    "question — see `column::stored`, where the bytewise order every backend agrees on is recorded,"
    "and where a v7's leading timestamp is what makes that order a time order."
    ""
    "The sixteen BYTES are what a column holds; this is what a client writes. A value outside the"
    "grammar is REFUSED and never guessed at, and so is a JSON number."
  }
}

// THE COMPILED PATTERN, and the FIRST row in this file whose crossing is a COMPILE rather than a
// parse of a fixed grammar.
//
// It is written out rather than taken from `parsed_text_scalar!` above, and the reason is the
// REFUSAL. That arm discards the operand's own error and writes one sentence of its own, which is
// right where the discarded error is `AddrParseError`'s *invalid IP address syntax* — a sentence
// naming neither the scalar nor the repair. `regex::Error` is the opposite kind of error: it names
// the offending span, quotes it, and says which rule it broke — *regex parse error: (?P<>  ^ error:
// empty capture group name* — and a client writing a pattern can act on nothing else. So the arm's
// one improvement would here be a loss, and the row carries the engine's sentence through.
//
// WHY IT IS TEXT AND WHY THE TEXT IS THE PATTERN. A `Regex` IS its pattern: `Display` writes it,
// `FromStr` reads it, and `Regex::new(r.as_str())` rebuilds the value. The automaton is a build
// product of that text — bigger than it, machine-specific in its layout, and meaningless to a client
// — so there is nothing else a wire form could honestly carry. That is also what the STORED form
// carries; see `column::stored`, where the pattern takes `TEXT` on every dialect and
// `column::assemble`, where reading it back is this same compile with a named refusal.
//
// **THE ROUND TRIP IS THE IDENTITY ON THE TEXT AND SAYS NOTHING ABOUT THE VALUE**, which is where
// this row parts from every other in the file. `render(parse(t))` is `t` exactly — `regex` keeps the
// pattern verbatim and canonicalises nothing, so unlike a uuid or an RFC 5952 address this scalar
// does not fold spellings together: `(?i)a` and `[aA]` are two values here and two rows in a column.
// `parse(render(v)) == v` cannot even be WRITTEN, the operand having no `PartialEq`; what holds in
// its place is that the two compile from one text, which is the whole of what a pattern column
// promises.
carrier!(
  #[cfg(feature = "regex")]
  bare RegexPattern(::regex::Regex),
  "A regular expression on the wire — its PATTERN, verbatim, `\"^[a-z]+(?:-[0-9]+)?$\"`."
);

/// The pattern scalar's citizenship, `builtin_reading!`'s filter name, and the roster line — all out
/// of ONE scalar literal, which is the shape `decimal_scalar!` and `bytes_scalar!` take and for
/// their reason: `$gql` has to reach a `#[Scalar]` ATTRIBUTE, whose arguments no macro expands, so
/// the only way `RegexFilter` can be DERIVED from `Regex` is for both to sit inside one expansion.
///
/// A macro for a table of one. It is a macro anyway rather than three items written out, because
/// what would otherwise be written out is the derivation itself — and a scalar name spelled twice is
/// exactly the state the constitution's first law exists to make unreachable.
#[cfg(feature = "regex")]
macro_rules! regex_scalar {
  (rows = $rows:ident; $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
    builtin_reading!($name($domain) : $gql);

    $( #[doc = $doc] )+
    #[cfg(feature = "async-graphql")]
    #[async_graphql::Scalar(name = $gql)]
    impl async_graphql::ScalarType for $name {
      fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
        let Some(pattern) = text(&value) else {
          return Err(async_graphql::InputValueError::expected_type(value));
        };
        match <$domain>::new(pattern) {
          Ok(operand) => Ok(Self(operand)),
          // THE ENGINE'S OWN SENTENCE, carried rather than replaced — see this row's note. It is
          // multi-line and that is deliberate: `regex` renders a caret under the offending span, and
          // a client that reads the message gets the column the pattern broke at.
          Err(error) => Err(async_graphql::InputValueError::custom(format!(
            "`{pattern}` is not `{}` text — a pattern crosses as the expression itself and is \
             COMPILED on the way in, and this one does not compile: {error}",
            $gql,
          ))),
        }
      }

      /// The SAME compile [`parse`](Self::parse) runs, so a document that validates is a document
      /// that parses — the promise every row in this file makes, and the one that costs most here:
      /// validating a pattern IS building its automaton, and the built one is discarded.
      ///
      /// It is paid rather than avoided because the alternative is a second, weaker grammar written
      /// by hand, which would admit patterns the parse then refuses — the exact disagreement
      /// [`U64::is_valid`] records the framework refusing to have.
      #[inline]
      fn is_valid(value: &async_graphql::Value) -> bool {
        matches!(text(value), Some(pattern) if <$domain>::new(pattern).is_ok())
      }

      /// The PATTERN, verbatim — `as_str` hands back the very text the value was compiled from, so
      /// this allocates one `String` and canonicalises nothing.
      fn to_value(&self) -> async_graphql::Value {
        async_graphql::Value::String(self.0.as_str().to_owned())
      }
    }

    #[cfg(all(test, feature = "async-graphql"))]
    pub(crate) const $rows: &[Row] = &[filtered_row!($name($domain) : $gql)];
  };
}

#[cfg(feature = "regex")]
regex_scalar! {
  rows = REGEX_ROWS;

  RegexPattern(::regex::Regex) : "Regex" {
    "A regular expression as its PATTERN — `\"^[a-z]+(?:-[0-9]+)?$\"`, the expression itself and"
    "never a description of one."
    ""
    "**IT IS COMPILED ON THE WAY IN, and a pattern that does not compile is REFUSED with the"
    "engine's own sentence.** The refusal names the offending span and the rule it broke, because"
    "that is the only thing a client writing a pattern can act on; nothing is guessed at and no"
    "pattern is repaired."
    ""
    "**The dialect is the `regex` crate's**, which is Rust's leading-crate syntax and NOT PCRE: there"
    "is no backreference and no lookaround, every pattern runs in time linear in the haystack, and"
    "case-insensitivity and multi-line reading are written INSIDE the expression as `(?i)` and"
    "`(?m)` rather than beside it as flags. A pattern that needs a backreference is not a pattern"
    "this column can hold, and it is refused at the wire rather than stored and failed later."
    ""
    "**A NAMED TYPE and not a roster width**, so the scalar is Pascal and its filter derives from it:"
    "`RegexFilter`."
    ""
    "**The round trip is the identity on the TEXT.** What comes back is the pattern that went in,"
    "character for character — this scalar canonicalises nothing, unlike [`Uuid`](HyphenatedUuid)"
    "and the address family, because a pattern has no canonical spelling: `(?i)a` and `[aA]` accept"
    "the same strings and are two different values here, two different rows in a column, and two"
    "different answers to `eq`."
    ""
    "**Comparison is over the PATTERN and never over what it MATCHES.** `eq`, the ordering"
    "operators and `in` all ask about the expression as text — which pattern is stored — and no"
    "operator anywhere asks a stored pattern to match a string. That question belongs to whatever"
    "runs the pattern, which is the declaring application and not the store."
    ""
    "A value outside the dialect is REFUSED and never guessed at, and so is a JSON number, which is"
    "a value of the wrong type rather than a badly written pattern."
  }
}

/// One byte's two hex digits, high first, in a two-byte stack buffer.
///
/// A tiny [`Digits`]: the same trade, at the size a byte needs. Rendering through `write!("{:02x}")`
/// would enter the formatting machinery once per byte of a blob.
fn nibbles(byte: u8) -> Digits {
  let mut buffer = [0u8; Digits::WIDTH];
  buffer[Digits::WIDTH - 2] = HEX[usize::from(byte >> 4)];
  buffer[Digits::WIDTH - 1] = HEX[usize::from(byte & 0x0f)];
  Digits {
    buffer,
    at: Digits::WIDTH - 2,
  }
}

/// The lowercase hex digits, indexed by nibble.
const HEX: &[u8; 16] = b"0123456789abcdef";

/// One hex string's bytes, or `None` where it is not one.
///
/// The WHOLE grammar in one function, shared by `parse` and `is_valid` so that a document which
/// validates is a document which parses.
#[cfg(feature = "async-graphql")]
fn read_hex(text: &str) -> Option<Vec<u8>> {
  let digits = text
    .strip_prefix("0x")
    .or_else(|| text.strip_prefix("0X"))
    .unwrap_or(text)
    .as_bytes();
  if !digits.len().is_multiple_of(2) {
    return None;
  }
  let mut bytes = Vec::with_capacity(digits.len() / 2);
  // `as_chunks` rather than `chunks_exact`, because the width here is a CONSTANT: the item becomes
  // `&[u8; 2]`, so the two indices below are in bounds by the type rather than by a check an
  // optimiser has to remove. The discarded remainder is provably empty — the divisibility guard
  // above has already returned if it were not — which is the one thing worth checking at a call that
  // drops half of a pair.
  for pair in digits.as_chunks::<2>().0 {
    bytes.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
  }
  Some(bytes)
}

/// One hex digit's value, in either case.
#[cfg(feature = "async-graphql")]
const fn nibble(digit: u8) -> Option<u8> {
  match digit {
    b'0'..=b'9' => Some(digit - b'0'),
    b'a'..=b'f' => Some(digit - b'a' + 10),
    b'A'..=b'F' => Some(digit - b'A' + 10),
    _ => None,
  }
}