structio 0.3.2

High performance JSON and BEVE for Rust structs. No dependencies, no proc-macros, no intermediate representation.
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
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
//! The `object!`, `array!` and enum macros.
//!
//! Declarative, not procedural: expansion is a token-tree substitution inside
//! the compiler front end, with no proc-macro crate to build and link first,
//! and no dependency of any kind. It generates exactly the trait impls you
//! would write by hand.
//!
//! The struct macros differ in how a field is found. `object!` writes keys and
//! looks them up in a compile-time perfect hash; `array!` writes nothing but
//! the values and finds a field by counting.
//!
//! `unit_enum!` and `tagged_enum!` declare the other shape a schema can have.
//! A variant's name goes on the wire and comes back through the same perfect
//! hash the keys use, so an enum costs a struct's lookup and nothing more.

/// Declare a struct's schema, for every format.
///
/// Keys default to the field names. Give an explicit key with `"name" =>
/// field` when the encoded name differs from the Rust one.
///
/// ```
/// #[derive(Default)]
/// struct Person {
///     first_name: String,
///     age: u32,
/// }
///
/// structio::object!(Person { first_name, age });
/// ```
///
/// Renaming:
///
/// ```
/// # #[derive(Default)]
/// # struct Person { first_name: String, age: u32 }
/// structio::object!(Person {
///     "first-name" => first_name,
///     age,
/// });
/// ```
///
/// A declaration whose keys differ from the Rust names by a rule rather than
/// one at a time names the rule once, after the type. Every key it does not
/// spell out is then converted during compilation.
///
/// ```
/// # use structio::to_string;
/// #[derive(Default)]
/// struct Camera { field_of_view: f32, near_plane: f32, sensor_id: u32 }
///
/// structio::object!(Camera as "camelCase" {
///     field_of_view,
///     near_plane,
///     "sensorID" => sensor_id,
/// });
///
/// assert_eq!(
///     to_string(&Camera::default()),
///     r#"{"fieldOfView":0,"nearPlane":0,"sensorID":0}"#,
/// );
/// ```
///
/// The rules are `"lowercase"`, `"UPPERCASE"`, `"PascalCase"`, `"camelCase"`,
/// `"snake_case"`, `"SCREAMING_SNAKE_CASE"`, `"kebab-case"` and
/// `"SCREAMING-KEBAB-CASE"`. An explicit key wins over the rule wherever both
/// are present, which is what makes `"sensorID" => sensor_id` above the escape
/// hatch for a name the rule spells differently than the format does.
///
/// [`case`](crate::case) has the rule in full. Two parts of it are worth
/// knowing before reaching for one: a leading or trailing `_` is dropped, so
/// `type_` converts to `type`, and a run of capitals is respelled as one word,
/// so `http_url` under `"camelCase"` is `httpUrl` rather than `httpURL`. The
/// spellings are `serde`'s but the rule is not, so a schema being ported
/// should check [the differences](crate::case#coming-from-serde) first.
///
/// A member a document has to carry is marked `#[required]`. Absence is
/// otherwise no error: an unmarked field the document leaves out keeps
/// whatever the destination already held.
///
/// ```
/// # use structio::{ErrorCode, from_str};
/// #[derive(Debug, Default)]
/// struct Asset { version: String, min_version: u32, generator: String }
///
/// structio::object!(Asset {
///     #[required] version,
///     #[required] "minVersion" => min_version,
///     generator,
/// });
///
/// // The optional member may be left out.
/// assert!(from_str::<Asset>(r#"{"version":"2.0","minVersion":1}"#).is_ok());
/// // A required one may not.
/// assert_eq!(
///     from_str::<Asset>(r#"{"generator":"g"}"#).unwrap_err().code,
///     ErrorCode::MissingKey,
/// );
/// ```
///
/// This is the type's own answer, so it holds under every policy, and
/// [`RequireKeys`](crate::RequireKeys) still requires the members no mark did.
/// It is the setting to reach for where a schema is mixed, which is most of
/// them. See [`Keys::REQUIRED`](crate::Keys::REQUIRED) for the mask it writes
/// and the one limit on it: a marked field must be among the first 64
/// declared.
///
/// A field whose type this crate does not describe, and which you cannot
/// implement the traits for because you own neither of them, names an
/// *adapter* instead: a type of your own that says how that type is read and
/// written. The field keeps its own type.
///
/// ```
/// # use std::time::Duration;
/// # use structio::{ErrorCode, Options, json};
/// // `Millis` reads and writes a `Duration` as a whole number of
/// // milliseconds. Its two impls are in `examples/adapters.rs`; see
/// // `json::ReadAs` for their signatures.
/// # struct Millis;
/// # impl<'de> json::ReadAs<'de, Duration> for Millis {
/// #     fn read<O: Options>(v: &mut Duration, p: &mut json::Parser<'de, O>)
/// #         -> Result<(), ErrorCode>
/// #     {
/// #         let mut ms = 0u64;
/// #         json::Read::read(&mut ms, p)?;
/// #         *v = Duration::from_millis(ms);
/// #         Ok(())
/// #     }
/// # }
/// # impl json::WriteAs<Duration> for Millis {
/// #     fn write<O: Options>(v: &Duration, w: &mut json::Writer<'_, O>) {
/// #         json::Write::write(&(v.as_millis() as u64), w);
/// #     }
/// # }
/// #[derive(Default)]
/// struct Job { id: u32, elapsed: Duration, retries: Vec<Duration> }
///
/// // A `json_object!`, because only the JSON half of `Millis` exists.
/// structio::json_object!(Job {
///     id,
///     "elapsed_ms" => elapsed as Millis,
///     retries as Vec<Millis>,
/// });
///
/// let job = Job { id: 1, elapsed: Duration::from_millis(90), retries: vec![] };
/// assert_eq!(structio::to_string(&job), r#"{"id":1,"elapsed_ms":90,"retries":[]}"#);
/// ```
///
/// Adapters compose as types do, so `Option<Millis>` and `Vec<Millis>` adapt
/// the containers and [`Same`](crate::Same) is the identity. See
/// [`json::ReadAs`](crate::json::ReadAs).
///
/// A declaration has to name every field of the type. Forgetting one is
/// `error[E0063]: missing field \`cache\` in initializer of \`Config\``,
/// pointed at the declaration, rather than a member that quietly stops being
/// written. Where the omission is deliberate, end the declaration with `..`,
/// which reads as it reads in a pattern: these fields, and there are others.
///
/// ```
/// #[derive(Default)]
/// struct Config { host: String, port: u16, cache: Vec<u8> }
/// structio::object!(Config { host, port, .. });
///
/// let c = Config { host: "example".into(), port: 8080, cache: vec![1] };
/// assert_eq!(structio::to_string(&c), r#"{"host":"example","port":8080}"#);
/// ```
///
/// Generic and borrowing types take their impl generics in brackets. A type
/// that borrows from the input names its lifetime first, under whatever name
/// the struct gave it; it becomes the lifetime of the document being read.
///
/// ```
/// #[derive(Default)]
/// struct Borrowed<'a> {
///     name: &'a str,
/// }
/// structio::object!(['a] Borrowed<'a> { name });
///
/// #[derive(Default)]
/// struct Page<T> {
///     items: Vec<T>,
///     cursor: Option<String>,
/// }
/// structio::object!([T: structio::ReadWrite + Default] Page<T> { items, cursor });
/// ```
///
/// # What it expands to
///
/// One [`Keys`](crate::Keys) impl carrying the key list and the compile-time
/// perfect hash, and then, for each format, four small impls: `ReadObject` and
/// `WriteObject` for the per-field dispatch, and `Read`/`Write` delegating to
/// the object forms.
///
/// The schema is declared once because it *is* one thing: the same field
/// order, the same keys, and the same hash table serve
/// [`json`](crate::json) and [`beve`](crate::beve) alike. Only the bytes
/// differ. Nothing is hidden; the same code written by hand behaves
/// identically.
///
/// An adapter is the one place that can stop being true. One name at a field
/// site stands for four impls, and nothing checks that its JSON half and its
/// BEVE half describe the same value, or that their
/// [`is_null`](crate::json::WriteAs::is_null) answers agree. Keeping them
/// saying the same thing is the adapter author's job, and it is worth stating
/// because everything else here makes it impossible to get wrong.
///
/// For a struct encoded as a positional array rather than as a keyed object,
/// see [`array!`](crate::array).
///
/// When a type cannot support both formats, declare it with
/// [`json_object!`](crate::json_object) or
/// [`beve_object!`](crate::beve_object) instead. Every field's type has to be
/// readable in each format generated for, so a struct holding a borrowed
/// `&[u8]`, which only BEVE can hand back, is a `beve_object!`.
#[macro_export]
macro_rules! object {
    ($($t:tt)*) => { $crate::__declare!(__both_impls $($t)*); };
}

/// Declare a struct's schema for JSON alone.
///
/// The same syntax as [`object!`], generating only the JSON impls. Reach for
/// it when a type cannot support both formats: a field whose type only one of
/// them can read, or a struct you simply do not want the other's code
/// generated for.
#[macro_export]
macro_rules! json_object {
    ($($t:tt)*) => { $crate::__declare!(__json_impls $($t)*); };
}

/// Declare a struct's schema for BEVE alone.
///
/// The counterpart of [`json_object!`]. A struct with a borrowed `&[u8]` field
/// needs this one: JSON has no way to hand back a run of bytes out of a
/// document, so there is no JSON impl to generate.
///
/// ```
/// #[derive(Default)]
/// struct Frame<'a> {
///     id: u32,
///     payload: &'a [u8],
/// }
/// structio::beve_object!(['a] Frame<'a> { id, payload });
/// ```
#[macro_export]
macro_rules! beve_object {
    ($($t:tt)*) => { $crate::__declare!(__beve_impls $($t)*); };
}

