structio 0.8.0

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
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
//! 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.

/// The diagnostic for `read_only`, which the documentation's "there is no
/// `read_only`" is precisely the sentence that invites someone to try.
#[doc(hidden)]
#[macro_export]
macro_rules! __no_read_only {
    () => {
        ::core::compile_error!(
            "structio: a declaration narrows to the write half or to neither, \
             so there is no `read_only`. A type that is only ever read still \
             generates its write impls, and its fields still need them: a \
             field with nothing to say on the way out writes `null`, with \
             `is_null` returning `true` so that `SkipNull` drops the member"
        );
    };
}

/// The diagnostic for a type path whose first segment is a `write_only`
/// module, which the marker eats: such a path reaches a declaration as a
/// stray `::`, and without this the failure names a crate nobody wrote.
#[doc(hidden)]
#[macro_export]
macro_rules! __write_only_is_the_marker {
    () => {
        ::core::compile_error!(
            "structio: `write_only` in front of a declaration is the marker \
             that narrows it to the write half, so `write_only::..` was read \
             as that marker followed by a stray `::`. Name the type without \
             the leading `::`, or bring it into scope with a `use` and name \
             it there"
        );
    };
}

/// 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 field may answer to more than one key. Write the extra ones after it,
/// separated by `|`: the declared key is the one written, and any of them is
/// accepted on read.
///
/// ```
/// # use structio::{from_str, to_string};
/// #[derive(Debug, Default, PartialEq)]
/// struct Settings { timeout: u64 }
///
/// structio::object!(Settings { timeout | "timeout_ms" | "timeoutMs" });
///
/// let want = Settings { timeout: 30 };
/// assert_eq!(from_str::<Settings>(r#"{"timeout":30}"#).unwrap(), want);
/// assert_eq!(from_str::<Settings>(r#"{"timeout_ms":30}"#).unwrap(), want);
/// assert_eq!(to_string(&want), r#"{"timeout":30}"#);
/// ```
///
/// That is what renames a key without breaking the documents already written
/// under the old one: move the old spelling to an alias and both are read.
/// An alias is spelled out, so a [case rule](crate::case) leaves it alone, the
/// way an explicit `"key" =>` is left alone; it costs one more entry in the
/// key hash and one more comparison on the field it belongs to, and nothing
/// at all to a field that declares none. Aliases go after an adapter where
/// there is one, `elapsed as Millis | "elapsed_ms"`. There is no alias on a
/// `write_only` declaration, which never reads.
///
/// 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!`.
///
/// # One direction
///
/// A declaration that leads with `write_only` generates the write half alone:
/// the `Keys`, `WriteObject` and `Write` impls, and no read. Nothing in such a
/// struct needs a `Read` impl or a `Default`, since nothing constructs a value
/// or fills one.
///
/// ```
/// struct Handle(u32);
/// impl structio::json::Write for Handle {
///     fn write<O: structio::Options>(&self, w: &mut structio::json::Writer<'_, O>) {
///         self.0.write(w);
///     }
/// }
/// impl structio::beve::Write for Handle {
///     fn write<O: structio::Options>(&self, w: &mut structio::beve::Writer<'_, O>) {
///         self.0.write(w);
///     }
/// }
///
/// struct Surface { id: Handle, volts: f64 }
/// structio::object!(write_only Surface { id, volts });
///
/// let s = Surface { id: Handle(7), volts: 3.25 };
/// assert_eq!(structio::to_string(&s), r#"{"id":7,"volts":3.25}"#);
/// ```
///
/// It comes first, in front of the generics and the type, and the two axes
/// narrow independently, so `json_object!(write_only ..)` is one format and
/// one direction. A generic one bounds its type parameters by
/// [`Write`](crate::Write) rather than by [`ReadWrite`](crate::ReadWrite), and
/// needs no `Default`. `#[required]` is refused, being a rule about reading.
///
/// There is no `read_only`: a read constructs a value before it fills one, so
/// it is the half that asks a field's type for `Default` as well as for an
/// impl, and the one worth being able to drop.
#[macro_export]
macro_rules! object {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare!([write] __both_write_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare!([both] __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 {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare!([write] __json_write_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare!([both] __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 {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare!([write] __beve_write_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare!([both] __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.
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared!([$dir] $m [$de $($gen)*] [$de $($gen)*] [$case] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared!([$dir] $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.
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared!([$dir] $m ['de, $($gen)*] [$($gen)*] [$case] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared!([$dir] $m ['de, $($gen)*] [$($gen)*] [_] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared!([$dir] $m ['de] [] [$case] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident $ty:ty { $($body:tt)* }) => {
        $crate::__declared!([$dir] $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.
    ([$dir:tt] $m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
        $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)* ,)* ..
    }) => {
        $crate::__case_check!($case);
        $crate::__keys_impl!([$($wgen)*] [$case] [partial] [$dir] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
    };
    // Every field named, so the declaration is checked against the type.
    ([$dir:tt] $m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
        $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)*),* $(,)?
    }) => {
        $crate::__case_check!($case);
        $crate::__keys_impl!([$($wgen)*] [$case] [all] [$dir] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
    };
}

/// 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)* });
    };
}

/// Both formats, one direction, for `object!(write_only ..)`.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_write_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty { $($body:tt)* }) => {
        $crate::__json_write_impls!([$($rgen)*] [$($wgen)*] [$case] $ty { $($body)* });
        $crate::__beve_write_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 nothing else is looking.
///
/// [`__declares_every_field!`](crate::__declares_every_field) catches a repeat
/// too, a field given twice in a struct literal being an error, and it names
/// the field better than this does. It is not a substitute: it expands to
/// nothing for a declaration ending in `..`, which is exactly where a repeat is
/// otherwise silent. A declaration with both mistakes gets both messages, which
/// has always been so for names and is now so for positions.
#[doc(hidden)]
#[macro_export]
macro_rules! __each_name_once {
    ($($name:ident),* $(,)?) => {
        const _: () = {
            $( #[allow(dead_code, non_upper_case_globals)] const $name: () = (); )*
        };
    };
    // A tuple struct's fields are `0` and `1`, and `const 0: ()` is not a
    // declaration. They are numbers, though, which is the easier thing to
    // compare: the list goes into a slice and the check is arithmetic.
    ($($index:tt),* $(,)?) => {
        const _: () = {
            const AT: &[usize] = &[$($index),*];
            let mut i = 0;
            while i < AT.len() {
                let mut j = i + 1;
                while j < AT.len() {
                    ::core::assert!(
                        AT[i] != AT[j],
                        "structio: this positional declaration names the same field twice, \
                         so one field would go out in two places and another not at all."
                    );
                    j += 1;
                }
                i += 1;
            }
        };
    };
}

/// 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:tt),* }) => {};
    ([$($wgen:tt)*] [all] $ty:ty { $($field:tt),* }) => {
        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]`"
        ))
    };
}

/// One, for a token a `macro_rules!` repetition has to count.
///
/// The alias counter in [`__keys_impl!`](crate::__keys_impl) and
/// [`__variants_impl!`](crate::__variants_impl) runs during const evaluation
/// and cannot size the array it writes into, an array length being needed
/// before the block that fills it runs. A repetition summing this over the
/// aliases is that length, and the argument is there only to give the
/// repetition a variable to expand.
#[doc(hidden)]
#[macro_export]
macro_rules! __counts_one {
    ($t:tt) => {
        1usize
    };
}

/// Refuse an alias on a declaration that generates no read.
///
/// An alias is a rule about reading: it is a further name a document may use,
/// and the name a field or a variant is *written* under is the declared one
/// whatever aliases stand beside it. A `write_only` declaration never reads,
/// so an alias on one is a name nothing would ever look up, which is worth a
/// message rather than silence.
/// [`__required_direction!`](crate::__required_direction) refuses
/// `#[required]` there for the same reason.
///
/// The noun says which of the two is being declared, because a message that
/// called a variant a field would send the reader looking for one.
#[doc(hidden)]
#[macro_export]
macro_rules! __alias_direction {
    ([write] key $alias:literal) => {
        ::core::compile_error!(
            "an alias is a rule about reading: it is a further key a document \
             may use for this field, and the key the field is written under is \
             the declared one. A type declared `write_only` is never read, so \
             nothing would ever look this one up"
        )
    };
    ([write] name $alias:literal) => {
        ::core::compile_error!(
            "an alias is a rule about reading: it is a further name a document \
             may use for this variant, and the name the variant is written \
             under is the declared one. A type declared `write_only` is never \
             read, so nothing would ever look this one up"
        )
    };
    ([$dir:tt] $what:ident $alias:literal) => {};
}

/// 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] [$dir:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        $crate::__each_name_once!($($field),*);
        $crate::__declares_every_field!([$($wgen)*] [$mode] $ty { $($field),* });

        impl<$($wgen)*> $crate::Keys for $ty {
            // The fields first, in declaration order, then every alias, which
            // is the order `ALIASES` below is indexed against. Each entry
            // carries its own trailing comma, the two runs being separate
            // repetitions with no separator to put between them. An alias is
            // spelled out, so no case rule touches it, exactly as an explicit
            // `"key" =>` is left alone.
            const KEYS: &'static [&'static str] = &[
                $( $crate::__json_key!([$case] $($key)? [$field]), )*
                $( $( $alias, )* )*
            ];

            // Which field each of those aliases fills. `macro_rules!` cannot
            // count, so it is a const-evaluated counter, as `REQUIRED`'s is.
            // The whole block is empty for a declaration with no aliases, and
            // the width assertion with it.
            #[allow(unused_assignments, unused_mut)]
            const ALIASES: &'static [u8] = &{
                let mut of = [0u8; 0 $( $( + $crate::__counts_one!($alias) )* )*];
                let mut j = 0usize;
                let mut f = 0usize;
                $(
                    $(
                        assert!(
                            f <= u8::MAX as usize,
                            "an aliased field must be one of the first 256 \
                             declared: the field an alias fills is a u8"
                        );
                        of[j] = f as u8;
                        j += 1;
                        $crate::__alias_direction!([$dir] key $alias);
                    )*
                    f += 1;
                )*
                of
            };

            // Built from `Self::KEYS` rather than a second copy of the key
            // list, so the two cannot drift apart. It covers the aliases too,
            // which is what makes one lookup enough to find a field under any
            // of its names.
            //
            // `&` 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;
                $(
                    $crate::__required_direction!([$dir] $($req)?);
                    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
            };
        }
    };
}

/// Refuse `#[required]` on a declaration that generates no read.
///
/// The marker is a rule about reading: a document that leaves the member out
/// is `MissingKey`. A `write_only` declaration never reads, so the bit it
/// would set is one nothing consults, and a marker that does nothing is worth
/// a message rather than silence. The derive refuses the attribute for the
/// same reason, at the attribute.
#[doc(hidden)]
#[macro_export]
macro_rules! __required_direction {
    ([write] required) => {
        ::core::compile_error!(
            "`#[required]` is a rule about reading: a document that leaves \
             this member out is `MissingKey`. A type declared `write_only` is \
             never read, so there is nothing to require"
        )
    };
    // Any other marker, in either direction: a misspelling is
    // [`__is_required!`](crate::__is_required)'s to report, and this must not
    // speak over it with a rule the declaration never named.
    ([$dir:tt] $($marker:ident)?) => {};
}

/// Both directions, for a declaration that narrowed neither. The two halves
/// are separate macros so that `write_only` can ask for one of them.
#[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)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        $crate::__json_read_impls!([$de $($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
        $crate::__json_write_impls!([$de $($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
    };
}

/// The read half of a declaration: the per-field dispatch and the `Read` that
/// drives it.
///
/// Split from the write half because a declaration chooses its direction.
/// `write_only` emits the other half alone, and this one not at all, so a
/// field's type never has to satisfy a read the program does not perform.
///
/// 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_read_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        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. A field that declared
                        // aliases answers to any of them, and the caller has
                        // already put whichever one the hash found back on the
                        // field, so there is one arm either way.
                        if !(p.match_key($crate::__json_key!([$case] $($key)? [$field]))
                            $( || p.match_key($alias) )*)
                        {
                            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<$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)
            }
        }
    };
}

/// The write half of a declaration, which a `write_only` declaration emits by
/// itself.
///
/// The read generics arrive and are ignored. Nothing here is parameterized by
/// the input's lifetime: writing borrows from the value, not from a document.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_write_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        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<$($wgen)*> $crate::json::Write for $ty {
            #[inline]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                w.write_object(self);
            }
        }
    };
}