/// Normalize a declaration's generics, then hand them to `$m` alongside the
/// shared `Keys` impl.
///
/// The three public macros differ only in which impls they want, and the rule
/// for the input lifetime is the same for all of them: reading borrows from
/// the input, so the read impls always need the lifetime, while the write
/// impls must not declare one they do not constrain. Stating that once is the
/// point. A declaration that leads with a lifetime supplies it under that
/// name; one without gets a `'de` the read impls introduce for themselves.
///
/// The two lists handed on are the read generics and the write generics, in
/// that order, and behind them the declaration's [case rule](crate::case) or
/// `_` for none.
///
/// Each generics form needs two arms, since `macro_rules!` cannot make `as
/// "camelCase"` optional in front of a `$ty:ty`. They differ only in what they
/// put in the case slot, so all six hand the normalized form to one place.
#[doc(hidden)]
#[macro_export]
macro_rules! __declare {
    // Generics that lead with a lifetime: the type borrows from the input, so
    // both impls use the list verbatim.
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared!($m [$de $($gen)*] [$de $($gen)*] [$case] $ty { $($body)* });
    };
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared!($m [$de $($gen)*] [$de $($gen)*] [_] $ty { $($body)* });
    };
    // Generics without a lifetime: the read impls need one, the write impls
    // must not declare an unconstrained lifetime.
    ($m:ident [ $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared!($m ['de, $($gen)*] [$($gen)*] [$case] $ty { $($body)* });
    };
    ($m:ident [ $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared!($m ['de, $($gen)*] [$($gen)*] [_] $ty { $($body)* });
    };
    ($m:ident $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared!($m ['de] [] [$case] $ty { $($body)* });
    };
    ($m:ident $ty:ty { $($body:tt)* }) => {
        $crate::__declared!($m ['de] [] [_] $ty { $($body)* });
    };
}

/// A declaration whose generics and case rule are both in normal form.
#[doc(hidden)]
#[macro_export]
macro_rules! __declared {
    // A declaration that ends in `..` leaves fields out on purpose, so the
    // type is not checked against it.
    //
    // Every field carries its own trailing comma in this arm rather than the
    // usual separator, which is what lets `..` follow a field that ends in an
    // adapter. `..` is not in the follow set of a `ty` fragment and `,` is, so
    // `$(as $with:ty)?),* ..` would not compile as a matcher at all.
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
        $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? ,)* ..
    }) => {
        $crate::__case_check!($case);
        $crate::__keys_impl!([$($wgen)*] [$case] [partial] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)?),*
        });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)?),*
        });
    };
    // Every field named, so the declaration is checked against the type.
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
        $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)?),* $(,)?
    }) => {
        $crate::__case_check!($case);
        $crate::__keys_impl!([$($wgen)*] [$case] [all] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)?),*
        });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)?),*
        });
    };
}

/// Both formats, for [`object!`].
#[doc(hidden)]
#[macro_export]
macro_rules! __both_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty { $($body:tt)* }) => {
        $crate::__json_impls!([$($rgen)*] [$($wgen)*] [$case] $ty { $($body)* });
        $crate::__beve_impls!([$($rgen)*] [$($wgen)*] [$case] $ty { $($body)* });
    };
}

/// Refuse a declaration that names the same field or variant twice.
///
/// One constant per name, in a scope of its own, so a repeat is `E0428`: "the
/// name `f` is defined multiple times", pointed at the declaration and naming
/// the duplicate.
///
/// It has to be a hard error rather than a lint. Duplicating a `match` arm or a
/// pattern binding would be diagnosed too, but as `unreachable_patterns` and
/// `E0025`, and a lint raised inside a macro expanded from *another* crate is
/// suppressed, so it would never reach the person who wrote the declaration.
/// An explicit `#[deny]` on the arm does not lift that; only an error does.
///
/// The key hash refuses a duplicate *key* already, which catches the same
/// mistake whenever the names are the wire names. This is the half it cannot
/// see: two spellings of one member, `"x" => f` beside `"z" => f`, which reads
/// under either name and writes the member twice. A positional struct has no
/// keys at all, so this is the only thing standing between `[x, y, x]` and an
/// array of three elements, two of them the same field.
#[doc(hidden)]
#[macro_export]
macro_rules! __each_name_once {
    ($($name:ident),* $(,)?) => {
        const _: () = {
            $( #[allow(dead_code, non_upper_case_globals)] const $name: () = (); )*
        };
    };
}

/// Refuse a declaration that leaves one of the type's fields out.
///
/// The one real cost of declaring a schema beside a type rather than on it is
/// that the field list is written twice and the two can drift. A field added to
/// the struct and forgotten here is silently absent from both formats, with
/// nothing to point at: the declaration still compiles, and every document
/// written from it is quietly missing a member. This closes that.
///
/// The check is a struct literal rather than a destructuring pattern, for the
/// diagnostic. Both catch the same mistake, but a pattern expanded from a macro
/// reports that it requires `..` due to inaccessible fields, which names
/// nothing, while a literal reports E0063, missing field so-and-so in the
/// initializer of the type, which names the field and points the note at the
/// declaration that forgot it.
///
/// `loop {}` is the field value because it has type `!` and so coerces to
/// whatever the field is, with no bound on it: not `Default`, not `Sized`, not
/// anything. Nothing calls the function, and it is inside a `const _` block, so
/// the trait it hangs off cannot collide with anything the user has.
///
/// A declaration ending in `..` says the omission is deliberate and expands to
/// nothing here.
///
/// There is no enum counterpart, because each format's write impl already ends
/// in an exhaustive `match` over the declared variants, for the reason given
/// there: a variant left out would otherwise write nothing at all.
#[doc(hidden)]
#[macro_export]
macro_rules! __declares_every_field {
    ([$($wgen:tt)*] [partial] $ty:ty { $($field:ident),* }) => {};
    ([$($wgen:tt)*] [all] $ty:ty { $($field:ident),* }) => {
        const _: () = {
            #[allow(dead_code)]
            trait DeclaresEveryField: ::core::marker::Sized {
                fn declared() -> Self;
            }
            impl<$($wgen)*> DeclaresEveryField for $ty {
                #[allow(unreachable_code, clippy::empty_loop)]
                fn declared() -> Self {
                    Self { $($field: loop {}),* }
                }
            }
        };
    };
}

/// Whether a field carried the `#[required]` marker.
///
/// A field's markers reach [`__keys_impl!`](crate::__keys_impl) as an optional
/// token, which `macro_rules!` can act on only by handing it to a macro that
/// branches on its presence. The last arm is what turns a misspelling into a
/// message rather than into "no rules expected this token".
#[doc(hidden)]
#[macro_export]
macro_rules! __is_required {
    () => {
        false
    };
    (required) => {
        true
    };
    ($other:ident) => {
        ::core::compile_error!(::core::concat!(
            "unrecognized field marker `#[",
            ::core::stringify!($other),
            "]`; the only one is `#[required]`"
        ))
    };
}

/// The format-independent half: the key list and its compile-time hash.
#[doc(hidden)]
#[macro_export]
macro_rules! __keys_impl {
    (
        [$($wgen:tt)*] [$case:tt] [$mode:ident] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)?),* $(,)?
        }
    ) => {
        $crate::__each_name_once!($($field),*);
        $crate::__declares_every_field!([$($wgen)*] [$mode] $ty { $($field),* });

        impl<$($wgen)*> $crate::Keys for $ty {
            const KEYS: &'static [&'static str] = &[
                $( $crate::__json_key!([$case] $($key)? [$field]) ),*
            ];
            // Built from `Self::KEYS` rather than a second copy of the key
            // list, so the two cannot drift apart.
            //
            // `&` on a const expression promotes to an anonymous static, so the
            // table lives in read-only memory and is never copied onto the
            // stack at a lookup site.
            const MAP: &'static $crate::KeyMap = &$crate::KeyMap::build(Self::KEYS);

            // `macro_rules!` cannot count, so the field index is carried in a
            // counter, here through const evaluation rather than through the
            // optimizer. Zero for a declaration that marks nothing, which is
            // what takes the check back out of both readers.
            #[allow(unused_assignments, unused_mut)]
            const REQUIRED: u64 = {
                let mut mask = 0u64;
                let mut i = 0u32;
                $(
                    if $crate::__is_required!($($req)?) {
                        assert!(
                            i < 64,
                            "a #[required] field must be one of the first 64 \
                             declared: the mask that tracks them is a u64"
                        );
                        mask |= 1u64 << i;
                    }
                    i += 1;
                )*
                mask
            };
        }
    };
}

/// The `#[required]` marker is matched and dropped here: which members a
/// document has to carry is a property of the schema, so only
/// [`__keys_impl!`](crate::__keys_impl) acts on it.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)?),* $(,)?
        }
    ) => {
        impl<$de $($rgen)*> $crate::json::ReadObject<$de> for $ty {
            // Deliberately not `inline(always)`: this body holds the parser for
            // every field, so forcing it into each caller duplicates a whole
            // nested struct's parser per field arm of its parent.
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn read_field<O: $crate::Options>(
                &mut self,
                index: usize,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                // `macro_rules!` cannot count, so the field index is carried in
                // a counter that const-folds away. LLVM rebuilds the same jump
                // table a `match` would have produced, and expansion stays
                // linear in the field count instead of quadratic.
                let mut i = 0usize;
                $(
                    if index == i {
                        // The hash only proposed this field; confirm the key
                        // before touching the value.
                        if !p.match_key($crate::__json_key!([$case] $($key)? [$field])) {
                            return ::core::result::Result::Ok(false);
                        }
                        p.colon()?;
                        $crate::__json_read_as!(&mut self.$field, p $(, $with)?)?;
                        return ::core::result::Result::Ok(true);
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }
        }

        impl<$($wgen)*> $crate::json::WriteObject for $ty {
            #[inline]
            fn write_fields<O: $crate::Options>(
                &self,
                w: &mut $crate::json::Writer<'_, O>,
            ) {
                // The duplicate-key check is in `KeyMap::build`, which nothing
                // reaches but `Keys::MAP`. Reading looks a key up and so
                // evaluates it; writing has no use for it, and a generic
                // type's associated const is evaluated only when something
                // names it, so a generic declaration that is never read would
                // otherwise write two members under one key. Naming it here
                // costs nothing and closes that.
                const {
                    let _ = <Self as $crate::Keys>::MAP;
                };
                // Each member carries its own trailing comma; the caller turns
                // the last one into `}`. No per-field "first?" branch.
                $( $crate::__write_member!(
                    w,
                    $crate::__json_member!([$case] $($key)? [$field]),
                    &self.$field
                    $(, $with)?
                ); )*
            }
        }

        impl<$de $($rgen)*> $crate::json::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                p.read_object(self)
            }
        }

        impl<$($wgen)*> $crate::json::Write for $ty {
            #[inline]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                w.write_object(self);
            }
        }
    };
}

/// The `#[required]` marker is matched and dropped here: which members a
/// document has to carry is a property of the schema, so only
/// [`__keys_impl!`](crate::__keys_impl) acts on it.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)?),* $(,)?
        }
    ) => {
        impl<$de $($rgen)*> $crate::beve::ReadObject<$de> for $ty {
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn read_field<O: $crate::Options>(
                &mut self,
                index: usize,
                key: &[u8],
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                let mut i = 0usize;
                $(
                    if index == i {
                        // The key arrived already delimited by its length
                        // prefix, so confirming the hash's candidate is one
                        // slice comparison against a constant.
                        if key != $crate::__json_key!([$case] $($key)? [$field]).as_bytes() {
                            return ::core::result::Result::Ok(false);
                        }
                        $crate::__beve_read_as!(&mut self.$field, r $(, $with)?)?;
                        return ::core::result::Result::Ok(true);
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }
        }

        impl<$($wgen)*> $crate::beve::WriteObject for $ty {
            #[inline]
            fn write_fields<O: $crate::Options>(
                &self,
                w: &mut $crate::beve::Writer<'_, O>,
            ) {
                // The duplicate-key check is in `KeyMap::build`, which nothing
                // reaches but `Keys::MAP`. Reading looks a key up and so
                // evaluates it; writing has no use for it, and a generic
                // type's associated const is evaluated only when something
                // names it, so a generic declaration that is never read would
                // otherwise write two members under one key. Naming it here
                // costs nothing and closes that.
                const {
                    let _ = <Self as $crate::Keys>::MAP;
                };
                // The member count went out with the object header, so a
                // member is its pre-encoded key followed by its value and
                // nothing else.
                $( $crate::__write_member!(
                    w,
                    $crate::__beve_key_bytes!($crate::__json_key!([$case] $($key)? [$field])),
                    &self.$field
                    $(, $with)?
                ); )*
            }

            #[inline]
            #[allow(unused_mut)]
            fn count_fields<O: $crate::Options>(&self) -> usize {
                // Without `SKIP_NULL` every term is `1` and the whole sum
                // folds to the same literal `KEYS.len()` would have been.
                let mut n = 0usize;
                $(
                    n += !(O::SKIP_NULL
                        && $crate::__beve_is_null_as!(&self.$field $(, $with)?)) as usize;
                )*
                n
            }
        }

        impl<$de $($rgen)*> $crate::beve::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                r.read_object(self)
            }
        }

        impl<$($wgen)*> $crate::beve::Write for $ty {
            #[inline]
            fn write<O: $crate::Options>(&self, w: &mut $crate::beve::Writer<'_, O>) {
                w.write_object(self);
            }
        }
    };
}

/// The key for a field: the explicit literal, the field name, or the field
/// name put through the declaration's [case rule](crate::case).
///
/// The case slot holds `_` when the declaration named no rule. An explicit
/// literal wins over a rule wherever both are present, which is what makes
/// `"httpURL" => http_url` the escape hatch for a name the rule spells
/// differently than you would.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_key {
    ([$case:tt] $key:literal [$field:ident]) => {
        $key
    };
    ([_] [$field:ident]) => {
        ::core::stringify!($field)
    };
    ([$case:tt] [$field:ident]) => {
        $crate::__case_apply!($case, ::core::stringify!($field))
    };
}

/// The pre-quoted `"key":` prefix, assembled during const evaluation so that
/// writing a JSON member is one copy of a constant string.
///
/// A function of [`__json_key!`](crate::__json_key) rather than a second copy
/// of the literal-or-name-or-rule choice, so the prefix a member is written
/// with and the key the reader confirms cannot come to describe different
/// members. The BEVE side is built the same way, from the same call.
///
/// `concat!` would do for the two forms whose key *is* a literal, and did
/// before there was a third: a converted key exists only once a `const fn` has
/// run, and `concat!` takes literals and nothing else.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_member {
    ($($key:tt)*) => {{
        const KEY: &str = $crate::__json_key!($($key)*);
        const N: usize = KEY.len() + 3;
        // Braced for `__beve_key_bytes!`'s reason: a bare `N` in
        // generic-argument position parses as a type.
        const PREFIX: [u8; N] = $crate::json::quoted_key::<{ N }>(KEY);
        const OUT: &str = $crate::case::as_str(&PREFIX);
        OUT
    }};
}

/// The pre-encoded `SIZE | KEY` bytes of a BEVE object key, assembled during
/// const evaluation so writing a member is one copy of a constant array.
///
/// Unlike [`__json_member!`](crate::__json_member), which needs its own copy of
/// the literal-or-field-name choice because `concat!` cannot take a macro call,
/// this binds its argument to a `const` first and so accepts one directly.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_key_bytes {
    ($key:expr) => {{
        const KEY: &str = $key;
        const N: usize = $crate::beve::header::key_len(KEY);
        // Braced, because a bare `N` in generic-argument position parses as a
        // type: a user struct called `N` would win over this constant and the
        // declaration would not compile. `macro_rules!` hygiene does not cover
        // items, so the block's own `N` is no protection.
        const ENCODED: [u8; N] = $crate::beve::header::encode_key::<{ N }>(KEY);
        &ENCODED
    }};
}

/// A name put through a case rule, during const evaluation.
///
/// The result is a `const` item, so it lives in read-only memory and the
/// declaration pays for the conversion once at compile time. See
/// [`case`](crate::case) for what the rule does to a name.
///
/// The rule reaches [`case::style`](crate::case::style) as an expression
/// rather than being matched against a list of spellings here, for the reason
/// the adapter helpers below give: a fragment captured by someone else's macro
/// does not re-match a token, so a wrapper macro passing its own
/// `$rule:literal` along would find every spelling rejected.
#[doc(hidden)]
#[macro_export]
macro_rules! __case_apply {
    ($case:literal, $name:expr) => {{
        const NAME: &str = $name;
        // Bound before it is looked up so that a literal of the wrong kind is
        // "expected `&str`" at the declaration rather than a type error deep
        // inside an expansion.
        const RULE: &str = $case;
        const STYLE: $crate::case::Style = $crate::case::style(RULE);
        const N: usize = $crate::case::cased_len(NAME, STYLE);
        // Braced for `__beve_key_bytes!`'s reason.
        const CASED: [u8; N] = $crate::case::cased::<{ N }>(NAME, STYLE);
        const OUT: &str = $crate::case::as_str(&CASED);
        OUT
    }};
    // Reported by `__case_check!`, once for the declaration rather than once
    // per site. Falling back to the name keeps the expansion type-correct so
    // that the one error is the one the reader sees.
    ($other:tt, $name:expr) => {
        $name
    };
}

/// Refuse a case rule that is not a string.
///
/// Checked once for the declaration, because [`__case_apply!`] runs at five
/// sites per field and a rule written without its quotes would otherwise be
/// reported five times over.
///
/// [`__case_apply!`]: crate::__case_apply
#[doc(hidden)]
#[macro_export]
macro_rules! __case_check {
    (_) => {};
    ($case:literal) => {};
    ($other:tt) => {
        ::core::compile_error!(::core::concat!(
            "structio: `",
            ::core::stringify!($other),
            "` is not a case rule; a rule is written as a string, as in \
             `object!(Root as \"camelCase\" { .. })`"
        ));
    };
}

// ---------------------------------------------------------------------------
// Adapter dispatch
// ---------------------------------------------------------------------------
//
// A field may name an adapter, and `macro_rules!` cannot branch inside a
// repetition, so each site that cares dispatches to a helper whose two arms are
// "with an adapter" and "without". The optional fragment goes last at every
// call site, so an absent one expands to nothing and selects the second arm.
//
// A captured `ty` re-matches a `ty` matcher in the callee, so passing one on
// like this does not hit the opaque-fragment rule that would bite a `ty`
// re-examined as anything else.

/// Read a field, through its adapter if it named one.
///
/// The `'_` binds to the generated impl's input lifetime, whatever the
/// declaration named it, and the `_` to the field's own type, so an adapter
/// over a borrowing field or over the declaration's own type parameter needs
/// nothing spelled out.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_as {
    ($place:expr, $p:ident, $with:ty) => {
        <$with as $crate::json::ReadAs<'_, _>>::read($place, $p)
    };
    ($place:expr, $p:ident) => {
        $crate::json::Read::read($place, $p)
    };
}

/// Write a member, through its adapter if the field named one.
///
/// The one adapter helper the two formats share, for
/// [`__write_variant!`](crate::__write_variant)'s reason: the two calls are
/// spelled the same in both, and only the pre-encoded key differs, so it is
/// passed in rather than built here.
///
/// The adapter appears in no argument of
/// [`member_with`](crate::json::Writer::member_with), so it is turned up
/// explicitly and the `<A, T>` parameter order there is load bearing.
#[doc(hidden)]
#[macro_export]
macro_rules! __write_member {
    ($w:ident, $key:expr, $place:expr, $with:ty) => {
        $w.member_with::<$with, _>($key, $place)
    };
    ($w:ident, $key:expr, $place:expr) => {
        $w.member($key, $place)
    };
}

/// [`__json_read_as!`](crate::__json_read_as) for BEVE.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_as {
    ($place:expr, $r:ident, $with:ty) => {
        <$with as $crate::beve::ReadAs<'_, _>>::read($place, $r)
    };
    ($place:expr, $r:ident) => {
        $crate::beve::Read::read($place, $r)
    };
}

/// Ask whether a member is absent, of its adapter if the field named one.
///
/// Not merely a matter of getting the same answer as the writer: this is the
/// one site that would otherwise put a [`beve::Write`](crate::beve::Write)
/// bound on the very type the adapter exists to avoid describing, so without
/// it an adapted declaration does not compile at all.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_is_null_as {
    ($place:expr, $with:ty) => {
        <$with as $crate::beve::WriteAs<_>>::is_null($place)
    };
    ($place:expr) => {
        $crate::beve::Write::is_null($place)
    };
}

/// Declare a struct's schema as a positional array, for every format.
///
/// The bracket counterpart of [`object!`]. Fields are encoded in declaration
/// order with no keys at all: JSON writes them between `[` and `]`, BEVE
/// behind a generic-array header.
///
/// ```
/// #[derive(Default, PartialEq, Debug)]
/// struct Vec3 {
///     x: f64,
///     y: f64,
///     z: f64,
/// }
///
/// structio::array!(Vec3 [x, y, z]);
///
/// let v = Vec3 { x: 1.0, y: 2.0, z: 3.0 };
/// assert_eq!(structio::to_string(&v), "[1,2,3]");
/// assert_eq!(structio::from_str::<Vec3>("[1,2,3]").unwrap(), v);
/// ```
///
/// The list holds field names and nothing else. [`object!`]'s `#[required]`
/// marker has no counterpart here and is not accepted: an element is required
/// by its position, and an array of the wrong length is refused under every
/// policy.
///
/// Generics work as they do for [`object!`]: in brackets before the type, with
/// the lifetime written first when the type borrows from the input.
///
/// ```
/// #[derive(Default)]
/// struct Labelled<'a, T> {
///     label: &'a str,
///     value: T,
/// }
/// structio::array!(['a, T: structio::ReadWrite + Default] Labelled<'a, T> [label, value]);
/// ```
///
/// # Homogeneous structs
///
/// When every field is the same type, name it in front of the field list, the
/// way an array type names its element:
///
/// ```
/// #[derive(Default, PartialEq, Debug)]
/// struct Rgb {
///     r: u8,
///     g: u8,
///     b: u8,
/// }
///
/// structio::array!(Rgb [u8; r, g, b]);
/// ```
///
/// JSON is unchanged by this. What it buys is BEVE, which stores a run of one
/// type as a **typed array**: one header for the whole run instead of one per
/// element, and the values as a contiguous block. `Rgb` goes out in five bytes
/// rather than eight, three `f64`s in twenty-six rather than twenty-nine, and
/// three `bool`s in three rather than five, since booleans pack one per bit.
/// The bytes are exactly what a `[u8; 3]` of the same values would have
/// produced, which is also what another implementation writes for its own
/// three-component colour.
///
/// The element type is checked: every field has to be it, and a mismatch is a
/// compile error at the declaration. It also has to be [`Copy`], because the
/// payload is one contiguous run and a struct's fields are not required to be
/// laid out as one, so they are gathered into a block first. That bound holds
/// whether or not the type turns out to have a typed array: one that does not,
/// such as another struct, falls back to a generic array and is written
/// exactly as it would have been without the element type.
///
/// Reading is unchanged either way: an array-declared struct takes a generic
/// array or a typed one whatever it was declared as, so adding an element type
/// changes what you write without narrowing what you accept.
///
/// Like [`object!`], a declaration has to name every field, and `..` at the
/// end of the list says an omission is deliberate. It goes behind the element
/// type where there is one.
///
/// ```
/// #[derive(Default)]
/// struct Rgb { r: u8, g: u8, b: u8, label: String }
/// structio::array!(Rgb [u8; r, g, b, ..]);
///
/// let c = Rgb { r: 1, g: 2, b: 3, label: "red".into() };
/// assert_eq!(structio::to_string(&c), "[1,2,3]");
/// ```
///
/// # When to reach for it
///
/// Position is cheaper than a key in every respect: nothing is hashed, nothing
/// is compared, no [`KeyMap`](crate::KeyMap) is built or stored, and the keys
/// themselves are off the wire. For a type whose field names carry no
/// information anyway, a coordinate or a colour or a row of a table, that is
/// most of the per-value cost gone.
///
/// What it costs is room to move. An object can tolerate a field appearing or
/// disappearing, since a reader matches on names and can be asked to step over
/// a key it does not know
/// ([`SkipUnknown`](crate::SkipUnknown); the default refuses it). An array
/// cannot, under any policy: adding, removing, or reordering a field silently
/// changes what every position means, and lengthens or shortens the array,
/// which readers of the old shape reject. Declare a type this way when its
/// shape is fixed by something outside your control, and `object!` otherwise.
///
/// # What it expands to
///
/// One [`Elements`](crate::Elements) impl carrying the field count, and then,
/// for each format, four small impls: `ReadArray` and `WriteArray` for the
/// per-element dispatch, and `Read`/`Write` delegating to the array forms.
/// There is no key list and no hash, because there is nothing to look up.
/// An element type adds the typed-array header and payload writer to BEVE's
/// `WriteArray`, both of which fold away when it is absent.
///
/// A tuple is the same encoding without the names, and goes through the same
/// drivers, so `(f64, f64, f64)` and the `Vec3` above produce identical bytes
/// in both formats.
#[macro_export]
macro_rules! array {
    ($($t:tt)*) => { $crate::__declare_array!(__both_array_impls $($t)*); };
}