/// Both directions, for a declaration that narrowed neither. The two halves
/// are separate macros so that `write_only` can ask for one of them.
#[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)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        $crate::__beve_read_impls!([$de $($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
        $crate::__beve_write_impls!([$de $($rgen)*] [$($wgen)*] [$case] $ty {
            $($(#[$req])? $($key =>)? $field $(as $with)? $(| $alias)*),*
        });
    };
}

/// The read half of a declaration: the per-field dispatch and the `Read` that
/// drives it.
///
/// Split from the write half because a declaration chooses its direction.
/// `write_only` emits the other half alone, and this one not at all, so a
/// field's type never has to satisfy a read the program does not perform.
///
/// 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_read_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        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, and one more
                        // per alias the field declared.
                        if !(key == $crate::__json_key!([$case] $($key)? [$field]).as_bytes()
                            $( || key == $alias.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<$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)
            }
        }
    };
}

/// The write half of a declaration, which a `write_only` declaration emits by
/// itself.
///
/// The read generics arrive and are ignored. Nothing here is parameterized by
/// the input's lifetime: writing borrows from the value, not from a document.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($(#[$req:ident])? $($key:literal =>)? $field:ident $(as $with:ty)? $(| $alias:literal)*),* $(,)?
        }
    ) => {
        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<$($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 name arrives from `stringify!`, so a raw identifier still carries its
/// `r#` and [`case::unraw`](crate::case::unraw) takes it off. That happens
/// before the rule rather than after, so a rule respells the name rather than
/// the prefix. Every key in the crate is built here, JSON and BEVE, field and
/// variant, so this is the one place it has to happen.
///
/// 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]) => {
        $crate::case::unraw(::core::stringify!($field))
    };
    ([$case:tt] [$field:ident]) => {
        $crate::__case_apply!($case, $crate::case::unraw(::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)
    };
}

/// Write a field, through its adapter if it named one.
///
/// [`__json_read_as!`](crate::__json_read_as)'s other half, and needed where a
/// value is written on its own rather than as a member:
/// [`__write_member!`](crate::__write_member) covers the member case, key
/// included, and a [`transparent!`](crate::transparent) declaration has no
/// member to write.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_write_as {
    ($place:expr, $w:ident, $with:ty) => {
        <$with as $crate::json::WriteAs<_>>::write($place, $w)
    };
    ($place:expr, $w:ident) => {
        $crate::json::Write::write($place, $w)
    };
}

/// Ask whether a value is absent, of its adapter if one was named.
///
/// [`__beve_is_null_as!`](crate::__beve_is_null_as)'s JSON counterpart. A
/// declaration that writes members reaches the adapter's answer through
/// [`Writer::member_with`](crate::json::Writer::member_with); a
/// [`transparent!`](crate::transparent) one forwards `is_null` itself and so
/// has to ask here.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_is_null_as {
    ($place:expr, $with:ty) => {
        <$with as $crate::json::WriteAs<_>>::is_null($place)
    };
    ($place:expr) => {
        $crate::json::Write::is_null($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)
    };
}

/// [`__json_write_as!`](crate::__json_write_as) for BEVE.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_as {
    ($place:expr, $w:ident, $with:ty) => {
        <$with as $crate::beve::WriteAs<_>>::write($place, $w)
    };
    ($place:expr, $w:ident) => {
        $crate::beve::Write::write($place, $w)
    };
}

/// 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]");
/// ```
///
/// # Tuple structs
///
/// A tuple struct is the one shape [`object!`] cannot take, having nothing for
/// the keys to be, and the one that loses nothing by being positional. Its
/// fields are named here by the names they have, which are their positions:
///
/// ```
/// #[derive(Default, PartialEq, Debug)]
/// struct Entry(String, f32);
/// structio::array!(Entry [0, 1]);
///
/// let e = Entry("load".into(), 1.5);
/// assert_eq!(structio::to_string(&e), r#"["load",1.5]"#);
/// assert_eq!(structio::from_str::<Entry>(r#"["load",1.5]"#).unwrap(), e);
/// ```
///
/// Everything above holds for it. The order is yours, `..` says an omission is
/// deliberate, and an element type packs the fields into a typed array. The
/// list is written out rather than implied because it is also what says how
/// many fields the declaration meant: leave one out without `..` and the
/// declaration is refused, exactly as for a name.
///
/// # 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.
///
/// A declaration that leads with `write_only` generates the write half alone,
/// so nothing in the type needs a `Read` impl or a `Default`; see
/// [`object!`](crate::object#one-direction).
#[macro_export]
macro_rules! array {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare_array!(__both_write_array_impls $($t)*); };
    ($($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 {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare_array!(__json_write_array_impls $($t)*); };
    ($($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 {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare_array!(__beve_write_array_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare_array!(__beve_array_impls $($t)*); };
}

/// Declare a one-field struct as that field alone.
///
/// The wrapper leaves no trace in the document: `UserId(7)` is `7`, not `[7]`
/// and not `{"0":7}`. Reading and writing delegate to the field, with no
/// object, no keys and no array around it.
///
/// ```
/// #[derive(Default, Debug, PartialEq)]
/// struct UserId(u64);
/// structio::transparent!(UserId { 0 });
///
/// assert_eq!(structio::to_string(&UserId(7)), "7");
/// assert_eq!(structio::from_str::<UserId>("7").unwrap(), UserId(7));
/// ```
///
/// This is the declaration for the newtype that exists to stop you passing an
/// order id where a user id belongs. That distinction is Rust's and means
/// nothing to either format, so the wrapper should not show up in the bytes.
/// [`array!`](crate::array) is the other reading of a one-field tuple struct,
/// and writes `[7]`: right where the shape really is a one-element sequence,
/// wrong where it is a name for a number.
///
/// The field is named the way the struct names it, so a tuple struct's is its
/// position and a named struct's is its name:
///
/// ```
/// # #[derive(Default)]
/// struct Meters { value: f64 }
/// structio::transparent!(Meters { value });
/// ```
///
/// Declaring a struct that has a second field is a build error naming the
/// field left out, exactly as [`object!`](crate::object) is: what it would
/// otherwise generate is a document that silently drops it.
///
/// A field whose type this crate does not describe names an adapter, as an
/// [`object!`](crate::object) field does:
///
/// ```
/// # use std::time::Duration;
/// # use structio::{ErrorCode, Options, json, beve};
/// # 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) }
/// # }
/// # impl<'de> beve::ReadAs<'de, Duration> for Millis {
/// #     fn read<O: Options>(v: &mut Duration, r: &mut beve::Reader<'de, O>)
/// #         -> Result<(), ErrorCode> { let mut ms = 0u64; beve::Read::read(&mut ms, r)?; *v = Duration::from_millis(ms); Ok(()) }
/// # }
/// # impl beve::WriteAs<Duration> for Millis {
/// #     fn write<O: Options>(v: &Duration, w: &mut beve::Writer<'_, O>) { beve::Write::write(&(v.as_millis() as u64), w) }
/// # }
/// #[derive(Default)]
/// struct Timeout(Duration);
/// structio::transparent!(Timeout { 0 as Millis });
///
/// assert_eq!(structio::to_string(&Timeout(Duration::from_secs(3))), "3000");
/// ```
///
/// Generics are declared as they are elsewhere, in a leading bracketed list:
/// `transparent!([T: structio::ReadWrite + Default] Wrapper<T> { 0 })`.
///
/// # What it does not forward
///
/// BEVE's typed-array path stays off. [`beve::Write::ARRAY`] and
/// [`beve::Read::read_bulk`] keep their defaults, so a `Vec<UserId>` is
/// written as a generic array of values rather than as one block of `u64`
/// payload, and is read back element by element. The bulk path is a copy
/// between `[Self]` and a run of the payload, which is sound only if the
/// wrapper is laid out exactly as what it wraps, and a declaration cannot see
/// whether `#[repr(transparent)]` is there to say so. What a reader sees is a
/// valid document either way; what it costs is the one-copy path.
///
/// [`Write::is_null`](crate::json::Write::is_null) *is* forwarded, in both
/// formats, so a transparent wrapper around an `Option` is absent under
/// [`SkipNull`](crate::SkipNull) for the same reason the bare `Option` is.
///
/// There is no `read_only`, for [`object!`](crate::object)'s reason, and
/// `write_only` narrows this the same way it narrows one.
///
/// [`beve::Write::ARRAY`]: crate::beve::Write::ARRAY
/// [`beve::Read::read_bulk`]: crate::beve::Read::read_bulk
#[macro_export]
macro_rules! transparent {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => {
        $crate::__declare_transparent!([write] __both_write_transparent_impls $($t)*);
    };
    ($($t:tt)*) => {
        $crate::__declare_transparent!([both] __both_transparent_impls $($t)*);
    };
}

/// Declare a one-field struct as that field alone, for JSON only.
///
/// The same syntax as [`transparent!`], generating only the JSON impls, and
/// wanted for [`json_object!`](crate::json_object)'s reasons: a field of a
/// type only one format can carry, such as a [`json::Raw`](crate::json::Raw).
#[macro_export]
macro_rules! json_transparent {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => {
        $crate::__declare_transparent!([write] __json_write_transparent_impls $($t)*);
    };
    ($($t:tt)*) => {
        $crate::__declare_transparent!([both] __json_transparent_impls $($t)*);
    };
}

/// Declare a one-field struct as that field alone, for BEVE only.
///
/// The counterpart of [`json_transparent!`], and what a wrapper around a
/// borrowed `&[u8]` needs.
#[macro_export]
macro_rules! beve_transparent {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => {
        $crate::__declare_transparent!([write] __beve_write_transparent_impls $($t)*);
    };
    ($($t:tt)*) => {
        $crate::__declare_transparent!([both] __beve_transparent_impls $($t)*);
    };
}

/// [`__declare!`](crate::__declare) for the transparent form.
///
/// The same normalization of the input lifetime and the same two lists handed
/// on, with no case rule and no [`Keys`](crate::Keys) impl: there is no key to
/// convert and no object for one to sit in. The completeness check is here
/// rather than in the impls, being the one thing the two directions share.
#[doc(hidden)]
#[macro_export]
macro_rules! __declare_transparent {
    // The type's own spelling, `transparent!(UserId(0))`, which is what
    // anyone writes first. It has to be caught in front of the rules that
    // follow rather than left to fall through them: `$ty:ty` handed
    // `UserId(0)` fails inside the type parser, and that is a hard error
    // pointed into this crate rather than a rule that did not match.
    ([$dir:tt] $m:ident $name:ident ( $($rest:tt)* )) => {
        ::core::compile_error!(
            "structio: the field goes in braces, not in the parentheses the \
             struct is written with: `transparent!(UserId { 0 })`. A tuple \
             struct's field is named by its position here, as it is in \
             `array!`"
        );
    };
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty { $field:tt $(as $with:ty)? }) => {
        $crate::__declares_every_field!([$de $($gen)*] [all] $ty { $field });
        $crate::$m!([$de $($gen)*] [$de $($gen)*] $ty { $field $(as $with)? });
    };
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty { $field:tt $(as $with:ty)? }) => {
        $crate::__declares_every_field!([$($gen)*] [all] $ty { $field });
        $crate::$m!(['de, $($gen)*] [$($gen)*] $ty { $field $(as $with)? });
    };
    ([$dir:tt] $m:ident $ty:ty { $field:tt $(as $with:ty)? }) => {
        $crate::__declares_every_field!([] [all] $ty { $field });
        $crate::$m!(['de] [] $ty { $field $(as $with)? });
    };
    // Every well-formed declaration is taken above, so this is the message a
    // malformed one gets rather than `no rules expected this token` pointed
    // into this crate. The shape people reach for first is the type's own
    // spelling, `transparent!(UserId(0))`, which cannot parse: a `ty` fragment
    // may not be followed by `(`.
    ([$dir:tt] $m:ident $($rest:tt)*) => {
        ::core::compile_error!(
            "structio: a transparent declaration is a type and the one field \
             it is written as, in braces: `transparent!(UserId { 0 })` for a \
             tuple struct, `transparent!(Meters { value })` for a named one, \
             with an adapter as `{ 0 as Millis }` and generics in a leading \
             bracketed list"
        );
    };
}

/// Both formats, for [`transparent!`](crate::transparent).
#[doc(hidden)]
#[macro_export]
macro_rules! __both_transparent_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $($body:tt)* }) => {
        $crate::__json_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
        $crate::__beve_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
    };
}

/// Both formats, one direction, for `transparent!(write_only ..)`.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_write_transparent_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $($body:tt)* }) => {
        $crate::__json_write_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
        $crate::__beve_write_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
    };
}

/// Both directions, for a transparent declaration that narrowed neither.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_transparent_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $($body:tt)* }) => {
        $crate::__json_read_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
        $crate::__json_write_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
    };
}