/// Declare a struct's schema as a positional array, for JSON alone.
///
/// The same syntax as [`array!`], generating only the JSON impls. The reasons
/// to want it are [`json_object!`]'s.
#[macro_export]
macro_rules! json_array {
    ($($t:tt)*) => { $crate::__declare_array!(__json_array_impls $($t)*); };
}

/// Declare a struct's schema as a positional array, for BEVE alone.
///
/// The counterpart of [`json_array!`], and what a struct with a borrowed
/// `&[u8]` element needs.
#[macro_export]
macro_rules! beve_array {
    ($($t:tt)*) => { $crate::__declare_array!(__beve_array_impls $($t)*); };
}

/// [`__declare!`](crate::__declare) for the array forms.
///
/// The same normalization of the input lifetime, and the same two lists handed on, but no
/// `Keys` impl: a positional struct has no keys. What it shares instead is its
/// length, which is [`Elements`](crate::Elements), and that is small enough to
/// be generated alongside each set of impls rather than on its own.
#[doc(hidden)]
#[macro_export]
macro_rules! __declare_array {
    // Generics that lead with a lifetime: the type borrows from the input, so
    // both impls use the list verbatim.
    //
    // A case rule goes in front of each shape rather than after all three. An
    // arm that fails to match falls through, but a `$ty:ty` handed something
    // that cannot be a type at all is a parse error that ends the expansion,
    // so a trailing arm would never be reached from a generic declaration.
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt [ $($body:tt)* ]) => {
        $crate::__no_array_case!();
    };
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty [ $($body:tt)* ]) => {
        $crate::__declared_array!($m [$de $($gen)*] [$de $($gen)*] $ty [ $($body)* ]);
    };
    // Generics without a lifetime: the read impls need one, the write impls
    // must not declare an unconstrained lifetime.
    ($m:ident [ $($gen:tt)* ] $ty:ty as $case:tt [ $($body:tt)* ]) => {
        $crate::__no_array_case!();
    };
    ($m:ident [ $($gen:tt)* ] $ty:ty [ $($body:tt)* ]) => {
        $crate::__declared_array!($m ['de, $($gen)*] [$($gen)*] $ty [ $($body)* ]);
    };
    ($m:ident $ty:ty as $case:tt [ $($body:tt)* ]) => {
        $crate::__no_array_case!();
    };
    ($m:ident $ty:ty [ $($body:tt)* ]) => {
        $crate::__declared_array!($m ['de] [] $ty [ $($body)* ]);
    };
}

/// Refuse a [case rule](crate::case) on a positional struct.
///
/// [`array!`] writes no keys at all, so a rule would have nothing to convert
/// and silently doing nothing is the wrong answer. Without this arm the
/// declaration simply fails to match and the error points into this crate
/// rather than at the `as "camelCase"` that caused it.
#[doc(hidden)]
#[macro_export]
macro_rules! __no_array_case {
    () => {
        ::core::compile_error!(
            "structio: a positional struct has no keys, so a case rule has nothing to \
             convert. Case rules belong on `object!`, `unit_enum!` and `tagged_enum!`."
        );
    };
}

/// Both formats, for [`array!`].
#[doc(hidden)]
#[macro_export]
macro_rules! __both_array_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($body:tt)* ]) => {
        $crate::__json_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($body)* ]);
        $crate::__beve_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($body)* ]);
    };
}

/// A positional declaration whose generics are in normal form, split on whether
/// it names every field.
///
/// [`__declared!`](crate::__declared)'s counterpart, and `..` means what it
/// means there. The element type stays in front of the field list rather than
/// being pulled out here, because only
/// [`__elements_impl!`](crate::__elements_impl) and BEVE's writer act on it.
///
/// It takes four arms rather than two because an optional `$elem:ty ;` in front
/// of a field list is a local ambiguity: the matcher cannot tell whether the
/// first token begins a type or is already a field. Spelling both shapes out is
/// what [`__elements_impl!`](crate::__elements_impl) and each format's array
/// macro already do, for the same reason.
#[doc(hidden)]
#[macro_export]
macro_rules! __declared_array {
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:ident ,)* .. ]) => {
        $crate::__elements_impl!([$($wgen)*] [partial] $ty [ $elem ; $($field),* ]);
        $crate::$m!([$($rgen)*] [$($wgen)*] $ty [ $elem ; $($field),* ]);
    };
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:ident),* $(,)? ]) => {
        $crate::__elements_impl!([$($wgen)*] [all] $ty [ $elem ; $($field),* ]);
        $crate::$m!([$($rgen)*] [$($wgen)*] $ty [ $elem ; $($field),* ]);
    };
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:ident ,)* .. ]) => {
        $crate::__elements_impl!([$($wgen)*] [partial] $ty [ $($field),* ]);
        $crate::$m!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:ident),* $(,)? ]) => {
        $crate::__elements_impl!([$($wgen)*] [all] $ty [ $($field),* ]);
        $crate::$m!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
}

/// The format-independent half: how many elements the array has.
#[doc(hidden)]
#[macro_export]
macro_rules! __elements_impl {
    // With an element type: the fields have to be it, and saying so is the
    // whole difference, so it is checked here rather than left to whichever
    // format happens to use it.
    ([$($wgen:tt)*] [$mode:ident] $ty:ty [ $elem:ty ; $($field:ident),* $(,)? ]) => {
        $crate::__elements_impl!([$($wgen)*] [$mode] $ty [ $($field),* ]);

        const _: () = {
            #[allow(dead_code)]
            fn every_field_is_the_element_type<$($wgen)*>(v: &$ty) {
                $( let _: &$elem = &v.$field; )*
            }
        };
    };
    ([$($wgen:tt)*] [$mode:ident] $ty:ty [ $($field:ident),* $(,)? ]) => {
        $crate::__each_name_once!($($field),*);
        $crate::__declares_every_field!([$($wgen)*] [$mode] $ty { $($field),* });

        impl<$($wgen)*> $crate::Elements for $ty {
            // Counted by building a slice of the field names and taking its
            // length, since `macro_rules!` cannot count. Both fold away: the
            // slice is never built.
            const LEN: usize =
                <[&'static str]>::len(&[$( ::core::stringify!($field) ),*]);
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __json_array_impls {
    // JSON has one array syntax, so the element type changes nothing here.
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:ident),* $(,)? ]) => {
        $crate::__json_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
    ([$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:ident),* $(,)? ]) => {
        impl<$de $($rgen)*> $crate::json::ReadArray<$de> for $ty {
            // Deliberately not `inline(always)`, for `read_field`'s reason:
            // this body holds the parser for every element.
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn read_element<O: $crate::Options>(
                &mut self,
                index: usize,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                // The same const-folding counter `read_field` uses, and for
                // the same reason: expansion stays linear in the field count.
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::json::Read::read(&mut self.$field, p);
                    }
                    i += 1;
                )*
                // Only reachable from an array longer than the struct, which
                // the driver would have rejected on the count anyway. Failing
                // here stops the parse at the first surplus element instead of
                // reading the rest of a document that cannot fit.
                ::core::result::Result::Err($crate::ErrorCode::ArrayLengthMismatch)
            }
        }

        impl<$($wgen)*> $crate::json::WriteArray for $ty {
            #[inline]
            fn write_elements<O: $crate::Options>(
                &self,
                w: &mut $crate::json::Writer<'_, O>,
            ) {
                // Each element carries its own trailing comma; the caller
                // turns the last one into `]`.
                $( w.element(&self.$field); )*
            }
        }

        impl<$de $($rgen)*> $crate::json::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                p.read_array(self)
            }
        }

        impl<$($wgen)*> $crate::json::Write for $ty {
            #[inline]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                w.write_array(self);
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __beve_array_impls {
    // With an element type, the struct is stored the way a run of that type is
    // stored: one header for the lot, then the elements' payloads back to
    // back. Reading is unchanged, since the array driver takes either form.
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:ident),* $(,)? ]) => {
        $crate::__beve_array_body!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ] {
            const ARRAY: ::core::option::Option<&'static [u8]> =
                <$elem as $crate::beve::Write>::ARRAY;

            // The fields are gathered into a block first, because a payload is
            // one contiguous run and a struct's fields are not required to be
            // laid out as one. It costs a copy of the values, which for the
            // types that have a typed array is a few registers, and it is what
            // lets the element type decide the encoding: a run of booleans
            // packs to bits here exactly as it does in a `Vec<bool>`.
            #[inline]
            fn write_payload<O: $crate::Options>(
                &self,
                w: &mut $crate::beve::Writer<'_, O>,
            ) {
                <$elem as $crate::beve::Write>::write_payload(&[$( self.$field ),*], w);
            }
        });
    };
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:ident),* $(,)? ]) => {
        $crate::__beve_array_body!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ] {});
    };
}

/// The BEVE impls themselves, with `$typed` holding the two items that make a
/// struct a typed array, or nothing.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_array_body {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:ident),* ] { $($typed:tt)* }
    ) => {
        impl<$de $($rgen)*> $crate::beve::ReadArray<$de> for $ty {
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn read_element<O: $crate::Options>(
                &mut self,
                index: usize,
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::beve::Read::read(&mut self.$field, r);
                    }
                    i += 1;
                )*
                ::core::result::Result::Err($crate::ErrorCode::ArrayLengthMismatch)
            }
        }

        impl<$($wgen)*> $crate::beve::WriteArray for $ty {
            #[inline]
            fn write_elements<O: $crate::Options>(
                &self,
                w: &mut $crate::beve::Writer<'_, O>,
            ) {
                // The element count went out with the array header, so an
                // element is its value and nothing else.
                $( w.element(&self.$field); )*
            }

            $($typed)*
        }

        impl<$de $($rgen)*> $crate::beve::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                r.read_array(self)
            }
        }

        impl<$($wgen)*> $crate::beve::Write for $ty {
            #[inline]
            fn write<O: $crate::Options>(&self, w: &mut $crate::beve::Writer<'_, O>) {
                w.write_array(self);
            }
        }
    };
}

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

/// Declare an enum whose variants carry nothing, for every format.
///
/// The value on the wire is the variant's name, as a string. Names default to
/// the Rust ones; give an explicit name with `"name" => Variant` when the
/// encoded spelling differs.
///
/// ```
/// #[derive(Default, PartialEq, Debug)]
/// enum Level {
///     #[default]
///     Info,
///     Warning,
///     Error,
/// }
///
/// structio::unit_enum!(Level { Info, Warning, Error });
///
/// assert_eq!(structio::to_string(&Level::Warning), "\"Warning\"");
/// assert_eq!(structio::from_str::<Level>("\"Error\"").unwrap(), Level::Error);
/// ```
///
/// Renaming, which is how a Rust name that is not the wire name is handled:
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Level { #[default] Info, Warning }
/// structio::unit_enum!(Level {
///     "info" => Info,
///     "warning" => Warning,
/// });
/// # assert_eq!(structio::to_string(&Level::Info), "\"info\"");
/// ```
///
/// A [case rule](crate::case) renames the lot at once, and reads a variant
/// name as words rather than as a snake_case string, so the capitals a Rust
/// variant is spelled with are where it splits.
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Mode { #[default] ReadOnly, ReadWrite }
/// structio::unit_enum!(Mode as "kebab-case" { ReadOnly, ReadWrite });
/// # assert_eq!(structio::to_string(&Mode::ReadWrite), "\"read-write\"");
/// ```
///
/// # Why it is a macro of its own
///
/// It will not compile if a variant carries a value, so the wire form is a
/// plain string and stays one. That promise is worth stating on its own for a
/// type whose encoding other people depend on, and in BEVE it pays for itself:
/// a value that can only be a string means a run of them is a **string array**,
/// one header for the whole run, so a `Vec<Level>` comes out byte for byte what
/// a `Vec<String>` of the same names would.
/// [`tagged_enum!`](crate::tagged_enum) cannot do that even for a declaration
/// that happens to be all unit variants, since a variant carrying a value
/// writes an object. Reading is unaffected either way: a sequence of enums
/// takes a string array or a generic one however it was written.
///
/// # Internal tagging
///
/// `as tag "kind"` puts the variant name inside the payload's object rather
/// than in a key wrapping it:
///
/// | The variant | No tag clause | `as tag "kind"` |
/// |---|---|---|
/// | Carries nothing | `"Empty"` | `{"kind":"Empty"}` |
/// | Carries a value | `{"Circle":{"radius":1}}` | `{"kind":"Circle","radius":1}` |
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # struct Circle { r: f64 }
/// # structio::object!(Circle { r });
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Shape { #[default] Empty, Circle(Circle) }
/// structio::tagged_enum!(Shape as tag "kind" { Empty, Circle(_) });
/// assert_eq!(structio::to_string(&Shape::Circle(Circle { r: 1.0 })), r#"{"kind":"Circle","r":1}"#);
/// assert_eq!(structio::to_string(&Shape::Empty), r#"{"kind":"Empty"}"#);
/// ```
///
/// This is the shape most JSON APIs settled on, and the one a C++ Glaze
/// `std::variant` with a declared tag produces. It is the only form here that
/// a deduced variant can be made to agree with, external tagging having no
/// place to put the payload's own keys.
///
/// The clause goes after the type and after a [case rule](crate::case), which
/// applies to the variant names as it does elsewhere. The tag key itself is a
/// literal and is never converted. A per-variant name literal
/// (`"read" => ReadFile(_)`) and generics work as they do without the clause.
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # struct Read { path: String }
/// # structio::object!(Read { path });
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Op { #[default] Noop, ReadFile(Read) }
/// structio::tagged_enum!(Op as "kebab-case" tag "op" { Noop, ReadFile(_) });
/// # assert_eq!(structio::to_string(&Op::Noop), r#"{"op":"noop"}"#);
/// ```
///
/// ## The tag has to come first
///
/// **A document whose object begins with any other key is
/// [`ExpectedTag`](crate::ErrorCode::ExpectedTag).** This crate reads in one
/// pass with no lookahead and no buffering, so the member that decides which
/// variant is being read has to arrive before the members whose meaning it
/// decides. Finding a tag further in means holding the object somewhere or
/// walking it twice, and neither is a thing this crate does.
///
/// The restriction is on *reading*. Writing always puts the tag first, so a
/// value written by this crate reads back unconditionally, and so does one
/// from any producer that emits its tag first, which is the conventional
/// ordering and what a declaration-ordered serializer does by default. A
/// producer that puts it last is refused, loudly and with the offending key's
/// position, rather than misread.
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # struct Circle { r: f64 }
/// # structio::object!(Circle { r });
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Shape { #[default] Empty, Circle(Circle) }
/// # structio::tagged_enum!(Shape as tag "kind" { Empty, Circle(_) });
/// use structio::{ErrorCode, from_str};
///
/// assert_eq!(
///     from_str::<Shape>(r#"{"kind":"Circle","r":1}"#).unwrap(),
///     Shape::Circle(Circle { r: 1.0 }),
/// );
/// // The same members, the tag last.
/// assert_eq!(
///     from_str::<Shape>(r#"{"r":1,"kind":"Circle"}"#).unwrap_err().code,
///     ErrorCode::ExpectedTag,
/// );
/// ```
///
/// ## What a payload may be
///
/// An object, and nothing else. The variant's members share one object with
/// the tag, so a payload with no members of its own to share has nowhere to
/// go: `Sides(u32)` is a compile error naming [`Keys`](crate::Keys), and then
/// [`WriteObject`](crate::json::WriteObject) and its neighbours, rather than a
/// runtime surprise. Declare such a variant's payload as a struct, or drop the
/// tag clause, external tagging taking any payload because it gives it an
/// object of its own.
///
/// A variant carrying nothing is written as the tag alone and reads back from
/// it. Members beside it meet the reader's policy exactly as an unknown member
/// of a struct does: refused under [`Standard`](crate::Standard), stepped over
/// under [`SkipUnknown`](crate::SkipUnknown).
///
/// **A tag that is also a payload's field is refused at compile time.** The
/// two share one object, so a collision would write the name twice
/// (`{"kind":"Config","kind":"debug"}`), which this crate reads back and a
/// last-wins parser does not: it keeps the field and loses the variant. The
/// comparison is of wire names, so it catches a collision that only exists
/// after a [case rule](crate::case) has been applied.
///
/// A declaration with no generics is checked by `cargo check`. A generic one
/// has no payload keys until it is instantiated, so it is checked when the
/// crate is built, which is [`Keys::REQUIRED`](crate::Keys::REQUIRED)'s tier.
///
/// # What it expands to
///
/// One [`Variants`](crate::Variants) impl carrying the name list and its
/// compile-time perfect hash, and then, for each format, `ReadEnum` and
/// `Read`/`Write`, with BEVE's `Write` also carrying the string array. The
/// names are hashed by the same [`KeyMap`](crate::KeyMap) that finds a
/// struct's fields.
///
/// # Further reading
///
/// [docs/enums.md](https://github.com/stephenberry/structio/blob/main/docs/enums.md) is the long form: every error an enum can
/// produce and what distinguishes it from the others, how the policies meet a
/// tag, generics and borrowed payloads, the string array a run of unit
/// variants becomes in BEVE, and how validation, pointers and transcoding walk
/// through one.
#[macro_export]
macro_rules! unit_enum {
    // Every variant a bare name. Parentheses do not parse here, and that
    // refusal is what lets the impls below know the value is always a string.
    //
    // Generics take a rule of their own rather than an optional group, because
    // a type may itself begin with `[` and the parser cannot tell which is
    // meant until it has committed.
    ([$($gen:tt)*] $ty:ty as $case:tt { $($($name:literal =>)? $variant:ident),* $(,)? }) => {
        $crate::__declare_enum!(
            __both_unit_enum_impls [$($gen)*] $ty as $case { $($($name =>)? $variant),* }
        );
    };
    ([$($gen:tt)*] $ty:ty { $($($name:literal =>)? $variant:ident),* $(,)? }) => {
        $crate::__declare_enum!(
            __both_unit_enum_impls [$($gen)*] $ty { $($($name =>)? $variant),* }
        );
    };
    ($ty:ty as $case:tt { $($($name:literal =>)? $variant:ident),* $(,)? }) => {
        $crate::__declare_enum!(
            __both_unit_enum_impls $ty as $case { $($($name =>)? $variant),* }
        );
    };
    ($ty:ty { $($($name:literal =>)? $variant:ident),* $(,)? }) => {
        $crate::__declare_enum!(
            __both_unit_enum_impls $ty { $($($name =>)? $variant),* }
        );
    };
    // Anything else, which is overwhelmingly a variant written `Name(_)`, and
    // after that a tag clause. Without this the failure is `no rules expected
    // `(`` pointed at a matcher inside this crate, which tells the reader
    // nothing about what to do.
    ($($rest:tt)*) => {
        ::core::compile_error!(
            "`unit_enum!` takes a type and a brace-delimited list of variant \
             names, each optionally renamed with `\"name\" => Variant`. A \
             variant that carries a value, written `Variant(_)`, belongs to \
             `tagged_enum!` instead, and so does a tag clause: a unit enum's \
             value is a bare name, with no object for a tag to go in."
        );
    };
}

/// Declare an enum, for every format.
///
/// A variant that carries nothing is written as its name. A variant that
/// carries a value is written as an object of one member, keyed by that name:
/// the tagged-union form, with the tag being the name rather than a position,
/// so adding or reordering variants does not change what a document means.
///
/// That is *external* tagging, where the name wraps the payload, and it is
/// what a declaration with no tag clause gets. Adding `as tag "..."` moves the
/// name **inside** the payload's object instead, as a member beside the
/// payload's own; see [Internal tagging](#internal-tagging) below.
///
/// Mark a variant that carries a value with `(_)`. The payload's type is not
/// repeated here; it is already on the enum, and stating it twice would be a
/// second place to keep in step.
///
/// ```
/// #[derive(Default, PartialEq, Debug)]
/// struct Circle { radius: f64 }
/// structio::object!(Circle { radius });
///
/// #[derive(Default, PartialEq, Debug)]
/// enum Shape {
///     #[default]
///     Empty,
///     Circle(Circle),
///     Sides(u32),
/// }
///
/// structio::tagged_enum!(Shape {
///     Empty,
///     Circle(_),
///     Sides(_),
/// });
///
/// assert_eq!(structio::to_string(&Shape::Empty), "\"Empty\"");
/// assert_eq!(
///     structio::to_string(&Shape::Circle(Circle { radius: 2.0 })),
///     r#"{"Circle":{"radius":2}}"#
/// );
/// assert_eq!(
///     structio::from_str::<Shape>(r#"{"Sides":3}"#).unwrap(),
///     Shape::Sides(3)
/// );
/// ```
///
/// Names are renamed the same way a field is, they take a
/// [case rule](crate::case) the same way, and generics go in brackets before
/// the type, exactly as for [`object!`]:
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Message<T> { #[default] Ping, Data(T) }
/// structio::tagged_enum!([T: structio::ReadWrite + Default] Message<T> {
///     "ping" => Ping,
///     "data" => Data(_),
/// });
/// # assert_eq!(structio::to_string(&Message::Data(vec![1u8, 2])), r#"{"data":[1,2]}"#);
/// ```
///
/// # One payload, of a type you already declared
///
/// A variant carries at most one value, which is the shape a
/// `std::variant<A, B, C>` has and the one that composes: the payload is an
/// ordinary type, declared with [`object!`] or [`array!`] or built in, and the
/// enum adds only the tag. A Rust variant with several fields, or with named
/// fields, is not accepted; give it a struct or a tuple instead. Neither is
/// [`object!`]'s `#[required]` marker, which has nothing to say here: a variant
/// declared as carrying a value can be read only from the object form that
/// holds one, so its payload is required by the declaration itself.
///
/// A payload type needs [`Default`], for the reason an `Option`'s payload
/// does: reading a variant the destination is not already holding has to build
/// one before it can read into it.
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Span { #[default] None, Range((u32, u32)) }
/// structio::tagged_enum!(Span { None, Range(_) });
/// assert_eq!(structio::to_string(&Span::Range((1, 5))), r#"{"Range":[1,5]}"#);
/// ```
///
/// # What is read back
///
/// The two forms are not interchangeable, and the asymmetry runs one way. A
/// variant carrying nothing reads from either, so a producer that always
/// writes the object form still round-trips. A variant carrying a value has
/// only the object form: the name on its own leaves the value missing, which
/// is [`ExpectedBrace`](crate::ErrorCode::ExpectedBrace) in JSON and
/// [`ExpectedObject`](crate::ErrorCode::ExpectedObject) in BEVE rather than an
/// unknown variant, the name having been recognized and the value under it
/// not being there.
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Shape { #[default] Empty, Sides(u32) }
/// # structio::tagged_enum!(Shape { Empty, Sides(_) });
/// use structio::{ErrorCode, from_str};
///
/// // A variant carrying nothing takes either form.
/// assert_eq!(from_str::<Shape>("\"Empty\"").unwrap(), Shape::Empty);
/// assert_eq!(from_str::<Shape>(r#"{"Empty":null}"#).unwrap(), Shape::Empty);
///
/// // A variant carrying a value takes the object form and only that.
/// assert_eq!(from_str::<Shape>(r#"{"Sides":6}"#).unwrap(), Shape::Sides(6));
/// assert_eq!(
///     from_str::<Shape>("\"Sides\"").unwrap_err().code,
///     ErrorCode::ExpectedBrace,
/// );
/// ```
///
/// What is refused is a name no variant claims, and that is refused under
/// every policy, including [`SkipUnknown`](crate::SkipUnknown). Stepping over
/// an unknown object key still leaves the object readable; stepping over an
/// unknown variant would leave the value itself undecided.
///
/// An object that is not exactly one member, `{}` or two tags at once, and a
/// value that is neither an object nor a string, are
/// [`ExpectedVariant`](crate::ErrorCode::ExpectedVariant). Under the object
/// form a variant carrying nothing wants `null` specifically, so `{"Empty":0}`
/// is [`ExpectedNull`](crate::ErrorCode::ExpectedNull).
///
/// Reading reuses what the destination already holds when it is already the
/// variant being read, so a loop that reads the same variant repeatedly keeps
/// its payload's buffers. Reading a *different* variant replaces the value,
/// which is what changing variants means.
///
/// # What it expands to
///
/// One [`Variants`](crate::Variants) impl carrying the name list and its
/// compile-time perfect hash, and then, for each format, `ReadEnum` and
/// `Read`/`Write`. Each `write` ends with a `match` over every declared
/// variant whose arms are empty, dead code that asks the compiler to confirm
/// the declaration names every variant the enum has, so extending the enum
/// later and forgetting to say so here is a compile error rather than a value
/// that silently writes nothing.
///
/// When a payload's type cannot support both formats, declare the enum with
/// [`json_tagged_enum!`](crate::json_tagged_enum) or [`beve_tagged_enum!`](crate::beve_tagged_enum) instead.
///
/// # Further reading
///
/// [docs/enums.md](https://github.com/stephenberry/structio/blob/main/docs/enums.md) is the long form: every error an enum can
/// produce and what distinguishes it from the others, how the policies meet a
/// tag, generics and borrowed payloads, the string array a run of unit
/// variants becomes in BEVE, and how validation, pointers and transcoding walk
/// through one.
#[macro_export]
macro_rules! tagged_enum {
    ($($t:tt)*) => { $crate::__declare_enum!(__both_enum_impls $($t)*); };
}

/// Declare an enum for JSON alone.
///
/// The same syntax as [`tagged_enum!`](crate::tagged_enum), generating only the JSON impls. The
/// reasons to want it are [`json_object!`]'s.
#[macro_export]
macro_rules! json_tagged_enum {
    ($($t:tt)*) => { $crate::__declare_enum!(__json_enum_impls $($t)*); };
}

/// Declare an enum for BEVE alone.
///
/// The counterpart of [`json_tagged_enum!`](crate::json_tagged_enum), and what an enum with a borrowed
/// `&[u8]` payload needs.
#[macro_export]
macro_rules! beve_tagged_enum {
    ($($t:tt)*) => { $crate::__declare_enum!(__beve_enum_impls $($t)*); };
}

/// [`__declare!`](crate::__declare) for the enum forms.
///
/// The same normalization of the input lifetime, and the same two lists handed on. What it
/// shares across formats is [`Variants`](crate::Variants), the enum's
/// counterpart of [`Keys`](crate::Keys).
///
/// Alongside the case rule travels the **tag slot**: `[]` where the variant
/// name wraps the payload, `["kind"]` where it goes inside it. Both are
/// properties of the declaration rather than of either format, and the slot is
/// what the impl selectors dispatch on, so external and internal tagging share
/// one grammar and one entry point rather than two of each.
///
/// Arm order carries two rules. Within a generics group, the `tag` rules come
/// first, because `as $case:tt` would otherwise capture the `tag` keyword and
/// leave the literal stranded. Across groups, every bracketed rule comes before
/// every bare one, because a bare rule parses `$ty:ty` against a leading `[`
/// and a failure there is a hard error rather than a fall through to the next
/// rule: `[const N: usize]` is not a type, and saying so ends the compile.
#[doc(hidden)]
#[macro_export]
macro_rules! __declare_enum {
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!(
            $m [$de $($gen)*] [$de $($gen)*] [_] [$tag] $ty { $($body)* });
    };
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!(
            $m [$de $($gen)*] [$de $($gen)*] [$case] [$tag] $ty { $($body)* });
    };
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared_enum!($m [$de $($gen)*] [$de $($gen)*] [$case] [] $ty { $($body)* });
    };
    ($m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared_enum!($m [$de $($gen)*] [$de $($gen)*] [_] [] $ty { $($body)* });
    };
    ($m:ident [ $($gen:tt)* ] $ty:ty as tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de, $($gen)*] [$($gen)*] [_] [$tag] $ty { $($body)* });
    };
    ($m:ident [ $($gen:tt)* ] $ty:ty as $case:tt tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!(
            $m ['de, $($gen)*] [$($gen)*] [$case] [$tag] $ty { $($body)* });
    };
    ($m:ident [ $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de, $($gen)*] [$($gen)*] [$case] [] $ty { $($body)* });
    };
    ($m:ident [ $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de, $($gen)*] [$($gen)*] [_] [] $ty { $($body)* });
    };
    ($m:ident $ty:ty as tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de] [] [_] [$tag] $ty { $($body)* });
    };
    ($m:ident $ty:ty as $case:tt tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de] [] [$case] [$tag] $ty { $($body)* });
    };
    ($m:ident $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de] [] [$case] [] $ty { $($body)* });
    };
    ($m:ident $ty:ty { $($body:tt)* }) => {
        $crate::__declared_enum!($m ['de] [] [_] [] $ty { $($body)* });
    };
}

/// [`__declared!`](crate::__declared) for the enum forms.
///
/// Two arms rather than one slot holding an optional literal, because a tag is
/// not merely carried: where there is one, it also has to be checked against
/// the payload's own keys, which is what
/// [`__tag_check!`](crate::__tag_check) is.
#[doc(hidden)]
#[macro_export]
macro_rules! __declared_enum {
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty { $($body:tt)* }) => {
        $crate::__case_check!($case);
        $crate::__variants_impl!([$($wgen)*] [$case] $ty { $($body)* });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] [] $ty { $($body)* });
    };
    (
        $m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($body:tt)*
        }
    ) => {
        $crate::__case_check!($case);
        $crate::__variants_impl!([$($wgen)*] [$case] $ty { $($body)* });
        $crate::__tag_check!([$($wgen)*] [$tag] $ty { $($body)* });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] [$tag] $ty { $($body)* });
    };
}