/// The read half of a transparent declaration, which is the field's own read.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_transparent_impls {
    ([$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $field:tt $(as $with:ty)? }) => {
        impl<$de $($rgen)*> $crate::json::Read<$de> for $ty {
            // Small enough to be worth forcing into the caller, unlike a
            // struct's read: the body is one call.
            #[inline(always)]
            fn read<O: $crate::Options>(
                &mut self,
                p: &mut $crate::json::Parser<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                $crate::__json_read_as!(&mut self.$field, p $(, $with)?)
            }
        }
    };
}

/// The write half, which `transparent!(write_only ..)` emits by itself.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_write_transparent_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $field:tt $(as $with:ty)? }) => {
        impl<$($wgen)*> $crate::json::Write for $ty {
            #[inline(always)]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                $crate::__json_write_as!(&self.$field, w $(, $with)?);
            }

            // Forwarded, so a wrapper around an `Option` is absent under
            // `SkipNull` for the reason the bare `Option` is: on the wire the
            // wrapper is its field and nothing else.
            #[inline(always)]
            fn is_null(&self) -> bool {
                $crate::__json_is_null_as!(&self.$field $(, $with)?)
            }
        }
    };
}

/// [`__json_transparent_impls!`](crate::__json_transparent_impls) for BEVE.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_transparent_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $($body:tt)* }) => {
        $crate::__beve_read_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
        $crate::__beve_write_transparent_impls!([$($rgen)*] [$($wgen)*] $ty { $($body)* });
    };
}