/// Both formats, for [`unit_enum!`](crate::unit_enum). The JSON half is the
/// tagged one unchanged; only BEVE has anything to add.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_unit_enum_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty { $($body:tt)* }) => {
        $crate::__json_enum_impls!([$($rgen)*] [$($wgen)*] [$case] [] $ty { $($body)* });
        $crate::__beve_unit_enum_impls!([$($rgen)*] [$($wgen)*] [$case] $ty { $($body)* });
    };
}

/// Both formats, for [`tagged_enum!`](crate::tagged_enum).
///
/// The tag slot passes through untouched: which of the two tagging conventions
/// a declaration asked for is settled once, in each format's own selector,
/// rather than here and there both.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_enum_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$($tag:literal)?] $ty:ty { $($body:tt)* }) => {
        $crate::__json_enum_impls!([$($rgen)*] [$($wgen)*] [$case] [$($tag)?] $ty { $($body)* });
        $crate::__beve_enum_impls!([$($rgen)*] [$($wgen)*] [$case] [$($tag)?] $ty { $($body)* });
    };
}

/// Refuse a tag that is also a field of some variant's payload, at the
/// earliest point the payload's keys are known.
///
/// For a declaration with no generics that point is here, in an item-level
/// `const` whose value is monomorphic and so is evaluated during `cargo
/// check`. A generic declaration has no keys until it is instantiated, so this
/// expands to nothing and the write path's `const` block carries the check
/// instead; see [`__tag_check_generic!`](crate::__tag_check_generic). Exactly
/// one of the two is live per declaration, so nothing is checked twice.
#[doc(hidden)]
#[macro_export]
macro_rules! __tag_check {
    (
        [] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        $( $crate::__tag_check_one!([$tag] $ty, $variant $(($($payload)*))?); )*
    };
    ([$($wgen:tt)+] [$tag:literal] $ty:ty { $($body:tt)* }) => {};
}

/// One variant's share of [`__tag_check!`](crate::__tag_check).
///
/// The payload's type is named through the variant's constructor, which is a
/// value of type `fn(P) -> Self`. That is what makes the check possible at all
/// without the declaration repeating a type it already gave the enum.
#[doc(hidden)]
#[macro_export]
macro_rules! __tag_check_one {
    // Carries nothing, so it shares its object with no members and has nothing
    // the tag could collide with.
    ([$tag:literal] $ty:ty, $variant:ident) => {};
    ([$tag:literal] $ty:ty, $variant:ident ($($payload:tt)*)) => {
        const _: () = $crate::assert_tag_not_a_field($tag, <$ty>::$variant);
    };
}

/// [`__tag_check!`](crate::__tag_check) for a generic declaration, whose
/// payload keys exist only once instantiated.
///
/// Expands to nothing when there are no generics, the item-level check having
/// already covered that case.
#[doc(hidden)]
#[macro_export]
macro_rules! __tag_check_generic {
    ([] [$tag:literal] { $($body:tt)* }) => {};
    (
        [$($wgen:tt)+] [$tag:literal] {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        $( $crate::__tag_check_generic_one!([$tag] $variant $(($($payload)*))?); )*
    };
}

/// One variant's share of [`__tag_check_generic!`](crate::__tag_check_generic).
#[doc(hidden)]
#[macro_export]
macro_rules! __tag_check_generic_one {
    ([$tag:literal] $variant:ident) => {};
    ([$tag:literal] $variant:ident ($($payload:tt)*)) => {
        $crate::assert_tag_not_a_field($tag, Self::$variant);
    };
}

/// Refuse a variant payload spelled as anything but `(_)`.
///
/// The payload slot is a `tt` run, so without this it swallows whatever is put
/// between the parentheses and generates code that ignores it. The case that
/// matters is `Variant(_ as Adapter)`: adapters are a field-level feature that
/// [`tagged_enum!`](crate::tagged_enum) deliberately does not have yet, and a
/// user who has just met `field as Adapter` on [`object!`](crate::object) will
/// reach for it here. Silently writing the payload through its own `Write`
/// would be a document that is valid, wrong, and unremarked.
///
/// A `compile_error!` rather than a matcher that simply fails to match, for
/// the reason `unit_enum!`'s payload rejection uses one: a matcher error is
/// pointed into this crate rather than at the declaration that caused it.
#[doc(hidden)]
#[macro_export]
macro_rules! __payload_is_wildcard {
    () => {};
    (_) => {};
    ($($other:tt)*) => {
        ::core::compile_error!(
            "structio: a variant payload is written `(_)`, and carries no options of its own. \
             Field adapters (`as ...`) are supported on `object!` fields, not on enum payloads."
        );
    };
}

/// The format-independent half: the variant names and their compile-time hash.
#[doc(hidden)]
#[macro_export]
macro_rules! __variants_impl {
    (
        [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        $crate::__each_name_once!($($variant),*);
        $( $crate::__payload_is_wildcard!($($($payload)*)?); )*

        impl<$($wgen)*> $crate::Variants for $ty {
            const VARIANTS: &'static [&'static str] = &[
                $( $crate::__json_key!([$case] $($name)? [$variant]) ),*
            ];
            // Built from `Self::VARIANTS`, and promoted to an anonymous static,
            // for the reasons `Keys::MAP` is.
            const MAP: &'static $crate::KeyMap = &$crate::KeyMap::build(Self::VARIANTS);
        }
    };
}

/// The JSON impls for [`tagged_enum!`](crate::tagged_enum), of whichever
/// tagging convention the declaration's tag slot named.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_enum_impls {
    // A tag key: the name goes inside the payload's object, and the impls are
    // a different set rather than a variation on these.
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty { $($body:tt)* }
    ) => {
        $crate::__json_internal_enum_impls!(
            [$($rgen)*] [$($wgen)*] [$case] [$tag] $ty { $($body)* });
    };
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        impl<$de $($rgen)*> $crate::json::ReadEnum<$de> for $ty {
            // Deliberately not `inline(always)`, for `read_field`'s reason:
            // this body holds an arm for every variant.
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn read_name<O: $crate::Options>(
                &mut self,
                index: usize,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                // The same const-folding counter `read_field` uses, and for the
                // same reason: expansion stays linear in the variant count.
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::__json_read_name!(
                            self, p,
                            $crate::__json_key!([$case] $($name)? [$variant]),
                            $variant $(($($payload)*))?
                        );
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }

            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut, unreachable_patterns)]
            fn read_payload<O: $crate::Options>(
                &mut self,
                index: usize,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::__json_read_payload!(
                            self, p,
                            $crate::__json_key!([$case] $($name)? [$variant]),
                            $variant $(($($payload)*))?
                        );
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }
        }

        impl<$de $($rgen)*> $crate::json::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                p.read_enum(self)
            }
        }

        impl<$($wgen)*> $crate::json::Write for $ty {
            #[inline]
            #[allow(irrefutable_let_patterns)]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                // The duplicate-name check is in `KeyMap::build`, which nothing
                // reaches but `Variants::MAP`. Reading looks a name up and so
                // evaluates it; writing has no use for it, and a generic
                // type's associated const is evaluated only when something
                // names it, so a generic declaration that is never read would
                // otherwise write two variants under one name. Naming it here
                // costs nothing and closes that.
                const {
                    let _ = <Self as $crate::Variants>::MAP;
                };
                $(
                    $crate::__write_variant!(
                        self, w,
                        $crate::__json_key!([$case] $($name)? [$variant]),
                        $crate::__json_member!([$case] $($name)? [$variant]),
                        $variant $(($($payload)*))?
                    );
                )*
                // Every variant returned above. This says so to the compiler,
                // which is what makes extending the enum without extending the
                // declaration a build error instead of a value that writes
                // nothing at all.
                match self { $( Self::$variant { .. } => {} ),* }
            }
        }
    };
}

/// One arm of the JSON `read_name`: the bare-name form.
///
/// `macro_rules!` cannot branch inside a repetition, so everywhere the two
/// kinds of variant differ goes through a helper with one rule for each. This
/// is the first of five, and the rest follow its shape.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_name {
    // Carries nothing, so the name is the whole value.
    ($self:ident, $p:ident, $name:expr, $variant:ident) => {
        if $p.match_key($name) {
            *$self = Self::$variant;
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
    // Carries a value, which the bare form has nowhere to put. The name was
    // recognized, so this is not an unknown variant: what is missing is the
    // object that would have held the value.
    ($self:ident, $p:ident, $name:expr, $variant:ident ($($payload:tt)*)) => {
        if $p.match_key($name) {
            ::core::result::Result::Err($crate::ErrorCode::ExpectedBrace)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
}

/// One arm of the JSON `read_payload`: the single member of an object.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_payload {
    // Carries nothing. Written as a bare name, but accepted here as well, so a
    // producer that always writes the object form round-trips.
    ($self:ident, $p:ident, $name:expr, $variant:ident) => {
        if $p.match_key($name) {
            $p.colon()?;
            if $p.try_null()? {
                *$self = Self::$variant;
                ::core::result::Result::Ok(true)
            } else {
                // The name is this variant's, so the value is not a tag that
                // went unrecognized: it is one that named a variant carrying
                // nothing and then put something under it.
                ::core::result::Result::Err($crate::ErrorCode::ExpectedNull)
            }
        } else {
            ::core::result::Result::Ok(false)
        }
    };
    ($self:ident, $p:ident, $name:expr, $variant:ident ($($payload:tt)*)) => {
        if $p.match_key($name) {
            $p.colon()?;
            // Read into what is already there when it is already this variant,
            // so a payload's buffers survive the read the way a struct field's
            // do. Anything else is replaced, which is what changing variants
            // means.
            match $self {
                Self::$variant(v) => {
                    $crate::json::Read::read(v, $p)?;
                }
                _ => {
                    let mut value = ::core::default::Default::default();
                    $crate::json::Read::read(&mut value, $p)?;
                    *$self = Self::$variant(value);
                }
            }
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __json_internal_enum_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        impl<$de $($rgen)*> $crate::json::ReadInternallyTagged<$de> for $ty {
            const TAG: &'static str = $tag;

            // Deliberately not `inline(always)`, for `read_field`'s reason:
            // this body holds an arm for every variant.
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut, unreachable_patterns)]
            fn read_variant<O: $crate::Options>(
                &mut self,
                index: usize,
                p: &mut $crate::json::Parser<$de, O>,
                open: usize,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                // The same const-folding counter `read_field` uses, and for the
                // same reason: expansion stays linear in the variant count.
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::__json_read_internal!(
                            self, p, open,
                            $crate::__json_key!([$case] $($name)? [$variant]),
                            $variant $(($($payload)*))?
                        );
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }
        }

        impl<$de $($rgen)*> $crate::json::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                p.read_internally_tagged(self)
            }
        }

        impl<$($wgen)*> $crate::json::Write for $ty {
            #[inline]
            #[allow(irrefutable_let_patterns)]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                // Named for `__json_enum_impls`'s reason: this is the only
                // place writing evaluates the map, and so the only place a
                // generic declaration's duplicate names are caught. The tag
                // check rides along for the same reason, a generic payload
                // having no keys until it is instantiated.
                const {
                    let _ = <Self as $crate::Variants>::MAP;
                    $crate::__tag_check_generic!([$($wgen)*] [$tag] {
                        $($($name =>)? $variant $(($($payload)*))?),*
                    });
                };
                $(
                    $crate::__write_internal_variant!(
                        self, w,
                        $crate::__json_key!([$case] $($name)? [$variant]),
                        // The tag key is a literal and is never case
                        // converted: it names a member of the document, not a
                        // variant of the enum. A literal key's prefix comes
                        // from `concat!`, which is what `__json_member!` exists
                        // to stand in for where the key is *computed*.
                        ::core::concat!("\"", $tag, "\":"),
                        $variant $(($($payload)*))?
                    );
                )*
                // Every variant returned above, which is what makes extending
                // the enum without extending the declaration a build error.
                match self { $( Self::$variant { .. } => {} ),* }
            }
        }
    };
}