/// The read half of a transparent BEVE declaration.
///
/// [`read_bulk`](crate::beve::Read::read_bulk) is deliberately left at its
/// default, which declines: it copies a run of payload straight into a
/// `[Self]`, and that is sound only where the wrapper is laid out exactly as
/// what it wraps. A declaration cannot see whether `#[repr(transparent)]` says
/// so, and declining costs a `Vec` of them the one-copy path and nothing else.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_transparent_impls {
    ([$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $field:tt $(as $with:ty)? }) => {
        impl<$de $($rgen)*> $crate::beve::Read<$de> for $ty {
            #[inline(always)]
            fn read<O: $crate::Options>(
                &mut self,
                r: &mut $crate::beve::Reader<$de, O>,
            ) -> ::core::result::Result<(), $crate::ErrorCode> {
                $crate::__beve_read_as!(&mut self.$field, r $(, $with)?)
            }
        }
    };
}

/// The write half, which `beve_transparent!(write_only ..)` emits by itself.
///
/// [`ARRAY`](crate::beve::Write::ARRAY) stays `None` for
/// [`__beve_read_transparent_impls!`](crate::__beve_read_transparent_impls)'s
/// reason: naming an array obliges `write_payload` to emit that array's
/// payload out of a `[Self]`, which is the same layout assumption from the
/// other side.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_transparent_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty { $field:tt $(as $with:ty)? }) => {
        impl<$($wgen)*> $crate::beve::Write for $ty {
            #[inline(always)]
            fn write<O: $crate::Options>(&self, w: &mut $crate::beve::Writer<'_, O>) {
                $crate::__beve_write_as!(&self.$field, w $(, $with)?);
            }

            #[inline(always)]
            fn is_null(&self) -> bool {
                $crate::__beve_is_null_as!(&self.$field $(, $with)?)
            }
        }
    };
}

/// [`__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)* ]);
    };
}

/// Both formats, one direction, for `array!(write_only ..)`.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_write_array_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($body:tt)* ]) => {
        $crate::__json_write_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($body)* ]);
        $crate::__beve_write_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.
///
/// Those four take field *names*. A tuple struct's fields are `0` and `1`,
/// which no `ident` matcher reaches, and widening these arms to `tt` is not
/// open either: a `tt` repetition in front of `..` is a local ambiguity, since
/// the matcher cannot tell a field from the marker that ends the list. An
/// index list therefore falls past all four into the two arms below them, which
/// normalize the element type and hand the rest to
/// [`__array_positions!`](crate::__array_positions), where the list is walked
/// one token at a time and `..` is looked for before a field.
#[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),* ]);
    };
    // A list the four arms above did not take, which is an index list or a
    // mistake. The element type is normalized into a group here so that the
    // walk carries one shape rather than two.
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($body:tt)* ]) => {
        $crate::__array_positions!($m [$($rgen)*] [$($wgen)*] $ty [$elem ;] [] $($body)*);
    };
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($body:tt)* ]) => {
        $crate::__array_positions!($m [$($rgen)*] [$($wgen)*] $ty [] [] $($body)*);
    };
}

/// A positional field list walked one token at a time, for the index form.
///
/// [`__declared_array!`](crate::__declared_array) says why this exists rather
/// than one more arm up there. The list is moved into the accumulator a field
/// at a time, and `..` is matched ahead of a field because `..` is one token
/// tree: a `tt` field matcher takes it whole, and the marker that ends the list
/// vanishes into the list as a field. What comes out is what the name arms
/// produce: the mode, the element type where there is one, and the fields.
///
/// The walk is one recursion per field, which the name arms do not pay, so the
/// index form alone is bounded by the recursion limit: around 127 fields under
/// the default, against no limit at all for names. A positional struct is a
/// handful of fields by the nature of the thing, and `recursion_limit` raises
/// it for anything that is not.
#[doc(hidden)]
#[macro_export]
macro_rules! __array_positions {
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [$($elem:tt)*] [$($acc:tt)*] ..) => {
        $crate::__elements_impl!([$($wgen)*] [partial] $ty [ $($elem)* $($acc)* ]);
        $crate::$m!([$($rgen)*] [$($wgen)*] $ty [ $($elem)* $($acc)* ]);
    };
    ($m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [$($elem:tt)*] [$($acc:tt)*]) => {
        $crate::__elements_impl!([$($wgen)*] [all] $ty [ $($elem)* $($acc)* ]);
        $crate::$m!([$($rgen)*] [$($wgen)*] $ty [ $($elem)* $($acc)* ]);
    };
    (
        $m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [$($elem:tt)*] [$($acc:tt)*]
        $field:tt , $($rest:tt)*
    ) => {
        $crate::__array_positions!(
            $m [$($rgen)*] [$($wgen)*] $ty [$($elem)*] [$($acc)* $field ,] $($rest)*
        );
    };
    // The last field, which carries no comma. It is pushed and handed back
    // rather than emitted here, so that one arm above emits `[all]`, one emits
    // `[partial]`, and neither is written out twice.
    (
        $m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [$($elem:tt)*] [$($acc:tt)*]
        $field:tt
    ) => {
        $crate::__array_positions!(
            $m [$($rgen)*] [$($wgen)*] $ty [$($elem)*] [$($acc)* $field]
        );
    };
    // Every well-formed list is taken above, so this is the one message a
    // malformed one gets. Without it the error is `no rules expected this
    // token`, pointing into this crate rather than at the declaration.
    (
        $m:ident [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [$($elem:tt)*] [$($acc:tt)*]
        $($rest:tt)*
    ) => {
        ::core::compile_error!(::core::concat!(
            "structio: `",
            ::core::stringify!($($rest)*),
            "` is not a positional field list. A list is a comma-separated run of field \
             names, or of tuple indices for a tuple struct, ending in `..` where leaving \
             a field out is deliberate."
        ));
    };
}

/// 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:tt),* $(,)? ]) => {
        $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:tt),* $(,)? ]) => {
        $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:tt),* $(,)? ]) => {
        $crate::__json_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
    ([$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:tt),* $(,)? ]) => {
        $crate::__json_read_array_impls!([$de $($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
        $crate::__json_write_array_impls!([$de $($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
}

/// The read half of a positional declaration.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_array_impls {
    ([$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:tt),* $(,)? ]) => {
        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<$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)
            }
        }
    };
}

/// The write half, which `array!(write_only ..)` emits by itself.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_write_array_impls {
    // JSON has one array syntax, so the element type changes nothing here.
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:tt),* $(,)? ]) => {
        $crate::__json_write_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:tt),* $(,)? ]) => {
        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<$($wgen)*> $crate::json::Write for $ty {
            #[inline]
            fn write<O: $crate::Options>(&self, w: &mut $crate::json::Writer<'_, O>) {
                w.write_array(self);
            }
        }
    };
}

/// Both directions, for [`beve_array!`](crate::beve_array). The two halves
/// are separate macros so that `write_only` can ask for one of them.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_array_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($body:tt)* ]) => {
        $crate::__beve_read_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($body)* ]);
        $crate::__beve_write_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($body)* ]);
    };
}

/// The read half of a positional declaration.
///
/// An element type says how the elements are *stored*, which is the write
/// half's business: the array driver takes either form on the way in, so this
/// drops it exactly as the JSON side does.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_array_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:tt),* $(,)? ]) => {
        $crate::__beve_read_array_impls!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ]);
    };
    ([$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field: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<$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)
            }
        }
    };
}

/// The write half, which `array!(write_only ..)` emits by itself.
///
/// 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.
/// The two arms differ only in those two items, so the impls themselves are
/// [`__beve_write_array_body!`](crate::__beve_write_array_body).
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_array_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $elem:ty ; $($field:tt),* $(,)? ]) => {
        $crate::__beve_write_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:tt),* $(,)? ]) => {
        $crate::__beve_write_array_body!([$($rgen)*] [$($wgen)*] $ty [ $($field),* ] {});
    };
}