/// One arm of the JSON `read_variant`.
///
/// The cursor sits inside the tag value's opening quote, so the name is
/// matched exactly as [`__json_read_name!`](crate::__json_read_name) matches
/// one. What differs is what follows: the rest of the enclosing object, which
/// belongs to the payload.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_internal {
    // Carries nothing, so the tag was the object's whole content. Members
    // beside it are unknown ones and meet the policy that governs those.
    ($self:ident, $p:ident, $open:ident, $name:expr, $variant:ident) => {
        if $p.match_key($name) {
            // Assigned after the object is consumed, not before, so a read
            // that fails on a member beside the tag leaves the destination
            // holding what it held.
            $p.finish_internally_tagged()?;
            *$self = Self::$variant;
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
    // Carries a value, whose members share the object with the tag.
    ($self:ident, $p:ident, $open:ident, $name:expr, $variant:ident ($($payload:tt)*)) => {
        if $p.match_key($name) {
            // Reading into what is already there, for
            // `__json_read_payload!`'s reason.
            match $self {
                Self::$variant(v) => {
                    $p.read_object_rest(v, $open)?;
                }
                _ => {
                    let mut value = ::core::default::Default::default();
                    $p.read_object_rest(&mut value, $open)?;
                    *$self = Self::$variant(value);
                }
            }
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __beve_internal_enum_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        impl<$de $($rgen)*> $crate::beve::ReadInternallyTagged<$de> for $ty {
            const TAG: &'static str = $tag;

            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut, unreachable_patterns)]
            fn read_variant<O: $crate::Options>(
                &mut self,
                index: usize,
                name: &[u8],
                r: &mut $crate::beve::Reader<$de, O>,
                remaining: usize,
                open: usize,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::__beve_read_internal!(
                            self, name, r, remaining, open,
                            $crate::__json_key!([$case] $($name)? [$variant]),
                            $variant $(($($payload)*))?
                        );
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }
        }

        impl<$de $($rgen)*> $crate::beve::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                r.read_internally_tagged(self)
            }
        }

        impl<$($wgen)*> $crate::beve::Write for $ty {
            #[inline]
            #[allow(irrefutable_let_patterns)]
            fn write<O: $crate::Options>(&self, w: &mut $crate::beve::Writer<'_, O>) {
                const {
                    let _ = <Self as $crate::Variants>::MAP;
                    $crate::__tag_check_generic!([$($wgen)*] [$tag] {
                        $($($name =>)? $variant $(($($payload)*))?),*
                    });
                };
                $(
                    $crate::__write_internal_variant!(
                        self, w,
                        $crate::__json_key!([$case] $($name)? [$variant]),
                        $crate::__beve_key_bytes!($tag),
                        $variant $(($($payload)*))?
                    );
                )*
                match self { $( Self::$variant { .. } => {} ),* }
            }
        }
    };
}

/// One arm of the BEVE `read_variant`.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_internal {
    ($self:ident, $key:ident, $r:ident, $remaining:ident, $open:ident, $name:expr, $variant:ident) => {
        if $key == $name.as_bytes() {
            // Assigned after the object is consumed, for the JSON arm's reason.
            $r.finish_internally_tagged($remaining)?;
            *$self = Self::$variant;
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
    (
        $self:ident, $key:ident, $r:ident, $remaining:ident, $open:ident, $name:expr,
        $variant:ident ($($payload:tt)*)
    ) => {
        if $key == $name.as_bytes() {
            match $self {
                Self::$variant(v) => {
                    $r.read_object_rest(v, $remaining, $open)?;
                }
                _ => {
                    let mut value = ::core::default::Default::default();
                    $r.read_object_rest(&mut value, $remaining, $open)?;
                    *$self = Self::$variant(value);
                }
            }
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
}

/// One arm of an internally tagged `write`, in either format.
///
/// [`__write_variant!`](crate::__write_variant)'s counterpart, and shared
/// between the formats for the same reason: the two calls are spelled the same
/// in both, and only the pre-encoded tag key differs.
#[doc(hidden)]
#[macro_export]
macro_rules! __write_internal_variant {
    ($self:ident, $w:ident, $name:expr, $tag:expr, $variant:ident) => {
        if let Self::$variant = $self {
            // An object of one member whose value is the name, which is
            // exactly what `write_tagged` writes for an externally tagged
            // payload. Same bytes, so there is no second writer for it.
            $w.write_tagged($tag, $name);
            return;
        }
    };
    ($self:ident, $w:ident, $name:expr, $tag:expr, $variant:ident ($($payload:tt)*)) => {
        if let Self::$variant(v) = $self {
            $w.write_internally_tagged($tag, $name, v);
            return;
        }
    };
}

/// One arm of `write`, in either format.
///
/// The one helper the two formats share, because the two calls are spelled the
/// same in both: a variant carrying nothing is its name, and one carrying a
/// value is a tag. Only the pre-encoded key differs, so it is passed in rather
/// than built here.
#[doc(hidden)]
#[macro_export]
macro_rules! __write_variant {
    ($self:ident, $w:ident, $name:expr, $key:expr, $variant:ident) => {
        if let Self::$variant = $self {
            $w.write_str($name);
            return;
        }
    };
    ($self:ident, $w:ident, $name:expr, $key:expr, $variant:ident ($($payload:tt)*)) => {
        if let Self::$variant(v) = $self {
            $w.write_tagged($key, v);
            return;
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __beve_enum_impls {
    // A tag key, for [`__json_enum_impls!`](crate::__json_enum_impls)'s reason.
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty { $($body:tt)* }
    ) => {
        $crate::__beve_internal_enum_impls!(
            [$($rgen)*] [$($wgen)*] [$case] [$tag] $ty { $($body)* });
    };
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        }
    ) => {
        $crate::__beve_enum_body!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($($name =>)? $variant $(($($payload)*))?),*
        } {});
    };
}

/// The BEVE impls for [`unit_enum!`](crate::unit_enum), which are the tagged
/// ones plus a typed array.
///
/// A unit enum's value is a string and can be nothing else, so a run of them is
/// a **string array**: one header for the lot and a length-prefixed name per
/// element, exactly as a `Vec<String>` is stored, rather than a generic array
/// carrying a string header per element. Nothing on the reading side changes,
/// since the sequence driver installs a typed array's element header and hands
/// out one value either way, so the two forms stay interchangeable.
///
/// [`tagged_enum!`](crate::tagged_enum) cannot do this even for a declaration
/// that happens to be all unit variants: `ARRAY` is one constant for the type,
/// and a variant carrying a value writes an object.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_unit_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($($name:literal =>)? $variant:ident),* $(,)?
        }
    ) => {
        $crate::__beve_enum_body!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($($name =>)? $variant),*
        } {
            const ARRAY: ::core::option::Option<&'static [u8]> =
                ::core::option::Option::Some(&[$crate::beve::header::STRING_ARRAY]);

            #[inline]
            fn write_payload<O: $crate::Options>(
                items: &[Self],
                w: &mut $crate::beve::Writer<'_, O>,
            ) where
                Self: ::core::marker::Sized,
            {
                // The header and count are already out, so an element is its
                // name with a length in front and nothing else. A real `match`
                // here, where `write` needs a chain, because this macro's own
                // matcher has already refused a variant that carries a value:
                // every arm has the same shape, so nothing has to branch and
                // the compiler checks the arms cover the enum.
                for item in items {
                    w.write_str_body(match item {
                        $( Self::$variant => $crate::__json_key!([$case] $($name)? [$variant]) ),*
                    });
                }
            }
        });
    };
}

/// The BEVE impls themselves, with `$typed` holding the two items that make a
/// run of this enum a string array, or nothing.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_enum_body {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))?),* $(,)?
        } { $($typed:tt)* }
    ) => {
        impl<$de $($rgen)*> $crate::beve::ReadEnum<$de> for $ty {
            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn read_name(
                &mut self,
                index: usize,
                name: &[u8],
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::__beve_read_name!(
                            self, name,
                            $crate::__json_key!([$case] $($name)? [$variant]),
                            $variant $(($($payload)*))?
                        );
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }

            #[inline]
            #[allow(unused_assignments, unused_variables, unused_mut, unreachable_patterns)]
            fn read_payload<O: $crate::Options>(
                &mut self,
                index: usize,
                name: &[u8],
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<bool, $crate::ErrorCode> {
                let mut i = 0usize;
                $(
                    if index == i {
                        return $crate::__beve_read_payload!(
                            self, name, r,
                            $crate::__json_key!([$case] $($name)? [$variant]),
                            $variant $(($($payload)*))?
                        );
                    }
                    i += 1;
                )*
                ::core::result::Result::Ok(false)
            }
        }

        impl<$de $($rgen)*> $crate::beve::Read<$de> for $ty {
            #[inline]
            fn read<O: $crate::Options>(
                &mut self,
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                r.read_enum(self)
            }
        }

        impl<$($wgen)*> $crate::beve::Write for $ty {
            #[inline]
            #[allow(irrefutable_let_patterns)]
            fn write<O: $crate::Options>(&self, w: &mut $crate::beve::Writer<'_, O>) {
                // The duplicate-name check is in `KeyMap::build`, which nothing
                // reaches but `Variants::MAP`. Reading looks a name up and so
                // evaluates it; writing has no use for it, and a generic
                // type's associated const is evaluated only when something
                // names it, so a generic declaration that is never read would
                // otherwise write two variants under one name. Naming it here
                // costs nothing and closes that.
                const {
                    let _ = <Self as $crate::Variants>::MAP;
                };
                $(
                    $crate::__write_variant!(
                        self, w,
                        $crate::__json_key!([$case] $($name)? [$variant]),
                        $crate::__beve_key_bytes!($crate::__json_key!([$case] $($name)? [$variant])),
                        $variant $(($($payload)*))?
                    );
                )*
                // As on the JSON side: the compiler's word that the declaration
                // names every variant.
                match self { $( Self::$variant { .. } => {} ),* }
            }

            $($typed)*
        }
    };
}

/// One arm of the BEVE `read_name`.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_name {
    ($self:ident, $key:ident, $name:expr, $variant:ident) => {
        if $key == $name.as_bytes() {
            *$self = Self::$variant;
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
    ($self:ident, $key:ident, $name:expr, $variant:ident ($($payload:tt)*)) => {
        if $key == $name.as_bytes() {
            ::core::result::Result::Err($crate::ErrorCode::ExpectedObject)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
}

/// One arm of the BEVE `read_payload`.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_payload {
    ($self:ident, $key:ident, $r:ident, $name:expr, $variant:ident) => {
        if $key == $name.as_bytes() {
            if $r.try_null()? {
                *$self = Self::$variant;
                ::core::result::Result::Ok(true)
            } else {
                ::core::result::Result::Err($crate::ErrorCode::ExpectedNull)
            }
        } else {
            ::core::result::Result::Ok(false)
        }
    };
    ($self:ident, $key:ident, $r:ident, $name:expr, $variant:ident ($($payload:tt)*)) => {
        if $key == $name.as_bytes() {
            match $self {
                Self::$variant(v) => {
                    $crate::beve::Read::read(v, $r)?;
                }
                _ => {
                    let mut value = ::core::default::Default::default();
                    $crate::beve::Read::read(&mut value, $r)?;
                    *$self = Self::$variant(value);
                }
            }
            ::core::result::Result::Ok(true)
        } else {
            ::core::result::Result::Ok(false)
        }
    };
}