/// The write half, which `array!(write_only ..)` emits by itself.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_array_body {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] $ty:ty [ $($field:tt),* ] { $($typed:tt)* }
    ) => {
        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<$($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 variant may answer to more than one name, written after it and separated
/// by `|`, exactly as an [`object!`] field's aliases are. The declared name is
/// the one written, and any of them is accepted on read, which is what renames
/// a variant without breaking the documents already written under the old
/// name.
///
/// ```
/// # #[derive(Default, PartialEq, Debug)]
/// # enum Level { #[default] Info, Warning }
/// structio::unit_enum!(Level {
///     "info" => Info | "INFO",
///     "warning" => Warning | "warn",
/// });
/// # assert_eq!(structio::from_str::<Level>("\"warn\"").unwrap(), Level::Warning);
/// # assert_eq!(structio::to_string(&Level::Warning), "\"warning\"");
/// ```
///
/// /// 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 need not come first
///
/// A tag that comes first is read in one pass. One that comes later is
/// found by stepping over the members before it, which are read once the
/// members after it are, so a document whose keys were sorted reads the same
/// as one that put the tag first. An object with no tag at all is
/// [`ExpectedTag`](crate::ErrorCode::ExpectedTag), reported against its
/// first key.
///
/// ```
/// # #[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(),
///     Shape::Circle(Circle { r: 1.0 }),
/// );
/// // No tag anywhere.
/// assert_eq!(
///     from_str::<Shape>(r#"{"r":1}"#).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/matrix-research-inc/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.
///
/// A declaration that leads with `write_only` generates the write half alone,
/// so nothing in the type needs a `Read` impl or a `Default`; see
/// [`object!`](crate::object#one-direction).
#[macro_export]
macro_rules! unit_enum {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__unit_enum!([write] __both_write_unit_enum_impls $($t)*); };
    ($($t:tt)*) => { $crate::__unit_enum!([both] __both_unit_enum_impls $($t)*); };
}

/// The arms of [`unit_enum!`](crate::unit_enum), with the impls it asked for
/// carried in front. They are spelled out rather than forwarded as a token
/// stream because the last one is the diagnostic for a body this macro does
/// not take, and it has to be reached only after the others have failed.
#[doc(hidden)]
#[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.
    ([$dir:tt] $m:ident [$($gen:tt)*] $ty:ty as $case:tt { $($($name:literal =>)? $variant:ident $(| $valias:literal)*),* $(,)? }) => {
        $crate::__declare_enum!(
            [$dir] $m [$($gen)*] $ty as $case { $($($name =>)? $variant $(| $valias)*),* }
        );
    };
    ([$dir:tt] $m:ident [$($gen:tt)*] $ty:ty { $($($name:literal =>)? $variant:ident $(| $valias:literal)*),* $(,)? }) => {
        $crate::__declare_enum!(
            [$dir] $m [$($gen)*] $ty { $($($name =>)? $variant $(| $valias)*),* }
        );
    };
    ([$dir:tt] $m:ident $ty:ty as $case:tt { $($($name:literal =>)? $variant:ident $(| $valias:literal)*),* $(,)? }) => {
        $crate::__declare_enum!(
            [$dir] $m $ty as $case { $($($name =>)? $variant $(| $valias)*),* }
        );
    };
    ([$dir:tt] $m:ident $ty:ty { $($($name:literal =>)? $variant:ident $(| $valias:literal)*),* $(,)? }) => {
        $crate::__declare_enum!(
            [$dir] $m $ty { $($($name =>)? $variant $(| $valias)*),* }
        );
    };
    // 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.
    ([$dir:tt] $m:ident $($rest:tt)*) => {
        ::core::compile_error!(
            "`unit_enum!` takes a type and a brace-delimited list of variant \
             names, each optionally renamed with `\"name\" => Variant` and \
             aliased with `Variant | \"other\"`. 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 aliases the same way
/// with `Variant | "other_name"`, 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]}"#);
/// ```
///
/// The requirement stops at the payloads. The enum itself needs no `Default`,
/// which is worth saying because the shape that most wants a tagged enum is
/// the one that cannot derive it: a message union whose every variant carries
/// something. `#[derive(Default)]` reaches an enum only through a variant
/// marked `#[default]`, and that variant has to be a unit one, so an enum like
/// the one below would have to nominate a message as the stand-in for no
/// message to get the derive. It does not have to. Declaring it, writing it,
/// and reading into a value the caller already holds ask the payloads for
/// their `Default` and the enum for nothing.
///
/// ```
/// // The payloads carry their own `Default`, which is the part that is
/// // required. The enum below carries none, and is not asked for one.
/// #[derive(Default, PartialEq, Debug)]
/// struct Frame { len: u32 }
/// #[derive(Default, PartialEq, Debug)]
/// struct Ack { seq: u32 }
/// # structio::object!(Frame { len });
/// # structio::object!(Ack { seq });
///
/// #[derive(PartialEq, Debug)]
/// enum Packet {
///     Data(Frame),
///     Ack(Ack),
/// }
///
/// structio::tagged_enum!(Packet { Data(_), Ack(_) });
///
/// let mut packet = Packet::Data(Frame { len: 0 });
/// structio::read_into(&mut packet, r#"{"Ack":{"seq":9}}"#).unwrap();
/// assert_eq!(packet, Packet::Ack(Ack { seq: 9 }));
/// ```
///
/// What does ask for one is a position that *constructs* the enum rather than
/// filling one that is there: [`from_str`](crate::from_str), which is handed
/// nothing but a document, and a growing container, whose new elements have to
/// exist before they can be read into. A `Vec<Packet>` therefore wants
/// `Packet: Default` and there is no spelling of the read that avoids it,
/// while a `Box<Packet>` or a `[Packet; N]` has no element to build and holds
/// the enum above as it stands. Where a placeholder is unavoidable, writing it
/// as a private constructor and reading into that keeps it out of the enum's
/// public API, which `#[derive(Default)]` would not.
///
/// # 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/matrix-research-inc/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.
///
/// A declaration that leads with `write_only` generates the write half alone,
/// so nothing in the type needs a `Read` impl or a `Default`; see
/// [`object!`](crate::object#one-direction).
#[macro_export]
macro_rules! tagged_enum {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare_enum!([write] __both_write_enum_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare_enum!([both] __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 {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare_enum!([write] __json_write_enum_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare_enum!([both] __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 {
    (write_only :: $($t:tt)*) => { $crate::__write_only_is_the_marker!(); };
    (read_only $($t:tt)*) => { $crate::__no_read_only!(); };
    (write_only $($t:tt)*) => { $crate::__declare_enum!([write] __beve_write_enum_impls $($t)*); };
    ($($t:tt)*) => { $crate::__declare_enum!([both] __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 {
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!(
            [$dir] $m [$de $($gen)*] [$de $($gen)*] [_] [$tag] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!(
            [$dir] $m [$de $($gen)*] [$de $($gen)*] [$case] [$tag] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m [$de $($gen)*] [$de $($gen)*] [$case] [] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $de:lifetime $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m [$de $($gen)*] [$de $($gen)*] [_] [] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty as tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m ['de, $($gen)*] [$($gen)*] [_] [$tag] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty as $case:tt tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!(
            [$dir] $m ['de, $($gen)*] [$($gen)*] [$case] [$tag] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m ['de, $($gen)*] [$($gen)*] [$case] [] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident [ $($gen:tt)* ] $ty:ty { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m ['de, $($gen)*] [$($gen)*] [_] [] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident $ty:ty as tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m ['de] [] [_] [$tag] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident $ty:ty as $case:tt tag $tag:literal { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m ['de] [] [$case] [$tag] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident $ty:ty as $case:tt { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $m ['de] [] [$case] [] $ty { $($body)* });
    };
    ([$dir:tt] $m:ident $ty:ty { $($body:tt)* }) => {
        $crate::__declared_enum!([$dir] $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 {
    (
        [$dir:tt] $m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty {
            $($body:tt)*
        }
    ) => {
        $crate::__case_check!($case);
        $crate::__variants_impl!([$($wgen)*] [$case] [$dir] $ty { $($body)* });
        $crate::$m!([$($rgen)*] [$($wgen)*] [$case] [] $ty { $($body)* });
    };
    (
        [$dir:tt] $m:ident [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($body:tt)*
        }
    ) => {
        $crate::__case_check!($case);
        $crate::__variants_impl!([$($wgen)*] [$case] [$dir] $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, one direction, for `unit_enum!(write_only ..)`.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_write_unit_enum_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty { $($body:tt)* }) => {
        $crate::__json_write_enum_impls!([$($rgen)*] [$($wgen)*] [$case] [] $ty { $($body)* });
        $crate::__beve_write_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)* });
    };
}

/// Both formats, one direction, for `tagged_enum!(write_only ..)`.
#[doc(hidden)]
#[macro_export]
macro_rules! __both_write_enum_impls {
    ([$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$($tag:literal)?] $ty:ty { $($body:tt)* }) => {
        $crate::__json_write_enum_impls!(
            [$($rgen)*] [$($wgen)*] [$case] [$($tag)?] $ty { $($body)* });
        $crate::__beve_write_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)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        $( $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)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        $( $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] [$dir:tt] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        $crate::__each_name_once!($($variant),*);
        $( $crate::__payload_is_wildcard!($($($payload)*)?); )*

        impl<$($wgen)*> $crate::Variants for $ty {
            // The variants first, in declaration order, then every alias,
            // which is the layout `Keys::KEYS` has and the order
            // [`Variants::ALIASES`](crate::Variants::ALIASES) is indexed
            // against.
            const VARIANTS: &'static [&'static str] = &[
                $( $crate::__json_key!([$case] $($name)? [$variant]), )*
                $( $( $valias, )* )*
            ];

            // `Keys::ALIASES`'s counterpart, built the same way and for the
            // same reason; an alias is spelled out, so no case rule touches it.
            #[allow(unused_assignments, unused_mut)]
            const ALIASES: &'static [u8] = &{
                let mut of = [0u8; 0 $( $( + $crate::__counts_one!($valias) )* )*];
                let mut j = 0usize;
                let mut v = 0usize;
                $(
                    $(
                        assert!(
                            v <= u8::MAX as usize,
                            "an aliased variant must be one of the first 256 \
                             declared: the variant an alias names is a u8"
                        );
                        of[j] = v as u8;
                        j += 1;
                        $crate::__alias_direction!([$dir] name $valias);
                    )*
                    v += 1;
                )*
                of
            };

            // 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 {
    ($($t:tt)*) => {
        $crate::__json_read_enum_impls!($($t)*);
        $crate::__json_write_enum_impls!($($t)*);
    };
}

/// The read half of an enum, dispatching on the tagging convention the
/// declaration asked for as the write half does.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty { $($body:tt)* }
    ) => {
        $crate::__json_read_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)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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]) $(, $valias)*],
                            $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]) $(, $valias)*],
                            $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)
            }
        }
    };
}

/// The write half, which `tagged_enum!(write_only ..)` and
/// `unit_enum!(write_only ..)` emit by themselves. A tag clause is dispatched
/// here as well, so that one direction reaches both tagging conventions.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_write_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty { $($body:tt)* }
    ) => {
        $crate::__json_write_internal_enum_impls!(
            [$($rgen)*] [$($wgen)*] [$case] [$tag] $ty { $($body)* });
    };
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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)
        }
    };
}

/// The read half of an internally tagged enum.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_read_internal_enum_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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]) $(, $valias)*],
                            $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)
            }
        }
    };
}

/// The write half, which a `write_only` declaration with a tag clause emits by
/// itself. The tag check rides in its `const` block, so narrowing the
/// direction does not drop it.
#[doc(hidden)]
#[macro_export]
macro_rules! __json_write_internal_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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)*))? $(| $valias)*),*
                    });
                };
                $(
                    $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)
        }
    };
}

/// The read half of an internally tagged enum.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_internal_enum_impls {
    (
        [$de:lifetime $($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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]) $(, $valias)*],
                            $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)
            }
        }
    };
}

/// The write half, carrying the tag check for the reason its JSON counterpart
/// does.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_internal_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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)*))? $(| $valias)*),*
                    });
                };
                $(
                    $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 {
    ($($t:tt)*) => {
        $crate::__beve_read_enum_impls!($($t)*);
        $crate::__beve_write_enum_impls!($($t)*);
    };
}

/// The read half of an enum, dispatching on the tagging convention the
/// declaration asked for as the write half does.
///
/// A unit enum reaches the second arm too: its string-array packing is the
/// write half's, the enum driver taking either form on the way in.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_read_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty { $($body:tt)* }
    ) => {
        $crate::__beve_read_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)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        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]) $(, $valias)*],
                            $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]) $(, $valias)*],
                            $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)
            }
        }
    };
}

/// The write half, which `tagged_enum!(write_only ..)` emits by itself,
/// dispatching on the tagging convention as the both-direction form does.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [$tag:literal] $ty:ty { $($body:tt)* }
    ) => {
        $crate::__beve_write_internal_enum_impls!(
            [$($rgen)*] [$($wgen)*] [$case] [$tag] $ty { $($body)* });
    };
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] [] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        }
    ) => {
        $crate::__beve_write_enum_body!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($($name =>)? $variant $(($($payload)*))? $(| $valias)*),*
        } {});
    };
}

/// 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 $(| $valias:literal)*),* $(,)?
        }
    ) => {
        $crate::__beve_read_enum_impls!([$($rgen)*] [$($wgen)*] [$case] [] $ty {
            $($($name =>)? $variant $(| $valias)*),*
        });
        $crate::__beve_write_unit_enum_impls!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($($name =>)? $variant $(| $valias)*),*
        });
    };
}

/// The write half, which `unit_enum!(write_only ..)` emits by itself.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_unit_enum_impls {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($($name:literal =>)? $variant:ident $(| $valias:literal)*),* $(,)?
        }
    ) => {
        $crate::__beve_write_enum_body!([$($rgen)*] [$($wgen)*] [$case] $ty {
            $($($name =>)? $variant $(| $valias)*),*
        } {
            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 write half, which a `write_only` declaration emits by itself.
#[doc(hidden)]
#[macro_export]
macro_rules! __beve_write_enum_body {
    (
        [$($rgen:tt)*] [$($wgen:tt)*] [$case:tt] $ty:ty {
            $($($name:literal =>)? $variant:ident $(($($payload:tt)*))? $(| $valias:literal)*),* $(,)?
        } { $($typed:tt)* }
    ) => {
        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)
        }
    };
}