summaryrefslogtreecommitdiff
path: root/core/walk.zig
blob: 6734c0b7e121fb839589a1c5218e06f0f36d91e2 (plain) (blame)
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
//! The reflective walk over the core's state: one comptime `@typeInfo` walk
//! that hashes a session into a digest (the replay harness compares two),
//! encodes values for the tape, and dumps a session for another build to
//! load by name: into a xitdb database's maps (`Put`, `Get`: a Dump,
//! Restore, -l, an Upgrade, a handover; Db.zig), or as bytes with a table
//! of its types (`Dump`, `Load`: a closed pane, the join of phase 5, and
//! for one release the `.dump` files before). The rollback copy is to walk
//! the same way (docs/next-daemon.md).
//!
//! Values, never addresses: a pointer is followed to what it points at, a
//! slice is its elements, an ArrayList its items, a hash map its entries in
//! no order. A type the walk cannot see into (an opaque handle, a function,
//! an untagged union, a many-pointer) is a compile error naming it, until
//! the struct that holds it says what the field is:
//!
//!     pub const replica = .{
//!         // This process's own: presentation, timing, the host's handles
//!         // and caches. A replica has its own and never compares them.
//!         .local = .{ "frames", "surface" },
//!         // Recomputed from the rest whenever it is wanted.
//!         .derived = .{ "wrap_line" },
//!         // Held by the session that performs effects alone.
//!         .authority = .{ "host" },
//!         // A field written only as far as another says: hashed that far.
//!         .len = .{ .{ "jumps", "njumps" } },
//!         // What a field holds is made with another allocator on a load.
//!         .alloc = .{ .{ "image", "image" } },
//!         // Immutable blobs: replaced whole, never written, freed raw
//!         // (memory.freeRaw). A digest hashes each once and
//!         // folds that word in; a replica's rollback copy pins them.
//!         .blob = .{ "content" },
//!     };
//!
//! None of the three kinds is in a digest or a dump. A type (a struct or a
//! tagged union) with a `pub fn digest(*const T, *Hasher) void` of its own
//! hashes itself; one with
//! `dumpWrite`, `dumpRead` (and `dumpFree`) dumps itself as bytes.
const std = @import("std");
const xitdb = @import("xitdb");

pub const Hasher = std.hash.Wyhash;
const builtin = @import("builtin");

/// Whether `T.name` holds blobs (`.blob`): a file's text, an undo entry's
/// bytes, a register's text, a file's location rows.
pub fn blob(comptime T: type, comptime name: []const u8) bool {
    @setEvalBranchQuota(100_000);
    if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "blob")) return false;
    inline for (T.replica.blob) |n| if (comptime std.mem.eql(u8, n, name)) return true;
    return false;
}

// ---- a blob in a digest: its length ----
//
// A digest walks the whole core at every unit a replica is sent (and every
// unit a replica replays): a 100 MB file was hashed in full each time, then
// once and kept as a word by its address while texts were never written in
// place. A blob of `blob_min` bytes or more is digested as its length now,
// never its bytes: a file's text says what it holds by its revision
// (File.State.revision, in the digest), and the other blobs are replaced
// whole, never written. A smaller one is hashed as any slice is.

const blob_min = 4096;
threadlocal var in_blob: bool = false;

/// A blob as a digest takes it: its length.
fn hashBlob(comptime E: type, items: []const E, h: *Hasher) void {
    // The list is the C heap's (a replica client's), which a build with no
    // libc has none of.
    if (comptime builtin.link_libc) if (blobs_out) |list| list.append(std.heap.c_allocator, std.mem.sliceAsBytes(items)) catch {};
    h.update(std.mem.asBytes(&items.len));
}

/// Where `blobs` notes every blob.
threadlocal var blobs_out: ?*std.ArrayListUnmanaged([]const u8) = null;

/// Every blob of `v` a digest takes as one (`blob_min` bytes and up), as
/// its bytes, onto `out` (the C heap's): a replica client's, which knows
/// its blobs by content (core/replica.zig `Have`).
pub fn blobs(comptime T: type, v: *const T, out: *std.ArrayListUnmanaged([]const u8)) void {
    blobs_out = out;
    defer blobs_out = null;
    _ = digest(T, v);
}

pub fn digest(comptime T: type, v: *const T) u64 {
    var h = Hasher.init(0);
    hash(T, v, &h);
    return h.final();
}

/// Equal as the digest sees them, by the digest's rules: what the walk
/// leaves out (a field `replica` names, a Buf's bytes past its length) is
/// not compared; a type that walks itself, by its digest. std.meta.eql
/// compares every byte of an array, and those bytes are undefined: 0xAA on
/// every Debug process, each release process's own garbage; a decision of
/// the core taken on them agrees between a session and its clients in
/// Debug alone.
pub fn eql(comptime T: type, a: *const T, b: *const T) bool {
    switch (@typeInfo(T)) {
        .void => return true,
        .bool, .int, .@"enum" => return a.* == b.*,
        .optional => |o| return if (a.*) |*x| (if (b.*) |*y| eql(o.child, x, y) else false) else b.* == null,
        .array => |arr| {
            if (comptime flatHash(arr.child)) return std.mem.eql(arr.child, a, b);
            for (a, b) |*x, *y| if (!eql(arr.child, x, y)) return false;
            return true;
        },
        .@"struct" => |s| {
            if (comptime machinery(T)) return true;
            if (comptime s.layout == .@"packed" or @hasDecl(T, "digest") or isList(T) or isAtomic(T) or isBitset(T) or @hasField(T, "any_future")) return digest(T, a) == digest(T, b);
            inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
                if (attr.@"comptime" or comptime excluded(T, name)) continue;
                if (comptime lengthOf(T, name)) |len| {
                    const x = @field(a, name)[0..lengthIn(a, len)];
                    const y = @field(b, name)[0..lengthIn(b, len)];
                    if (comptime flatHash(Element(F))) {
                        if (!std.mem.eql(Element(F), x, y)) return false;
                    } else {
                        if (x.len != y.len) return false;
                        for (x, y) |*p, *q| if (!eql(Element(F), p, q)) return false;
                    }
                } else if (!eql(F, &@field(a, name), &@field(b, name))) return false;
            }
            return true;
        },
        else => return digest(T, a) == digest(T, b),
    }
}

/// A digest of each field `hash` would walk, in order (what a divergence
/// is narrowed down by); `names` are theirs.
pub fn fieldDigests(comptime T: type, v: *const T, out: []u64) []u64 {
    var n: usize = 0;
    const s = @typeInfo(T).@"struct";
    inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
        if (attr.@"comptime" or comptime excluded(T, name)) continue;
        var h = Hasher.init(0);
        const was = in_blob;
        in_blob = comptime blob(T, name);
        defer in_blob = was;
        if (comptime lengthOf(T, name)) |len| {
            hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], &h);
        } else hash(F, &@field(v, name), &h);
        out[n] = h.final();
        n += 1;
    }
    return out[0..n];
}

pub fn fieldNames(comptime T: type) []const []const u8 {
    comptime {
        var names: []const []const u8 = &.{};
        const s = @typeInfo(T).@"struct";
        for (s.field_names, s.field_attrs) |name, attr| {
            if (attr.@"comptime" or excluded(T, name)) continue;
            names = names ++ .{name};
        }
        return names;
    }
}

/// Types that are machinery, never state: an allocator, the Io, a lock.
pub fn machinery(comptime T: type) bool {
    inline for (.{ std.mem.Allocator, std.Io, std.Io.Mutex, std.Io.Condition, std.Thread, std.heap.ArenaAllocator }) |M| if (T == M) return true;
    return false;
}

/// Bytes that are the value whole: no padding, no pointer.
fn flat(comptime T: type) bool {
    return switch (@typeInfo(T)) {
        .int => @sizeOf(T) * 8 == @bitSizeOf(T),
        .bool => true,
        .@"enum" => |e| @sizeOf(T) * 8 == @bitSizeOf(e.tag_type),
        else => false,
    };
}

/// A field the walk cannot follow: a pointer to an opaque thing or a
/// function, or a many-pointer, bare or optional (the struct holding it is
/// named in the error, not the walk's depth).
fn opaqueTo(comptime F: type) bool {
    return switch (@typeInfo(F)) {
        .optional => |o| opaqueTo(o.child),
        .pointer => |p| p.size == .many or p.size == .c or switch (@typeInfo(p.child)) {
            .@"opaque", .@"fn" => true,
            else => false,
        },
        else => false,
    };
}

fn excluded(comptime T: type, comptime name: []const u8) bool {
    @setEvalBranchQuota(100_000);
    if (!@hasDecl(T, "replica")) return false;
    inline for (.{ "local", "derived", "authority" }) |kind| {
        if (@hasField(@TypeOf(T.replica), kind)) inline for (@field(T.replica, kind)) |n| {
            if (comptime std.mem.eql(u8, n, name)) return true;
        };
    }
    return false;
}

/// What a `len`-cut field holds: a fixed array's, or a slice's room (a
/// selection's ranges, made once and used `nsel` deep).
fn Element(comptime F: type) type {
    return switch (@typeInfo(F)) {
        .array => |a| a.child,
        .pointer => |p| p.child,
        else => @compileError("walk: a `len` cuts an array or a slice, not " ++ @typeName(F)),
    };
}

pub fn lengthIn(v: anytype, comptime len: []const u8) usize {
    const n = @field(v, len);
    return if (@typeInfo(@TypeOf(n)) == .optional) (if (n) |k| k else 0) else n;
}

/// How far the field `len` names says its array is written (null: none).
pub fn lengthOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
    @setEvalBranchQuota(100_000);
    if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "len")) return null;
    inline for (T.replica.len) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1];
    return null;
}

/// How many `replica.len` pairs `T` has: a buffer, and the field saying how
/// far it is written.
fn pairs(comptime T: type) usize {
    return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), "len")) T.replica.len.len else 0;
}

/// Where `name` is among `T`'s pairs' buffers.
fn pairAt(comptime T: type, comptime name: []const u8) ?usize {
    inline for (0..comptime pairs(T)) |i| if (comptime std.mem.eql(u8, T.replica.len[i][0], name)) return i;
    return null;
}

/// A length that says more than its buffer holds.
const Past = struct { name: []const u8, says: usize, holds: usize };

/// The first length of `v` past what its buffer holds, or null. A digest, a
/// copy, a deinit and every use slice each pair's buffer as far as its length
/// says, so a value read back (a tape, a dump, an image: bytes from another
/// process or the disk) is held to it where it is decoded, every pair of every
/// type at once, and refused when one says more: never walked. `held`: how
/// many of each fixed array were read back (a dump writes one as far as its
/// length said); null, each whole (a tape writes them whole). A slice's are
/// its own.
fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past {
    inline for (0..comptime pairs(T)) |i| {
        const buffer = @field(v, T.replica.len[i][0]);
        const holds = if (comptime @typeInfo(@TypeOf(buffer)) == .array) (if (held) |h| @min(h[i], buffer.len) else buffer.len) else buffer.len;
        const says = lengthIn(v, T.replica.len[i][1]);
        if (says > holds) return .{ .name = T.replica.len[i][1], .says = says, .holds = holds };
    }
    return null;
}

// ---- an index read back is held to what it names ----
//
// A field that NAMES one of the things a session holds (a view by its slot,
// a pane by its) says what, beside it, as a length says its buffer; a field
// that says WHERE in a thing it is (a scroll, a row), the thing's last place:
//
//     pub const replica = .{
//         // One of the slots field `views` has (as many as it holds), or one
//         // a predicate of the struct says is there (`fn (*const T, usize)
//         // bool`); a third word, one of the things of the struct named
//         // second that holds this one (held where ITS fields end, every
//         // value of this type it holds); a fourth, the field counting a
//         // span of them from it (all within the field named third).
//         .index = .{ .{ "sized_by", Pardes, "views" }, .{ "live", "openViews" }, .{ "first", Journal, "entries", "n" } },
//         // Its last place, a function of the struct (`fn (*const T) usize`),
//         // or its first and last (`[2]usize`).
//         .place = .{ .{ "scroll", "lastLine" } },
//         // Where each of its entries (as far as its length says) may be,
//         // a predicate of the struct by the entry's place in the field
//         // (`fn (*const T, usize) bool`): a view's rects on its screen.
//         .within = .{ .{ "rects", "onScreen" } },
//         // What a load that left one of its things out (another build's
//         // pane) does to what names it (`fn (*T) void`), before its indexes
//         // are held.
//         .left_out = "dropMissing",
//     };
//
// A value read back (a tape, a dump, an image: bytes from another process or
// the disk) is held to them where its fields end, beside its lengths
// (`pastHeld`), every declaration of every type at once: an index that names
// none is REFUSED, its field named (the dump is not the session: the view,
// the pane it names is not there), and so is an entry that is not where it
// may be (no session's: a rect past its screen); a place past its thing's
// last is that LAST (the session is there, its view a line off). A field
// that names a slot by its type (`Pane.Id`, `View.Id`) and says nothing is
// a compile error (`checkSlots`); a bare integer that does is found by
// reading, as the lengths' were, until it is typed as its slot.

fn declared(comptime T: type, comptime kind: []const u8) usize {
    return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0;
}

/// An index read back that names none of what it says it indexes, or
/// (`within`) the entry `says` of a field that is not where it may be.
const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8, within: bool = false };

/// What an index field says, as a number: an integer, an optional one's (null
/// names nothing), a slot's enum's (`Pane.Id`).
fn number(comptime F: type, v: F) ?usize {
    return switch (@typeInfo(F)) {
        .int => std.math.cast(usize, v) orelse std.math.maxInt(usize),
        .optional => |o| if (v) |x| number(o.child, x) else null,
        .@"enum" => |e| number(e.tag_type, @backingInt(v)),
        else => @compileError("walk: an `index` names a thing by a number, not " ++ @typeName(F)),
    };
}

/// How many of field `name`'s elements `v` holds: as far as its length says.
fn heldOf(comptime T: type, v: *const T, comptime name: []const u8) usize {
    const all = &@field(v, name);
    if (comptime isList(@TypeOf(all.*))) return all.items.len;
    return if (comptime lengthOf(T, name)) |len| @min(lengthIn(v, len), all.len) else all.len;
}

/// Whether `h` has the thing `i` names by `what`: a field of it (one of its
/// slots), or a predicate of it.
fn hasThing(comptime H: type, h: *const H, comptime what: []const u8, i: usize) bool {
    if (comptime @hasField(H, what)) {
        return i < heldOf(H, h, what);
    } else return @field(H, what)(h, i);
}

/// The first number field `name` of `u` says (each of an array as far as its
/// length says) that names no thing of `h`'s by `what`.
fn firstUnnamed(comptime U: type, u: *const U, comptime name: []const u8, comptime H: type, h: *const H, comptime what: []const u8) ?usize {
    const F = @FieldType(U, name);
    if (comptime @typeInfo(F) == .array) {
        for (@field(u, name)[0..heldOf(U, u, name)]) |e| if (number(@typeInfo(F).array.child, e)) |i| if (!hasThing(H, h, what, i)) return i;
        return null;
    }
    const i = number(F, @field(u, name)) orelse return null;
    return if (hasThing(H, h, what, i)) null else i;
}

/// `at` held to `[first, last]`: a place past its thing's last is that last.
fn clampTo(comptime F: type, at: *F, first: usize, last: usize) void {
    switch (@typeInfo(F)) {
        .int => if (at.* > last) {
            at.* = @intCast(last);
        } else if (at.* < first) {
            at.* = @intCast(first);
        },
        .optional => |o| if (at.*) |*x| clampTo(o.child, x, first, last),
        else => @compileError("walk: a `place` is a number, not " ++ @typeName(F)),
    }
}

/// The types `T`'s value holds whose indexes name `T`'s things (a third word
/// `T`): held where `T`'s fields end.
fn heldIn(comptime T: type) []const type {
    comptime {
        if (!@hasDecl(T, "replica")) return &.{};
        var out: []const type = &.{};
        for (graph(&.{T})) |U| if (@typeInfo(U) == .@"struct") for (0..declared(U, "index")) |k| {
            const d = U.replica.index[k];
            if (d.len >= 3) if (d[1] == T) {
                out = out ++ .{U};
                break;
            };
        };
        return out;
    }
}

/// Whether a value of `X` can hold a `U`, as a dump walks it.
fn reaches(comptime X: type, comptime U: type) bool {
    comptime {
        @setEvalBranchQuota(100_000_000);
        return switch (kindOf(Canon(X))) {
            .@"struct", .optional, .one, .slice, .array, .@"union" => for (graph(&.{Canon(X)})) |Y| {
                if (Y == U) break true;
            } else false,
            else => false,
        };
    }
}

/// `v`'s places held to their things' last, then the first of its indexes,
/// and of every value it holds whose indexes name its things, that names
/// none (see above).
fn heldIndexes(comptime T: type, v: *T) ?Unnamed {
    inline for (0..comptime declared(T, "place")) |k| {
        const d = T.replica.place[k];
        const held = @field(T, d[1])(v);
        const span: [2]usize = if (@TypeOf(held) == usize) .{ 0, held } else held;
        clampTo(@FieldType(T, d[0]), &@field(v, d[0]), span[0], span[1]);
    }
    inline for (0..comptime declared(T, "index")) |k| {
        const d = T.replica.index[k];
        if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i|
            return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] };
    }
    inline for (0..comptime declared(T, "within")) |k| {
        const d = T.replica.within[k];
        for (0..heldOf(T, v, d[0])) |i| if (!@field(T, d[1])(v, i))
            return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1], .within = true };
    }
    inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad;
    return null;
}

/// Every `U` that `x` holds (its fields as a dump walks them, as far as each
/// length says; optionals, arrays, slices, lists, unions and pointers
/// followed), its indexes into `h`'s things held; the first that names none.
/// A value nested past `max_depth` (a pointer that is its own holder: a
/// damaged dump's) is refused too.
fn visit(comptime X: type, x: *const X, comptime U: type, comptime H: type, h: *const H, depth: u16) ?Unnamed {
    if (comptime !reaches(X, U)) return null;
    if (depth == max_depth) return .{ .holder = @typeName(X), .name = "", .says = depth, .of = "a depth a session's values nest to" };
    if (X == U) inline for (0..comptime declared(U, "index")) |k| {
        const d = U.replica.index[k];
        if (comptime d.len >= 3) if (comptime d[1] == H) {
            const of = @typeName(H) ++ "." ++ d[2];
            if (comptime d.len == 3) {
                if (firstUnnamed(U, x, d[0], H, h, d[2])) |i| return .{ .holder = @typeName(U), .name = d[0], .says = i, .of = of };
            } else {
                // A span: as many as its count says from it, all there (an
                // empty one may stand at their end).
                const end = @as(usize, @field(x, d[0])) +| @field(x, d[3]);
                if (end > heldOf(H, h, d[2])) return .{ .holder = @typeName(U), .name = d[0], .says = @field(x, d[0]), .of = of };
            }
        };
    };
    switch (@typeInfo(X)) {
        .optional => |o| if (x.*) |*c| return visit(o.child, c, U, H, h, depth + 1),
        .array => |a| for (x) |*e| if (visit(a.child, e, U, H, h, depth + 1)) |bad| return bad,
        .pointer => |p| switch (p.size) {
            .one => return visit(p.child, x.*, U, H, h, depth + 1),
            .slice => for (x.*) |*e| if (visit(p.child, e, U, H, h, depth + 1)) |bad| return bad,
            else => {},
        },
        .@"struct" => {
            if (comptime isAtomic(X)) return visit(@FieldType(X, "raw"), &x.raw, U, H, h, depth + 1);
            if (comptime isList(X)) return visit(@FieldType(X, "items"), &x.items, U, H, h, depth + 1);
            inline for (comptime dumpFields(X)) |name| {
                const F = @FieldType(X, name);
                if (comptime reaches(F, U)) {
                    if (comptime lengthOf(X, name) != null) {
                        for (@field(x, name)[0..heldOf(X, x, name)]) |*e| if (visit(Element(F), e, U, H, h, depth + 1)) |bad| return bad;
                    } else if (visit(F, &@field(x, name), U, H, h, depth + 1)) |bad| return bad;
                }
            }
        },
        .@"union" => switch (x.*) {
            inline else => |*payload| return visit(@TypeOf(payload.*), payload, U, H, h, depth + 1),
        },
        else => {},
    }
    return null;
}

/// `out`'s lengths held to what their buffers hold as read (`pastHeld`), and
/// its indexes to what they name (`heldIndexes`), where a reader (`Loader`,
/// `Get`) has read its fields: the dump refused, the field named. One that
/// left a thing out since `dropped` (another build's pane) first has `T`'s
/// `left_out` take out what names it.
fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, dropped: usize) error{BadDump}!void {
    if (pastHeld(T, out, held)) |past| {
        l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
        return error.BadDump;
    }
    if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out);
    if (heldIndexes(T, out)) |bad| {
        if (bad.within)
            l.note("{s}.{s}[{d}] is not within {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of })
        else
            l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of });
        return error.BadDump;
    }
}

/// A slot's type (`Pane.Id`, `View.Id`: an enum that is `at` a slot and
/// gives its `index`), bare, optional or in an array.
fn isSlot(comptime F: type) bool {
    return switch (@typeInfo(F)) {
        .optional => |o| isSlot(o.child),
        .array => |a| isSlot(a.child),
        .@"enum" => @hasDecl(F, "at") and @hasDecl(F, "index"),
        else => false,
    };
}

/// A field a dump carries that names a slot by its type says what it
/// indexes (`.index`): a compile error otherwise, so that one added later
/// is held where it is read back.
fn checkSlots(comptime T: type) void {
    for (dumpFields(T)) |name| if (isSlot(@FieldType(T, name))) {
        for (0..declared(T, "index")) |k| {
            if (std.mem.eql(u8, T.replica.index[k][0], name)) break;
        } else @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " names a slot: say what it indexes (`replica.index`)");
    };
}

/// Every name an annotation gives is a field (and what an index or a place
/// says it is held to, a field or a function): a rename cannot quietly put a
/// field back in the digest, nor take one out of its rule.
fn checkAnnotations(comptime T: type) void {
    if (!@hasDecl(T, "replica")) return;
    inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| {
        if (comptime std.mem.eql(u8, kind, "left_out")) {
            if (!@hasDecl(T, T.replica.left_out)) @compileError("walk: " ++ @typeName(T) ++ " has no " ++ T.replica.left_out ++ " for what a load left out");
            continue;
        }
        inline for (@field(T.replica, kind)) |entry| {
            const held = comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place") or std.mem.eql(u8, kind, "within");
            const pair = comptime held or std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc");
            const name = if (pair) entry[0] else entry;
            if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name);
            if (held) {
                const H = if (entry.len >= 3) entry[1] else T;
                const what = if (entry.len >= 3) entry[2] else entry[1];
                if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]);
                if (!@hasField(H, what) and !@hasDecl(H, what)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is held to " ++ what ++ ", which " ++ @typeName(H) ++ " has not");
            }
        }
    }
}

pub fn hash(comptime T: type, v: *const T, h: *Hasher) void {
    switch (@typeInfo(T)) {
        .void, .null, .undefined => {},
        .bool => h.update(&.{@intFromBool(v.*)}),
        .int => hashInt(T, v.*, h),
        .float => h.update(std.mem.asBytes(v)),
        .@"enum" => hashEnum(T, v.*, h),
        .optional => |o| if (v.*) |*payload| {
            h.update(&.{1});
            hash(o.child, payload, h);
        } else h.update(&.{0}),
        .array => |a| if (comptime flatHash(a.child)) h.update(std.mem.sliceAsBytes(v)) else for (v) |*e| hash(a.child, e, h),
        .pointer => |p| switch (p.size) {
            .one => hash(p.child, v.*, h),
            .slice => hashSlice(p.child, v.*, h),
            else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
        },
        .@"struct" => |s| {
            if (comptime machinery(T)) return;
            if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
            if (s.layout == .@"packed") return hashInt(s.backing_integer.?, @bitCast(v.*), h);
            if (comptime isList(T))
                return hashSlice(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, h);
            // std.atomic.Value: what it holds.
            if (comptime isAtomic(T)) return hash(@FieldType(T, "raw"), &v.raw, h);
            // A worker's future is a handle of the host's, never state.
            if (comptime @hasField(T, "any_future")) return;
            // std.DynamicBitSetUnmanaged: its bits.
            if (comptime isBitset(T)) {
                h.update(std.mem.asBytes(&v.bit_length));
                return h.update(std.mem.sliceAsBytes(v.masks[0 .. (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize)]));
            }
            comptime checkAnnotations(T);
            inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
                if (attr.@"comptime" or comptime excluded(T, name)) continue;
                if (comptime opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)");
                const was = in_blob;
                in_blob = comptime blob(T, name);
                defer in_blob = was;
                if (comptime lengthOf(T, name)) |len| {
                    hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], h);
                } else hash(F, &@field(v, name), h);
            }
        },
        .@"union" => |u| {
            if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
            if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
            const tag: u.tag_type.? = v.*;
            hash(u.tag_type.?, &tag, h);
            switch (v.*) {
                inline else => |*payload| hash(@TypeOf(payload.*), payload, h),
            }
        },
        .error_set => h.update(@errorName(v.*)),
        .error_union => |e| if (v.*) |*payload| {
            h.update(&.{1});
            hash(e.payload, payload, h);
        } else |err| {
            h.update(&.{0});
            h.update(@errorName(err));
        },
        else => @compileError("walk: cannot hash " ++ @typeName(T)),
    }
}

/// Bytes a digest takes whole: an enum's are its build's number, not it.
fn flatHash(comptime T: type) bool {
    return flat(T) and @typeInfo(T) != .@"enum";
}

/// An enum by its name, as a dump reads it, not by its number: an enum
/// made at compile time numbers its words as its build has them
/// (`registry.Builtin` has fewer in a FreeBSD build than a Linux one, which
/// has Tty9p), so a window client here of a session on the box loaded a
/// +LocationsConfig to another digest. A name's word (its hash, fixed
/// width, so that two names in a row are not one), looked up by number
/// where the words are numbered 0 up; one numbered by hand, or a value no
/// word has, by its number.
fn hashEnum(comptime T: type, v: T, h: *Hasher) void {
    const e = @typeInfo(T).@"enum";
    const words: ?[e.field_names.len]u64 = comptime words: {
        @setEvalBranchQuota(100_000);
        var out: [e.field_names.len]u64 = undefined;
        for (e.field_names, e.field_values, 0..) |name, n, i| {
            if (n != i) break :words null;
            out[i] = std.hash.Wyhash.hash(0, name);
        }
        break :words out;
    };
    const n = @backingInt(v);
    if (words) |table| if (n >= 0 and n < table.len) return h.update(std.mem.asBytes(&table[@intCast(n)]));
    hashInt(e.tag_type, n, h);
}

/// An integer by its value: one narrower than its bytes (a u21, an i2) has
/// bits in memory that are no part of it.
fn hashInt(comptime I: type, n: I, h: *Hasher) void {
    const W = @Int(@typeInfo(I).int.signedness, @sizeOf(I) * 8);
    const wide: W = n;
    h.update(std.mem.asBytes(&wide));
}

fn hashSlice(comptime E: type, items: []const E, h: *Hasher) void {
    if (in_blob and items.len * @sizeOf(E) >= blob_min) return hashBlob(E, items, h);
    h.update(std.mem.asBytes(&items.len));
    if (comptime flatHash(E)) return h.update(std.mem.sliceAsBytes(items));
    for (items) |*e| hash(E, e, h);
}

/// The value as bytes, the same walk: what the tape carries (core/tape.zig),
/// to a replica of another build too (a window of a terminal's session, a
/// Linux client of a FreeBSD one). Native byte order, which every machine
/// pardes runs on shares, and an error by its name: its number is its
/// build's own (a Linux terminal's FileNotFound is a window's
/// NoDefaultValue). What a field is laid out as (a std.Io.File.Stat's
/// `nlink` is another width on FreeBSD) is the tape's shape, which
/// wire.semantics hashes (`shape`).
pub fn encode(comptime T: type, v: *const T, w: *std.Io.Writer) std.Io.Writer.Error!void {
    switch (@typeInfo(T)) {
        .void, .null, .undefined => {},
        .bool, .int, .float, .@"enum" => try w.writeAll(std.mem.asBytes(v)),
        .optional => |o| if (comptime machinery(o.child)) try w.writeByte(0) else if (v.*) |*payload| {
            try w.writeByte(1);
            try encode(o.child, payload, w);
        } else try w.writeByte(0),
        .array => |a| if (comptime flat(a.child)) try w.writeAll(std.mem.sliceAsBytes(v)) else for (v) |*e| try encode(a.child, e, w),
        .pointer => |p| switch (p.size) {
            .one => try encode(p.child, v.*, w),
            .slice => {
                try w.writeAll(std.mem.asBytes(&v.len));
                if (comptime flat(p.child)) try w.writeAll(std.mem.sliceAsBytes(v.*)) else for (v.*) |*e| try encode(p.child, e, w);
            },
            else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
        },
        .@"struct" => |s| {
            if (comptime machinery(T)) return;
            if (s.layout == .@"packed") return w.writeAll(std.mem.asBytes(v));
            inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
                if (attr.@"comptime" or comptime excluded(T, name)) continue;
                try encode(F, &@field(v, name), w);
            }
        },
        .@"union" => |u| {
            if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
            const tag: u.tag_type.? = v.*;
            try encode(u.tag_type.?, &tag, w);
            switch (v.*) {
                inline else => |*payload| try encode(@TypeOf(payload.*), payload, w),
            }
        },
        .error_set => try encodeError(T, v.*, w),
        .error_union => |e| if (v.*) |*payload| {
            try w.writeByte(1);
            try encode(e.payload, payload, w);
        } else |err| {
            try w.writeByte(0);
            try encodeError(e.error_set, err, w);
        },
        else => @compileError("walk: cannot encode " ++ @typeName(T)),
    }
}

/// What `encode` lays each of `types` out as, in words: each field, element
/// and tag where it goes, an enum's names and numbers, an error as an
/// error (it goes by its name). wire.semantics hashes the tape's: builds
/// whose tapes differ in shape, as a FreeBSD std.Io.File.Stat differs from
/// a Linux one, refuse each other's replicas in words, not read each other
/// out of step.
pub fn shape(comptime types: []const type) []const u8 {
    comptime {
        @setEvalBranchQuota(10_000_000);
        var out: []const u8 = "";
        for (types) |T| out = out ++ (shapeOf(T, 0) ++ "\n");
        return out;
    }
}

fn shapeOf(comptime T: type, comptime depth: u8) []const u8 {
    comptime {
        if (depth > 32) @compileError("walk: the tape's shape nests past 32 deep at " ++ @typeName(T) ++ ": a type that holds itself?");
        return switch (@typeInfo(T)) {
            .void, .null, .undefined => "v",
            .bool => "b",
            .int => |i| @tagName(i.signedness) ++ decimal(i.bits),
            .float => |f| "f" ++ decimal(f.bits),
            .@"enum" => |e| blk: {
                var out: []const u8 = shapeOf(e.tag_type, depth + 1) ++ "{";
                for (e.field_names, e.field_values) |n, v| out = out ++ (n ++ "=" ++ decimal(v) ++ ",");
                break :blk out ++ "}";
            },
            .optional => |o| if (machinery(o.child)) "0" else "?" ++ shapeOf(o.child, depth + 1),
            .array => |a| "[" ++ decimal(a.len) ++ "]" ++ shapeOf(a.child, depth + 1),
            .pointer => |p| switch (p.size) {
                .one => shapeOf(p.child, depth + 1),
                .slice => "[]" ++ shapeOf(p.child, depth + 1),
                else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
            },
            .@"struct" => |s| blk: {
                if (machinery(T)) break :blk "";
                var out: []const u8 = if (s.layout == .@"packed") "p{" else "{";
                for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
                    if (attr.@"comptime" or excluded(T, name)) continue;
                    out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ",");
                }
                break :blk out ++ "}";
            },
            .@"union" => |u| blk: {
                var out: []const u8 = shapeOf(u.tag_type.?, depth + 1) ++ "(";
                for (u.field_names, u.field_types) |name, F| out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ",");
                break :blk out ++ ")";
            },
            .error_set => "error",
            .error_union => |e| "!" ++ shapeOf(e.payload, depth + 1),
            else => @compileError("walk: cannot encode " ++ @typeName(T)),
        };
    }
}

/// `n` in decimal, as `{d}` writes it: memoized, where comptimePrint (an
/// inline function) formats again at every call, 5e6 of the compiler's
/// instructions each.
fn decimal(comptime n: comptime_int) []const u8 {
    if (n < 0) return "-" ++ decimal(-n);
    if (n < 10) return &.{'0' + n};
    return decimal(n / 10) ++ &[_]u8{'0' + n % 10};
}

/// An error by its name. An `anyerror` must be one `decode` can read back
/// (`errorNamed`): a Debug build stops at one that is not, as it is taped.
fn encodeError(comptime E: type, err: E, w: *std.Io.Writer) std.Io.Writer.Error!void {
    if (comptime E == anyerror and builtin.mode == .debug) if (errorNamed(E, @errorName(err)) == null)
        std.debug.panic("walk: error.{s} is taped as an anyerror, which a replica reads back only as one of tape.Failure's: add the set it comes from", .{@errorName(err)});
    try writeName(w, @errorName(err));
}

/// The error of `E` called `name`. `anyerror` keeps no list of its names
/// to look one up in: one is read back as one of tape.Failure's, what a
/// host reports as failed (the tape's only anyerrors).
fn errorNamed(comptime E: type, name: []const u8) ?E {
    const Named = if (E == anyerror) @import("tape.zig").Failure else E;
    inline for (@typeInfo(Named).error_set.error_names.?) |n| if (std.mem.eql(u8, name, n)) return @field(Named, n);
    return null;
}

pub const Reader = struct {
    bytes: []const u8,
    at: usize = 0,

    pub fn take(r: *Reader, n: usize) error{EndOfTape}![]const u8 {
        if (r.bytes.len - r.at < n) return error.EndOfTape;
        defer r.at += n;
        return r.bytes[r.at..][0..n];
    }

    fn scalar(r: *Reader, comptime T: type) error{EndOfTape}!T {
        return std.mem.bytesToValue(T, try r.take(@sizeOf(T)));
    }
};

/// What an error read back is when this build has none of that name (an
/// OS's own, a newer build's): the tape is another build's, and diverges;
/// BadTape, a value none of its type's (an enum's number of no name).
const TapeError = error{ EndOfTape, OutOfMemory, NoSuchError, BadTape };

/// An enum's bytes as `encode` writes them (`@sizeOf(E)` of them), read
/// checked: null for a number none of `E`'s names has, which a tape or a
/// dump read back may hold (cut, flipped, a hostile peer's), never cast.
pub fn enumFrom(comptime E: type, bytes: *const [@sizeOf(E)]u8) ?E {
    const info = @typeInfo(E).@"enum";
    const wide = std.mem.bytesToValue(@Int(.unsigned, @sizeOf(E) * 8), bytes);
    const tag: info.tag_type = @bitCast(@as(@Int(.unsigned, @bitSizeOf(info.tag_type)), @truncate(wide)));
    if (info.mode == .nonexhaustive) return @fromBackingInt(tag);
    return std.enums.fromInt(E, tag);
}

/// `bytes`, a run of `E`s copied whole, when each is one of `E`'s names (an
/// enum's run is checked as one read alone is; another flat type's is bytes).
fn named(comptime E: type, bytes: []const u8) error{BadTape}![]const u8 {
    if (comptime @typeInfo(E) != .@"enum" or @typeInfo(E).@"enum".mode == .nonexhaustive) return bytes;
    var at: usize = 0;
    while (at < bytes.len) : (at += @sizeOf(E)) if (enumFrom(E, bytes[at..][0..@sizeOf(E)]) == null) return error.BadTape;
    return bytes;
}

/// The fewest bytes `encode` writes for a `T`: a count read back is held to
/// the bytes left before anything is made for it (0: no such bound).
fn least(comptime T: type) usize {
    return switch (@typeInfo(T)) {
        .bool, .int, .float, .@"enum" => @sizeOf(T),
        .optional, .error_union => 1,
        .array => |a| a.len * least(a.child),
        .pointer => |p| if (p.size == .slice) @sizeOf(usize) else 0,
        .@"union" => |u| @sizeOf(u.tag_type.?),
        .@"struct" => |s| sum: {
            if (s.layout == .@"packed") break :sum @sizeOf(T);
            if (machinery(T)) break :sum 0;
            var n: usize = 0;
            for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
                if (attr.@"comptime" or excluded(T, name)) continue;
                n += least(F);
            }
            break :sum n;
        },
        else => 0,
    };
}

/// The inverse of `encode`; slices (and what a pointer points at) are made
/// in `a`. A field `encode` left out is its default.
pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T {
    switch (@typeInfo(T)) {
        .void, .null, .undefined => return {},
        .bool => return (try r.take(1))[0] != 0,
        .int, .float => return r.scalar(T),
        .@"enum" => return enumFrom(T, (try r.take(@sizeOf(T)))[0..@sizeOf(T)]) orelse error.BadTape,
        .optional => |o| {
            if ((try r.take(1))[0] == 0) return null;
            if (comptime machinery(o.child)) unreachable;
            return try decode(o.child, r, a);
        },
        .array => |a_info| {
            var out: T = undefined;
            if (comptime flat(a_info.child)) {
                @memcpy(std.mem.sliceAsBytes(&out), try named(a_info.child, try r.take(@sizeOf(T))));
            } else for (&out) |*e| {
                e.* = try decode(a_info.child, r, a);
            }
            return out;
        },
        .pointer => |p| switch (p.size) {
            .one => {
                const out = try a.create(p.child);
                out.* = try decode(p.child, r, a);
                return out;
            },
            .slice => {
                const n = try r.scalar(usize);
                // More than the bytes left could hold: refused before it is made.
                const min = comptime least(p.child);
                if (min > 0 and n > (r.bytes.len - r.at) / min) return error.EndOfTape;
                const out = try a.alloc(p.child, n);
                if (comptime flat(p.child)) {
                    @memcpy(std.mem.sliceAsBytes(out), try named(p.child, try r.take(n * @sizeOf(p.child))));
                } else for (out) |*e| {
                    e.* = try decode(p.child, r, a);
                }
                return out;
            },
            else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
        },
        .@"struct" => |s| {
            if (s.layout == .@"packed") return r.scalar(T);
            var out: T = undefined;
            inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
                if (attr.@"comptime") continue;
                if (comptime excluded(T, name)) {
                    const default = attr.default_value_ptr orelse @compileError("walk: " ++ name ++ " has no default to decode to");
                    @field(out, name) = @as(*const F, @ptrCast(@alignCast(default))).*;
                } else if (comptime @typeInfo(F) == .error_set) {
                    // No `!anyerror` to return it through: read in place.
                    try decodeError(F, r, &@field(out, name));
                } else @field(out, name) = try decode(F, r, a);
            }
            if (pastHeld(T, &out, null) != null or heldIndexes(T, &out) != null) return error.BadTape;
            return out;
        },
        .@"union" => |u| {
            const tag = try decode(u.tag_type.?, r, a);
            inline for (u.field_names, u.field_types) |name, F| if (tag == @field(u.tag_type.?, name)) {
                return @unionInit(T, name, try decode(F, r, a));
            };
            unreachable;
        },
        .error_union => |e| {
            if ((try r.take(1))[0] != 0) return try decode(e.payload, r, a);
            // The value's error, not decode's own.
            var err: e.error_set = undefined;
            try decodeError(e.error_set, r, &err);
            return @as(T, err);
        },
        else => @compileError("walk: cannot decode " ++ @typeName(T)),
    }
}

/// An error by its name, as `encode` wrote it, into `out`: no error union
/// holds an error set.
fn decodeError(comptime E: type, r: *Reader, out: *E) TapeError!void {
    const len = try r.scalar(u16);
    out.* = errorNamed(E, try r.take(len)) orelse return error.NoSuchError;
}

// ---- the dump: the same walk, by name, for another build ----
//
// A dump (docs/next-daemon.md, phase 2) is `dump_magic`, then a table of
// every type its roots' walk reaches -- each struct's and union's fields by
// name, each enum's names, each number's width -- then each root's value,
// laid out as `encode` lays it out but for three things: an enum or a
// union's tag is its place among the table's names, a pointer or a slice met
// again is a reference to the first (what two fields share is shared again),
// and a type with a `dumpWrite` of its own is its bytes, counted.
//
// A build that is not the writer's matches by name: a field added since
// takes its default, one removed is passed over, one whose kind changed
// takes its default and says so (`Decoder.notes`). With no default to take,
// the value it is part of is refused (`error.Incompatible`), and an element
// of an array of optional pointers (a session's panes) is then left out,
// nothing above it. A dump whose table is this build's own is read field
// after field, no name asked.
//
// Native byte order: the machines pardes runs on are all little-endian.

const dump_magic = "pardes-dump\x00\x02\n";

const Kind = enum(u8) { skip, void, bool, int, float, @"enum", optional, one, slice, array, prefix, @"struct", @"union", err, error_union, custom, bitset };

/// std's lists: their items, not the capacity behind them (nor, in a safe
/// build, the lock that checks no pointer into them moves).
pub fn isList(comptime T: type) bool {
    if (@typeInfo(T) != .@"struct" or !@hasField(T, "items") or !@hasField(T, "capacity")) return false;
    const n = @typeInfo(T).@"struct".field_names.len;
    return n == 2 or (n == 3 and @hasField(T, "pointer_stability"));
}
fn isAtomic(comptime T: type) bool {
    return @typeInfo(T) == .@"struct" and @hasField(T, "raw") and @typeInfo(T).@"struct".field_names.len == 1 and @hasDecl(T, "load");
}
fn isBitset(comptime T: type) bool {
    return @typeInfo(T) == .@"struct" and @hasField(T, "bit_length") and @hasField(T, "masks") and @typeInfo(T).@"struct".field_names.len == 2;
}

/// A field written only as far as its `len` says: a count, then that many.
fn Prefix(comptime E: type) type {
    return struct {
        pub const element = E;
    };
}

/// What the dump walks `T` as: an atomic as what it holds, a list as its
/// items.
fn Canon(comptime T: type) type {
    if (comptime isAtomic(T)) return Canon(@FieldType(T, "raw"));
    if (comptime isList(T)) return []@typeInfo(@FieldType(T, "items")).pointer.child;
    return T;
}

fn kindOf(comptime T: type) Kind {
    return switch (@typeInfo(T)) {
        .void, .null, .undefined => .void,
        .bool => .bool,
        .int => .int,
        .float => .float,
        .@"enum" => .@"enum",
        .optional => .optional,
        .array => .array,
        .pointer => |p| switch (p.size) {
            .one => .one,
            .slice => .slice,
            else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
        },
        .@"struct" => if (machinery(T) or @hasField(T, "any_future"))
            .skip
        else if (@hasDecl(T, "dumpWrite"))
            .custom
        else if (@hasDecl(T, "element") and T == Prefix(T.element))
            .prefix
        else if (isBitset(T))
            .bitset
        else
            .@"struct",
        .@"union" => |u| if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)) else .@"union",
        else => @compileError("walk: cannot dump " ++ @typeName(T)),
    };
}

/// The fields of struct `T` a dump holds, in order.
fn dumpFields(comptime T: type) []const [:0]const u8 {
    comptime {
        @setEvalBranchQuota(1_000_000);
        var names: []const [:0]const u8 = &.{};
        const s = @typeInfo(T).@"struct";
        for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
            if (attr.@"comptime" or excluded(T, name) or kindOf(Canon(F)) == .skip) continue;
            if (opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)");
            names = names ++ .{name};
        }
        return names;
    }
}

/// The type a dump walks field `name` of `T` as.
fn FieldDump(comptime T: type, comptime name: []const u8) type {
    const F = @FieldType(T, name);
    if (comptime cutArray(T, name)) return Prefix(Canon(@typeInfo(F).array.child));
    return Canon(F);
}

/// A fixed array a `len` cuts, which a dump writes as far as it says. A
/// slice it cuts (a text's room for its ranges, made whole) is written
/// whole, room and all, which only plain numbers may be: a load gives it
/// the room it had.
fn cutArray(comptime T: type, comptime name: []const u8) bool {
    const F = @FieldType(T, name);
    if (comptime lengthOf(T, name) == null) return false;
    if (@typeInfo(F) == .array) return true;
    if (!plain(Element(F))) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is a slice a `len` cuts, of what a dump cannot write past the cut");
    return false;
}

/// Every bit pattern one of its values: what a dump may write where
/// nothing was ever written.
fn plain(comptime T: type) bool {
    return switch (@typeInfo(T)) {
        .int, .float => true,
        .array => |a| plain(a.child),
        .@"struct" => |st| st.layout != .@"packed" and blk: {
            for (st.field_types) |F| if (!plain(F)) break :blk false;
            break :blk true;
        },
        else => false,
    };
}

fn children(comptime T: type) []const type {
    comptime {
        return switch (kindOf(T)) {
            .optional => &.{Canon(@typeInfo(T).optional.child)},
            .one, .slice => &.{Canon(@typeInfo(T).pointer.child)},
            .array => &.{Canon(@typeInfo(T).array.child)},
            .prefix => &.{T.element},
            .@"struct" => blk: {
                var out: []const type = &.{};
                for (dumpFields(T)) |name| out = out ++ .{FieldDump(T, name)};
                break :blk out;
            },
            .@"union" => blk: {
                var out: []const type = &.{};
                for (@typeInfo(T).@"union".field_types) |F| out = out ++ .{Canon(F)};
                break :blk out;
            },
            else => &.{},
        };
    }
}

fn collect(comptime T: type, comptime list: []const type) []const type {
    comptime {
        for (list) |U| if (U == T) return list;
        var out: []const type = list ++ .{T};
        if (kindOf(T) == .@"struct") {
            checkAnnotations(T);
            checkSlots(T);
        }
        for (children(T)) |C| out = collect(C, out);
        return out;
    }
}

/// Every type the walk of `roots` reaches, each once.
fn graph(comptime roots: []const type) []const type {
    comptime {
        @setEvalBranchQuota(100_000_000);
        var list: []const type = &.{};
        for (roots) |R| list = collect(Canon(R), list);
        return list;
    }
}

/// The types the walk of `roots` reaches that walk themselves by hand (a
/// `digest` or a `dumpWrite` of their own): the ones whose digest can take
/// what their dump does not carry, which the one walk holds for the rest.
pub fn handWalked(comptime roots: []const type) []const type {
    comptime {
        var out: []const type = &.{};
        for (graph(roots)) |T| switch (@typeInfo(T)) {
            .@"struct", .@"union" => if (@hasDecl(T, "dumpWrite") or (@hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void)) {
                out = out ++ .{T};
            },
            else => {},
        };
        return out;
    }
}

fn indexIn(comptime types: []const type, comptime T: type) u32 {
    comptime {
        @setEvalBranchQuota(100_000_000);
        for (types, 0..) |U, i| if (U == T) return i;
        @compileError("walk: not in the dump's table: " ++ @typeName(T));
    }
}

/// How many bytes an integer of `bits` is written in: its own size.
fn intBytes(bits: u16) usize {
    return if (bits == 0) 0 else if (bits <= 8) 1 else if (bits <= 16) 2 else if (bits <= 32) 4 else if (bits <= 64) 8 else 16;
}

fn writeName(w: *std.Io.Writer, name: []const u8) !void {
    try w.writeAll(std.mem.asBytes(&@as(u16, @intCast(name.len))));
    try w.writeAll(name);
}

fn writeU32(w: *std.Io.Writer, n: u32) !void {
    try w.writeAll(std.mem.asBytes(&n));
}

fn writeTable(comptime types: []const type, w: *std.Io.Writer) !void {
    try writeU32(w, types.len);
    inline for (types) |T| {
        const k = comptime kindOf(T);
        try w.writeByte(@backingInt(k));
        switch (k) {
            .int => {
                try w.writeByte(@intFromBool(@typeInfo(T).int.signedness == .signed));
                try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).int.bits)));
            },
            .float => try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).float.bits))),
            .@"enum" => {
                const e = @typeInfo(T).@"enum";
                const tag = @typeInfo(e.tag_type).int;
                try w.writeByte(@intFromBool(tag.signedness == .signed));
                try w.writeAll(std.mem.asBytes(&@as(u16, tag.bits)));
                try writeU32(w, e.field_names.len);
                inline for (e.field_names, e.field_values) |name, value| {
                    try writeName(w, name);
                    try w.writeAll(std.mem.asBytes(&@as(i128, value)));
                }
            },
            .array => {
                try w.writeAll(std.mem.asBytes(&@as(u64, @typeInfo(T).array.len)));
                try writeU32(w, comptime indexIn(types, children(T)[0]));
            },
            .optional, .one, .slice, .prefix, .error_union => try writeU32(w, comptime indexIn(types, children(T)[0])),
            .@"struct" => {
                const names = comptime dumpFields(T);
                try writeU32(w, names.len);
                inline for (names) |name| {
                    try writeName(w, name);
                    try writeU32(w, comptime indexIn(types, FieldDump(T, name)));
                }
            },
            .@"union" => {
                const u = @typeInfo(T).@"union";
                try writeU32(w, u.field_names.len);
                inline for (u.field_names, u.field_types) |name, F| {
                    try writeName(w, name);
                    try writeU32(w, comptime indexIn(types, Canon(F)));
                }
            },
            .custom => try writeName(w, @typeName(T)),
            .skip, .void, .bool, .err, .bitset => {},
        }
    }
}

/// Integers by value, in the bytes `intBytes` gives them: a `u21`'s
/// padding is no part of it.
fn putInt(comptime I: type, n: I, w: *std.Io.Writer) !void {
    const info = @typeInfo(I).int;
    const W = @Int(info.signedness, intBytes(info.bits) * 8);
    const wide: W = n;
    try w.writeAll(std.mem.asBytes(&wide));
}

/// The table of `types` as bytes, made once a process (it is the build's):
/// a store record or a dump writes it, a load compares it.
fn tableOf(comptime types: []const type) []const u8 {
    const Once = struct {
        // Of these types alone: a container that named none of its
        // function's parameters would be one for every table.
        const of = types;
        /// 0 none, 1 being made, 2 made.
        var state: std.atomic.Value(u8) = .init(0);
        var bytes: []const u8 = &.{};
    };
    if (Once.state.load(.acquire) == 2) return Once.bytes;
    if (Once.state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) {
        var out: std.Io.Writer.Allocating = .init(std.heap.page_allocator);
        writeTable(types, &out.writer) catch @panic("walk: out of memory for a dump's table");
        Once.bytes = out.toOwnedSlice() catch @panic("walk: out of memory for a dump's table");
        Once.state.store(2, .release);
    } else while (Once.state.load(.acquire) != 2) std.atomic.spinLoopHint();
    return Once.bytes;
}

/// A blob's bytes a dump left out (`Dump.deferred`): they go at `at`.
pub const Deferred = struct { at: usize, bytes: []const u8 };

/// Writes a dump of `roots`' values, one `put` each in order.
pub fn Dump(comptime roots: []const type) type {
    return struct {
        const Self = @This();
        pub const types = graph(roots);

        gpa: std.mem.Allocator,
        out: std.Io.Writer.Allocating,
        memo: std.AutoHashMapUnmanaged(Key, u32) = .empty,
        /// Set: a `.blob`'s bytes (of `blob_min` and up) are not written but
        /// noted, where they go and what they are; the dump with them put
        /// back in place is the dump. A replica's join streams them from
        /// its writer thread (core/replica.zig), the session's step paying
        /// for the rest alone.
        deferred: ?*std.ArrayListUnmanaged(Deferred) = null,
        in_blob: bool = false,

        const Key = struct { addr: usize, len: usize, ty: u32 };

        pub fn init(gpa: std.mem.Allocator) !Self {
            var d: Self = .{ .gpa = gpa, .out = .init(gpa) };
            errdefer d.out.deinit();
            try d.out.writer.writeAll(dump_magic);
            try d.out.writer.writeAll(tableOf(types));
            return d;
        }

        pub fn deinit(d: *Self) void {
            d.memo.deinit(d.gpa);
            d.out.deinit();
        }

        /// The dump, the caller's (gpa).
        pub fn finish(d: *Self) ![]u8 {
            d.memo.deinit(d.gpa);
            d.memo = .empty;
            return d.out.toOwnedSlice();
        }

        pub fn put(d: *Self, comptime T: type, v: *const T) !void {
            try writeU32(&d.out.writer, comptime indexIn(types, Canon(T)));
            try d.value(T, v);
        }

        /// Whether the pointer or slice at `addr` was met before: its
        /// reference written if so, else 0 and it is noted.
        fn seen(d: *Self, comptime T: type, addr: usize, len: usize) Error!bool {
            const w = &d.out.writer;
            if (len == 0) {
                try writeU32(w, 0);
                return false;
            }
            const got = try d.memo.getOrPut(d.gpa, .{ .addr = addr, .len = len, .ty = comptime indexIn(types, Canon(T)) });
            if (got.found_existing) {
                try writeU32(w, got.value_ptr.*);
                return true;
            }
            got.value_ptr.* = @intCast(d.memo.count());
            try writeU32(w, 0);
            return false;
        }

        const Error = std.Io.Writer.Error || std.mem.Allocator.Error;

        fn items(d: *Self, comptime E: type, slice: []const E) Error!void {
            const w = &d.out.writer;
            try w.writeAll(std.mem.asBytes(&@as(u64, slice.len)));
            if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(slice));
            for (slice) |*e| try d.value(E, e);
        }

        fn value(d: *Self, comptime T: type, v: *const T) Error!void {
            if (comptime isAtomic(T)) return d.value(@FieldType(T, "raw"), &v.raw);
            const w = &d.out.writer;
            if (comptime isList(T)) {
                const E = @typeInfo(@FieldType(T, "items")).pointer.child;
                if (try d.seen([]E, @intFromPtr(v.items.ptr), v.items.len)) return;
                return d.items(E, v.items);
            }
            switch (comptime kindOf(T)) {
                .skip, .void => {},
                .bool => try w.writeByte(@intFromBool(v.*)),
                .int => try putInt(T, v.*, w),
                .float => try w.writeAll(std.mem.asBytes(v)),
                .@"enum" => try putInt(@typeInfo(T).@"enum".tag_type, @backingInt(v.*), w),
                .optional => if (v.*) |*payload| {
                    try w.writeByte(1);
                    try d.value(@typeInfo(T).optional.child, payload);
                } else try w.writeByte(0),
                .one => {
                    const C = @typeInfo(T).pointer.child;
                    if (try d.seen(T, @intFromPtr(v.*), @max(1, @sizeOf(C)))) return;
                    try d.value(C, v.*);
                },
                .slice => {
                    const E = @typeInfo(T).pointer.child;
                    if (try d.seen(T, @intFromPtr(v.ptr), v.len)) return;
                    if (comptime flat(E)) if (d.in_blob) if (d.deferred) |later| {
                        const bytes = std.mem.sliceAsBytes(v.*);
                        if (bytes.len >= blob_min) {
                            try w.writeAll(std.mem.asBytes(&@as(u64, v.len)));
                            return later.append(d.gpa, .{ .at = d.out.writer.end, .bytes = bytes });
                        }
                    };
                    try d.items(E, v.*);
                },
                .array => {
                    const E = @typeInfo(T).array.child;
                    if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(v));
                    for (v) |*e| try d.value(E, e);
                },
                .prefix => unreachable,
                .@"struct" => {
                    const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
                    inline for (comptime dumpFields(T)) |name| {
                        const F = @FieldType(T, name);
                        const was = d.in_blob;
                        d.in_blob = was or comptime blob(T, name);
                        defer d.in_blob = was;
                        if (comptime cutArray(T, name)) {
                            const all = &@field(v, name);
                            try d.items(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))]);
                        } else if (packed_struct) {
                            const copy: F = @field(v, name);
                            try d.value(F, &copy);
                        } else try d.value(F, &@field(v, name));
                    }
                },
                .@"union" => {
                    const tag = std.meta.activeTag(v.*);
                    const ordinal: u16 = inline for (@typeInfo(T).@"union".field_names, 0..) |name, i| {
                        if (tag == @field(std.meta.Tag(T), name)) break i;
                    } else unreachable;
                    try w.writeAll(std.mem.asBytes(&ordinal));
                    switch (v.*) {
                        inline else => |*payload| try d.value(@TypeOf(payload.*), payload),
                    }
                },
                // Kinds an old dump's table may name (`skip`); no type walked here has them.
                .err, .error_union => unreachable,
                .custom => {
                    const at = d.out.writer.end;
                    try w.writeAll(&std.mem.toBytes(@as(u64, 0)));
                    T.dumpWrite(v, d.gpa, w) catch return error.WriteFailed;
                    const n: u64 = d.out.writer.end - at - 8;
                    @memcpy(d.out.writer.buffer[at..][0..8], std.mem.asBytes(&n));
                },
                .bitset => {
                    try w.writeAll(std.mem.asBytes(&@as(u64, v.bit_length)));
                    const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
                    if (words > 0) try w.writeAll(std.mem.sliceAsBytes(v.masks[0..words]));
                },
            }
        }
    };
}

/// One value `T` as a dump of its own (gpa): a closed pane, a terminal's
/// parts that are not its emulator.
pub fn save(comptime T: type, gpa: std.mem.Allocator, v: *const T) ![]u8 {
    var d = try Dump(&.{T}).init(gpa);
    errdefer d.deinit();
    try d.put(T, v);
    return d.finish();
}

const DecodeError = error{ EndOfDump, BadDump, Incompatible, OutOfMemory };

/// The allocators a `replica.alloc` annotation may name, beside the
/// loader's own: `.alloc = .{ .{ "image", "image" } }` makes what field
/// `image` holds with `allocs.image`.
const Allocators = struct {
    image: ?std.mem.Allocator = null,
    terminal: ?std.mem.Allocator = null,
};

fn allocOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
    if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "alloc")) return null;
    inline for (T.replica.alloc) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1];
    return null;
}

fn countOf(n: u64) DecodeError!usize {
    return std.math.cast(usize, n) orelse error.BadDump;
}

/// An allocation a load made: what a reference to it finds, and what a
/// failed load frees. `of`: what it holds (`typeWord` of its element); a
/// reference read back is to a value of its own type, or the dump is
/// refused (a damaged one would have one type's bytes read as another's,
/// pointers and all).
const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false, of: u64 = 0 };

/// How far a reader had made things before a value: what that value made
/// is everything after it (`letGo`).
const Mark = struct { made: usize, customs: usize };

/// A type as the dump's writer had it.
const SrcType = struct {
    kind: Kind,
    signed: bool = false,
    bits: u16 = 0,
    child: u32 = 0,
    len: u64 = 0,
    /// A struct's or union's fields, an enum's names (and `value`s).
    fields: []const SrcField = &.{},
};
const SrcField = struct { name: []const u8, ty: u32 = 0, value: i128 = 0 };

/// Reads a dump of `roots`, one `into` or `get` each in order: a `Loader`
/// told this build's table of them.
pub fn Load(comptime roots: []const type) type {
    return struct {
        pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Loader {
            return Loader.init(gpa, bytes, tableOf(graph(roots)));
        }
    };
}

/// How deep a dump's types nest, at most: a session's are about twenty.
const max_depth = 256;

/// `Load`'s reader, one for every root set: it reads by the dump's own
/// table, and this build's (`table`) only says whether the two are one.
pub const Loader = struct {
    const Self = @This();

    /// Where what is read is made (a `replica.alloc` field's own
    /// allocator while it is read).
    gpa: std.mem.Allocator,
    /// The loader's own lists'.
    own: std.mem.Allocator,
    bytes: []const u8,
    at: usize = 0,
    arena: std.heap.ArenaAllocator,
    src: []SrcType = &.{},
    /// Its table is this build's: no name is asked.
    same: bool = false,
    /// Each pointer and slice made so far: what a reference finds, and
    /// what `rollback` frees.
    shared: std.ArrayList(Made) = .empty,
    /// What a type's `dumpRead` made, freed by its `dumpFree` too.
    customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty,
    /// What was let go, for the person whose session it is.
    notes: std.ArrayList(u8) = .empty,
    /// The field being read, for a note.
    field: []const u8 = "",
    /// Where a field's annotation (`replica.alloc`) says its values are
    /// made instead of `gpa`.
    allocs: Allocators = .{},
    /// How many elements the last array or slice read holds (`pastHeld`).
    filled: usize = 0,
    /// How deep `skip` is in the dump's own types.
    depth: u16 = 0,
    /// How many things (a session's panes) it left out (`holdTo`).
    dropped: usize = 0,

    pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self {
        var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) };
        errdefer l.arena.deinit();
        if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump;
        l.at = dump_magic.len;
        const table_at = l.at;
        try l.readTable();
        l.same = std.mem.eql(u8, table, bytes[table_at..l.at]);
        return l;
    }

    pub fn deinit(l: *Self) void {
        l.shared.deinit(l.own);
        l.customs.deinit(l.own);
        l.notes.deinit(l.own);
        l.arena.deinit();
    }

    /// Everything read so far freed: a load that fails leaves nothing.
    /// What it was read into must not be used after (nor freed).
    pub fn rollback(l: *Self) void {
        for (l.customs.items) |c| c.free(c.ptr, c.gpa);
        for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
        l.customs.clearRetainingCapacity();
        l.shared.clearRetainingCapacity();
    }

    fn mark(l: *const Self) Mark {
        return .{ .made = l.shared.items.len, .customs = l.customs.items.len };
    }

    /// What was made since `at`, freed: the value it was made for was left
    /// out or took its default (another build's, or a damaged dump's), so
    /// nothing holds it. A reference to it later is refused (`dead`).
    fn letGo(l: *Self, at: Mark) void {
        for (l.customs.items[at.customs..]) |c| c.free(c.ptr, c.gpa);
        l.customs.shrinkRetainingCapacity(at.customs);
        for (l.shared.items[at.made..]) |*m| {
            if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
            m.bytes = &.{};
            m.dead = true;
        }
    }

    fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment, of: u64) DecodeError!usize {
        try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of });
        return l.shared.items.len - 1;
    }

    fn take(l: *Self, n: usize) DecodeError![]const u8 {
        if (l.bytes.len - l.at < n) return error.EndOfDump;
        defer l.at += n;
        return l.bytes[l.at..][0..n];
    }

    fn scalar(l: *Self, comptime T: type) DecodeError!T {
        return std.mem.bytesToValue(T, try l.take(@sizeOf(T)));
    }

    /// A count, as this machine counts (a wasm32 one has 32 bits).
    fn count(l: *Self) DecodeError!usize {
        return countOf(try l.scalar(u64));
    }

    /// A bitset's count of bits, its words no more than the bytes left.
    fn bitCount(l: *Self) DecodeError!usize {
        const n = try l.count();
        if (n / 64 > (l.bytes.len - l.at) / 8) return error.EndOfDump;
        return n;
    }

    fn name(l: *Self) DecodeError![]const u8 {
        return l.take(try l.scalar(u16));
    }

    /// The count of a table's entries of `each` bytes at least read next,
    /// no more than the bytes left hold: a damaged one sizes nothing.
    fn entries(l: *Self, each: usize) DecodeError!usize {
        const n = try l.scalar(u32);
        if (n > (l.bytes.len - l.at) / each) return error.BadDump;
        return n;
    }

    fn readTable(l: *Self) DecodeError!void {
        const a = l.arena.allocator();
        // A type is its kind's byte at least; a name its length's two.
        const n = try l.entries(1);
        l.src = try a.alloc(SrcType, n);
        for (l.src) |*t| {
            const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump;
            t.* = .{ .kind = k };
            switch (k) {
                .int => {
                    t.signed = (try l.take(1))[0] != 0;
                    t.bits = try l.scalar(u16);
                },
                .float => t.bits = try l.scalar(u16),
                .@"enum" => {
                    t.signed = (try l.take(1))[0] != 0;
                    t.bits = try l.scalar(u16);
                    const list = try a.alloc(SrcField, try l.entries(2 + 16));
                    for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) };
                    t.fields = list;
                },
                .array => {
                    t.len = try l.scalar(u64);
                    t.child = try l.scalar(u32);
                },
                .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32),
                .@"struct", .@"union" => {
                    const list = try a.alloc(SrcField, try l.entries(2 + 4));
                    for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) };
                    t.fields = list;
                },
                .custom => _ = try l.name(),
                .skip, .void, .bool, .err, .bitset => {},
            }
        }
        for (l.src) |t| {
            if (t.child >= n) return error.BadDump;
            for (t.fields) |f| if (f.ty >= n) return error.BadDump;
        }
    }

    pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void {
        if (l.notes.items.len > 4096) return;
        l.notes.print(l.own, fmt ++ "\n", args) catch {};
    }

    /// A note on a type's field, its names given as run-time strings:
    /// one instance of `note` (and of std's `print`) a message, where
    /// a tuple of the comptime names made one a type, field and message.
    fn noteField(l: *Self, comptime what: []const u8, type_name: []const u8, field: []const u8) void {
        l.note("{s}.{s}: " ++ what, .{ type_name, field });
    }

    fn root(l: *Self) DecodeError!u32 {
        const ty = try l.scalar(u32);
        if (ty >= l.src.len) return error.BadDump;
        return ty;
    }

    /// The next root, made: what it points at is `gpa`'s.
    pub fn get(l: *Self, comptime T: type) DecodeError!T {
        // A root that fails lets go of what it had made: its caller's books
        // (a load's, cut back past what it frees itself) never hold half
        // of a value.
        const at = l.mark();
        errdefer l.letGo(at);
        var out: T = undefined;
        try l.fresh(T, &out);
        try l.value(T, try l.root(), &out);
        return out;
    }

    /// The next root read into `out` as it stands: a field the dump
    /// holds is replaced (what it held is not freed), every other one
    /// is left as it is. A field another build cannot give is left too,
    /// and noted.
    pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void {
        const ty = try l.root();
        const s = l.src[ty];
        if (s.kind != .@"struct") return error.BadDump;
        try l.fields(T, s, out, true);
    }

    fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void {
        freshOf(T, out, l.gpa);
    }

    /// Whether the source's `ty` and `T` are of one kind, else the
    /// source's value passed over.
    fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool {
        if (l.same) return true;
        const want = comptime kindOf(Canon(T));
        const got = l.src[ty].kind;
        if (got == want) return true;
        // A field that came to hold a count and so many, or stopped.
        if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true;
        try l.skip(ty);
        return false;
    }

    fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I {
        if (l.same) {
            const info = @typeInfo(I).int;
            const W = @Int(info.signedness, intBytes(info.bits) * 8);
            // A number its own width holds: a u21's byte-wide word past it is no u21.
            return std.math.cast(I, try l.scalar(W)) orelse error.BadDump;
        }
        const n = intBytes(s.bits);
        const raw = try l.take(n);
        var wide: u128 = 0;
        for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8);
        if (s.signed and n > 0) {
            const shift: u7 = @intCast(128 - n * 8);
            const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift;
            return std.math.cast(I, signed) orelse error.Incompatible;
        }
        return std.math.cast(I, wide) orelse error.Incompatible;
    }

    /// `T` read from the source's type `ty` into `out`, which `fresh`
    /// has made ready.
    fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void {
        if (comptime isAtomic(T)) {
            const R = @FieldType(T, "raw");
            var raw: R = undefined;
            try l.fresh(R, &raw);
            try l.value(R, ty, &raw);
            out.* = .{ .raw = raw };
            return;
        }
        // A field this build compiles out (a void field): passed over,
        // said only when it held something.
        if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) {
            const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0);
            try l.skip(ty);
            if (held) l.note("{s}: not in this build", .{l.field});
            return;
        };
        if (!try l.kindMatches(T, ty)) return error.Incompatible;
        const s = l.src[ty];
        if (comptime isList(T)) {
            const E = @typeInfo(@FieldType(T, "items")).pointer.child;
            const got = try l.slice(E, s);
            out.* = .empty;
            out.items = got;
            out.capacity = got.len;
            return;
        }
        switch (comptime kindOf(T)) {
            .skip, .void => {},
            .bool => out.* = (try l.take(1))[0] != 0,
            .int => out.* = try l.readInt(T, s),
            .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible,
            .@"enum" => {
                const e = @typeInfo(T).@"enum";
                if (l.same) {
                    // A number one of its names has (`enumFrom`'s rule).
                    const tag = try l.readInt(e.tag_type, s);
                    out.* = if (e.mode == .nonexhaustive) @fromBackingInt(tag) else std.enums.fromInt(T, tag) orelse return error.BadDump;
                    return;
                }
                const n = try l.readInt(i128, s);
                const was = for (s.fields) |f| {
                    if (f.value == n) break f.name;
                } else null;
                if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) {
                    out.* = @field(T, field);
                    return;
                };
                if (e.mode == .nonexhaustive and was == null)
                    if (std.math.cast(e.tag_type, n)) |tag| {
                        out.* = @fromBackingInt(@intCast(tag));
                        return;
                    };
                l.note("{s}: no {s} here", .{ l.field, was orelse "such value" });
                return error.Incompatible;
            },
            .optional => {
                const C = @typeInfo(T).optional.child;
                if ((try l.take(1))[0] == 0) {
                    out.* = null;
                    return;
                }
                if (comptime kindOf(Canon(C)) == .skip) {
                    out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
                    return;
                }
                // A slice's or a pointer's null is its address: set to
                // an undefined payload, the optional itself is undefined,
                // and ReleaseSafe's optimizer read it as null (a pane's
                // `?[]u8` command one byte long, every field after it out
                // of step). Read through a local and set it from that.
                if (comptime @typeInfo(C) == .pointer) {
                    var payload: C = undefined;
                    try l.value(C, s.child, &payload);
                    out.* = payload;
                    return;
                }
                out.* = @as(C, undefined);
                try l.fresh(C, &out.*.?);
                l.value(C, s.child, &out.*.?) catch |err| {
                    out.* = null;
                    return err;
                };
            },
            .one => {
                const C = @typeInfo(T).pointer.child;
                if (try l.ref(C)) |again| {
                    out.* = @ptrCast(@alignCast(again.ptr));
                    return;
                }
                const one = try l.gpa.create(C);
                const at = l.made(std.mem.asBytes(one), .of(C), typeWord(C)) catch |err| {
                    l.gpa.destroy(one);
                    return err;
                };
                try l.fresh(C, one);
                l.value(C, s.child, one) catch |err| {
                    // Left half made: no later reference may find it.
                    l.shared.items[at].dead = true;
                    return err;
                };
                out.* = one;
            },
            .slice => {
                const E = @typeInfo(T).pointer.child;
                const got = try l.slice(E, s);
                if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
                out.* = got;
            },
            .array => {
                const E = @typeInfo(T).array.child;
                const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len;
                try l.elements(E, s.child, n, out);
            },
            .prefix => unreachable,
            .@"struct" => try l.fields(T, s, out, false),
            .@"union" => {
                const u = @typeInfo(T).@"union";
                const ordinal = try l.scalar(u16);
                if (ordinal >= s.fields.len) return error.BadDump;
                const was = s.fields[ordinal];
                inline for (u.field_names, u.field_types, 0..) |field, F, i| {
                    if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) {
                        out.* = @unionInit(T, field, undefined);
                        try l.fresh(F, &@field(out.*, field));
                        return l.value(F, was.ty, &@field(out.*, field));
                    }
                }
                try l.skip(was.ty);
                l.note("{s}: no {s} here", .{ l.field, was.name });
                return error.Incompatible;
            },
            .err, .error_union => unreachable,
            .custom => {
                const bytes = try l.take(try l.count());
                T.dumpRead(out, l.gpa, bytes) catch |err| {
                    if (err == error.OutOfMemory) return error.OutOfMemory;
                    l.note("{s}: {t}", .{ l.field, err });
                    return error.Incompatible;
                };
                if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
            },
            .bitset => {
                const bits = try l.bitCount();
                out.* = try .initEmpty(l.gpa, bits);
                l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| {
                    out.deinit(l.gpa);
                    return err;
                };
                const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
                if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize)));
            },
        }
    }

    /// A reference to a pointer or slice made before, or null for a
    /// new one (its length then read).
    fn ref(l: *Self, comptime E: type) DecodeError!?[]u8 {
        const n = try l.scalar(u32);
        if (n == 0) return null;
        if (n > l.shared.items.len) return error.BadDump;
        const got = l.shared.items[n - 1];
        if (got.dead) return error.Incompatible;
        if (got.of != typeWord(E)) return error.BadDump;
        return got.bytes;
    }

    fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E {
        if (try l.ref(E)) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))];
        const n = try l.count();
        if (n == 0) return &.{};
        if (n > l.bytes.len - l.at) return error.EndOfDump;
        const many = try l.gpa.alloc(E, n);
        const at = l.made(std.mem.sliceAsBytes(many), .of(E), typeWord(E)) catch |err| {
            l.gpa.free(many);
            return err;
        };
        l.elements(E, s.child, n, many) catch |err| {
            l.shared.items[at].dead = true;
            return err;
        };
        return many;
    }

    /// `n` elements of the source's type `ty` into `out` (an array or
    /// a slice), as many as it holds, the rest passed over.
    fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void {
        const keep: usize = @intCast(@min(n, out.len));
        const s = l.src[ty];
        // Bytes copied whole between builds when both sides agree on
        // them: integers and bools (an enum's numbers may not be the other's).
        const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and
            (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false;
        defer l.filled = keep;
        if (bulk) {
            if (n > l.bytes.len) return error.EndOfDump;
            @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E)));
            _ = try l.take(@intCast((n - keep) * @sizeOf(E)));
            return;
        }
        // An array of optional pointers (a session's panes): one that
        // cannot be read is left out, not the array.
        const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
        var failed = false;
        // Each element a byte at least: a damaged count starts no loop.
        if (n > l.bytes.len - l.at) return error.EndOfDump;
        for (0..try countOf(n)) |i| {
            if (i >= keep) {
                try l.skip(ty);
                continue;
            }
            try l.fresh(E, &out[i]);
            const before = l.mark();
            l.value(E, ty, &out[i]) catch |err| {
                if (err != error.Incompatible) return err;
                if (droppable) {
                    l.letGo(before);
                    out[i] = null;
                    l.dropped += 1;
                    l.note("{s}[{d}] left out", .{ l.field, i });
                } else failed = true;
            };
        }
        if (failed) return error.Incompatible;
    }

    fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void {
        const names = comptime dumpFields(T);
        const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
        const outer = l.field;
        defer l.field = outer;
        const dropped = l.dropped;
        // How far each array a length cuts was read: none yet (one read in
        // place holds what it held).
        var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0);
        if (l.same) {
            if (s.fields.len != names.len) return error.BadDump;
            inline for (names, 0..) |field, k| {
                l.field = field;
                try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
                if (comptime pairAt(T, field)) |i| held[i] = l.filled;
            }
            return holdTo(l, T, out, &held, dropped);
        }
        var found: std.StaticBitSet(@max(1, names.len)) = .empty;
        var failed = false;
        for (s.fields) |f| {
            const k: ?usize = inline for (names, 0..) |field, k| {
                if (std.mem.eql(u8, f.name, field)) break k;
            } else null;
            const at = k orelse {
                try l.skip(f.ty);
                continue;
            };
            found.set(at);
            inline for (names, 0..) |field, i| if (i == at) {
                l.field = field;
                const before = l.mark();
                if (l.oneField(T, field, f.ty, out, packed_struct, existing)) {
                    if (comptime pairAt(T, field)) |p| held[p] = l.filled;
                } else |err| {
                    if (err != error.Incompatible) return err;
                    // What the read made before it failed: nothing holds it.
                    l.letGo(before);
                    const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
                    if (comptime attr.default_value_ptr) |dp| {
                        @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
                        l.noteField("its kind changed; its default taken", @typeName(T), field);
                    } else if (existing) {
                        l.noteField("its kind changed; left as it was", @typeName(T), field);
                    } else failed = true;
                }
            };
        }
        // A field the writer did not have: its default (`fresh`), or
        // the value cannot be made.
        inline for (names, 0..) |field, i| if (!found.isSet(i)) {
            const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
            if (comptime attr.default_value_ptr == null) {
                if (!existing) {
                    l.noteField("not in the dump", @typeName(T), field);
                    failed = true;
                }
            }
        };
        if (failed) return error.Incompatible;
        return holdTo(l, T, out, &held, dropped);
    }

    fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
        const F = @FieldType(T, field);
        const gpa = l.gpa;
        defer l.gpa = gpa;
        if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
            l.gpa = a;
        };
        if (comptime cutArray(T, field)) {
            return l.value(F, ty, &@field(out, field));
        }
        // A struct held in place in one read as it stands (the root's):
        // what it does not hold stays as it is too.
        if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) {
            if (!try l.kindMatches(F, ty)) return error.Incompatible;
            return l.fields(F, l.src[ty], &@field(out, field), true);
        };
        if (packed_struct) {
            var copy: F = undefined;
            try l.fresh(F, &copy);
            try l.value(F, ty, &copy);
            @field(out, field) = copy;
            return;
        }
        try l.fresh(F, &@field(out, field));
        try l.value(F, ty, &@field(out, field));
    }

    /// The source's value of type `ty` passed over.
    fn skip(l: *Self, ty: u32) DecodeError!void {
        // The dump's table says what its types hold: a damaged one can make
        // a struct its own field, a recursion as deep as the stack.
        if (l.depth == max_depth) return error.BadDump;
        l.depth += 1;
        defer l.depth -= 1;
        const s = l.src[ty];
        switch (s.kind) {
            .skip, .void => {},
            .bool => _ = try l.take(1),
            .int, .@"enum" => _ = try l.take(intBytes(s.bits)),
            .float => _ = try l.take(s.bits / 8),
            .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child),
            .one => if (try l.scalar(u32) == 0) {
                _ = try l.made(&.{}, .@"1", 0);
                l.shared.items[l.shared.items.len - 1].dead = true;
                try l.skip(s.child);
            },
            .slice => if (try l.scalar(u32) == 0) {
                const n = try l.scalar(u64);
                if (n > 0) {
                    _ = try l.made(&.{}, .@"1", 0);
                    l.shared.items[l.shared.items.len - 1].dead = true;
                }
                try l.skipMany(s.child, n);
            },
            .prefix => try l.skipMany(s.child, try l.scalar(u64)),
            .array => try l.skipMany(s.child, s.len),
            .@"struct" => for (s.fields) |f| try l.skip(f.ty),
            .@"union" => {
                const ordinal = try l.scalar(u16);
                if (ordinal >= s.fields.len) return error.BadDump;
                try l.skip(s.fields[ordinal].ty);
            },
            .err => _ = try l.name(),
            .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else {
                _ = try l.name();
            },
            .custom => _ = try l.take(try l.count()),
            .bitset => _ = try l.take((try l.bitCount() + 63) / 64 * 8),
        }
    }

    fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void {
        const s = l.src[ty];
        if (s.kind == .int or s.kind == .bool) {
            const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits);
            if (n > l.bytes.len) return error.EndOfDump;
            _ = try l.take(@intCast(n * size));
            return;
        }
        if (n > l.bytes.len - l.at) return error.EndOfDump;
        for (0..try countOf(n)) |_| try l.skip(ty);
    }
};

/// A bitset a load made, freed as a `dumpRead`'s value is (`customs`) when
/// the load fails or what held it is let go: its words are no `made` slice.
fn Bits(comptime T: type) type {
    return struct {
        fn free(b: *T, gpa: std.mem.Allocator) void {
            b.deinit(gpa);
        }
    };
}

/// `out` as a new `T` is before a load reads its fields: each field's
/// default, an allocator `gpa`.
fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void {
    if (comptime @typeInfo(T) != .@"struct" or isList(T) or isAtomic(T) or isBitset(T) or kindOf(T) == .custom or kindOf(T) == .skip) return;
    const s = @typeInfo(T).@"struct";
    inline for (s.field_names, s.field_types, s.field_attrs) |field, F, attr| {
        if (attr.@"comptime") continue;
        if (comptime attr.default_value_ptr) |dp| {
            @field(out, field) = @as(*const F, @ptrCast(@alignCast(dp))).*;
        } else if (comptime F == std.mem.Allocator) {
            @field(out, field) = gpa;
        } else if (comptime !walkedField(T, field)) {
            @compileError("walk: " ++ @typeName(T) ++ "." ++ field ++ " has no default to load to");
        }
    }
}

fn walkedField(comptime T: type, comptime field: []const u8) bool {
    inline for (comptime dumpFields(T)) |n| if (comptime std.mem.eql(u8, n, field)) return true;
    return false;
}

/// A value `save` made, `gpa`'s; what was let go, or why it was refused, is
/// said in `notes` when it is given.
pub fn load(comptime T: type, gpa: std.mem.Allocator, bytes: []const u8, notes: ?*std.ArrayList(u8)) DecodeError!T {
    var l = try Load(&.{T}).init(gpa, bytes);
    defer l.deinit();
    defer if (notes) |n| n.appendSlice(gpa, l.notes.items) catch {};
    errdefer l.rollback();
    return l.get(T);
}

// ---- a dump as a database: the same walk, by name, into xitdb's maps ----
//
// A dump (Db.zig) is a xitdb database in memory, its bytes one value of the
// state file, written by the walk by name: a struct is a map whose keys are
// its fields' names (`putKey`: a reader goes through them by name, never by
// a hash of its own), a union a map of its one field, a slice, an array or
// a list of records a list, of plain numbers one bytes value (its format
// tag the numbers' kind and width), an enum the bytes of its name, a number
// a uint or an int (a wider one its bytes), an optional an absent key (an
// explicit none where the field's default is not null), a type with
// `dumpWrite` its bytes, and a `.blob`'s text of `blob_min` bytes and up
// its BLAKE3 hash (tag "b3"): the text is kept once beside the dump
// (`Blob`). A pointer or a slice met again is the first one's value again:
// what two fields share is shared again.
//
// Another build reads it by name: a field the dump has not takes its
// default, a key this build has not is passed over, a value of another kind
// takes its default and is said (`notes`); with no default the value it is
// part of is refused, and an element of an array of optional pointers (a
// session's panes) is then left out, nothing above it.

pub const Mem = xitdb.Database(.memory, u256);

/// A text a dump keeps beside it, once: its BLAKE3 hash and its bytes (the
/// session's, while the dump is made).
pub const Blob = struct { hash: [32]u8, bytes: []const u8 };

/// A field's key: its name's word, unique within its struct (a reader
/// matches names, so another build's words need not be these).
fn nameKey(comptime name: []const u8) u256 {
    return comptime std.hash.Wyhash.hash(0, name);
}

/// Whether a run of `E` is one bytes value: plain numbers.
fn numbers(comptime E: type) bool {
    return switch (@typeInfo(E)) {
        .int => |i| @sizeOf(E) * 8 == i.bits and @sizeOf(E) <= 8,
        .bool => true,
        .float => |f| f.bits == 32 or f.bits == 64,
        else => false,
    };
}

/// A run of numbers' format tag: their kind and byte width ("u4", "i8", "b1").
fn numbersTag(comptime E: type) [2]u8 {
    const kind: u8 = switch (@typeInfo(E)) {
        .int => |i| if (i.signedness == .signed) 'i' else 'u',
        .bool => 'b',
        .float => 'f',
        else => unreachable,
    };
    return .{ kind, '0' + @sizeOf(E) };
}

const blob_tag = "b3".*;
const wide_tag = "w8".*;
const custom_tag = "cu".*;
const bitset_tag = "bs".*;

/// The most bytes a value read at the cursor `c` can be: its database's. A
/// damaged length (an image's, cut or flipped) sizes no allocation past them.
pub fn most(c: anytype) usize {
    return std.math.cast(usize, c.db.core.length() catch 0) orelse std.math.maxInt(usize);
}

fn typeWord(comptime T: type) u64 {
    return comptime std.hash.Wyhash.hash(0, @typeName(T));
}

/// Writes values into a database in memory, by name (see above).
pub const Put = struct {
    gpa: std.mem.Allocator,
    /// Each pointer and slice written, by address, length and type, and
    /// where its value is: met again, that value is written again.
    memo: std.AutoHashMapUnmanaged(Key, xitdb.Slot) = .empty,
    /// The blobs met, each once.
    blobs: std.ArrayListUnmanaged(Blob) = .empty,
    in_blob: bool = false,

    const Key = struct { addr: usize, len: usize, ty: u64 };
    const Cursor = Mem.Cursor(.read_write);

    pub fn deinit(w: *Put) void {
        w.memo.deinit(w.gpa);
        w.blobs.deinit(w.gpa);
    }

    /// `v` written as `name`'s value in `map` (a dump's roots).
    pub fn member(w: *Put, map: Mem.HashMap(.read_write), comptime name: []const u8, comptime T: type, v: *const T) anyerror!void {
        try map.putKey(comptime nameKey(name), .{ .bytes = name });
        var at = try map.putCursor(comptime nameKey(name));
        _ = try w.value(T, v, &at);
    }

    /// `v` written at `c`; where its value is.
    pub fn value(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot {
        if (comptime isAtomic(T)) return w.value(@FieldType(T, "raw"), &v.raw, c);
        if (comptime isList(T)) return w.many(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, c, true);
        switch (comptime kindOf(T)) {
            .skip, .void => try c.write(.{ .slot = null }),
            .bool => try c.write(.{ .uint = @intFromBool(v.*) }),
            .int => if (@typeInfo(T).int.bits <= 64) {
                try c.write(if (@typeInfo(T).int.signedness == .signed) .{ .int = v.* } else .{ .uint = v.* });
            } else {
                const wide: i128 = @intCast(v.*);
                try c.write(.{ .bytes_object = .{ .value = std.mem.asBytes(&wide), .format_tag = wide_tag } });
            },
            .float => try c.write(.{ .float = v.* }),
            .@"enum" => if (std.enums.tagName(T, v.*)) |name| {
                try c.write(.{ .bytes = name });
            } else try c.write(.{ .int = @intCast(@backingInt(v.*)) }),
            .optional => {
                const C = @typeInfo(T).optional.child;
                if (v.*) |*payload| {
                    // An allocator, say, is no state: there or not, which a
                    // load answers with its own.
                    if (comptime kindOf(Canon(C)) == .skip) try c.write(.{ .uint = 1 }) else return w.value(C, payload, c);
                } else try c.write(.{ .slot = null });
            },
            .one => {
                const C = @typeInfo(T).pointer.child;
                const key: Key = .{ .addr = @intFromPtr(v.*), .len = @max(1, @sizeOf(C)), .ty = typeWord(T) };
                if (w.memo.get(key)) |slot| {
                    try c.write(.{ .slot = slot });
                    return slot;
                }
                const slot = try w.value(C, v.*, c);
                try w.memo.put(w.gpa, key, slot);
                return slot;
            },
            .slice => return w.many(@typeInfo(T).pointer.child, v.*, c, true),
            .array => return w.many(@typeInfo(T).array.child, v, c, false),
            .prefix => unreachable,
            .@"struct" => return w.fields(T, v, c),
            .@"union" => {
                const map = try Mem.HashMap(.read_write).init(c.*);
                switch (v.*) {
                    inline else => |*payload, tag| {
                        const name = @tagName(tag);
                        try map.putKey(comptime nameKey(name), .{ .bytes = name });
                        var at = try map.putCursor(comptime nameKey(name));
                        _ = try w.value(@TypeOf(payload.*), payload, &at);
                    },
                }
                return map.slot();
            },
            // No type a dump walks has them.
            .err, .error_union => unreachable,
            .custom => {
                var buf: [4096]u8 = undefined;
                var out = try c.writer(&buf);
                try T.dumpWrite(v, w.gpa, &out.interface);
                out.format_tag = custom_tag;
                try out.finish();
            },
            .bitset => {
                const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
                var buf: [64]u8 = undefined;
                var out = try c.writer(&buf);
                try out.interface.writeAll(std.mem.asBytes(&@as(u64, v.bit_length)));
                if (words > 0) try out.interface.writeAll(std.mem.sliceAsBytes(v.masks[0..words]));
                out.format_tag = bitset_tag;
                try out.finish();
            },
        }
        return c.slot();
    }

    /// A run of `E`: numbers as one bytes value (a blob's text by its
    /// hash), records as a list; a slice met again (`shared`) its first
    /// value.
    fn many(w: *Put, comptime E: type, items: []const E, c: *Cursor, comptime shared: bool) anyerror!xitdb.Slot {
        const key: Key = .{ .addr = @intFromPtr(items.ptr), .len = items.len, .ty = typeWord([]const E) };
        if (shared and items.len > 0) if (w.memo.get(key)) |slot| {
            try c.write(.{ .slot = slot });
            return slot;
        };
        const slot = if (comptime numbers(E)) slot: {
            const bytes = std.mem.sliceAsBytes(items);
            if (E == u8 and w.in_blob and bytes.len >= blob_min) {
                var sum: [32]u8 = undefined;
                std.crypto.hash.Blake3.hash(bytes, &sum, .{});
                const known = for (w.blobs.items) |b| {
                    if (std.mem.eql(u8, &b.hash, &sum)) break true;
                } else false;
                if (!known) try w.blobs.append(w.gpa, .{ .hash = sum, .bytes = bytes });
                try c.write(.{ .bytes_object = .{ .value = &sum, .format_tag = blob_tag } });
            } else try c.write(.{ .bytes_object = .{ .value = bytes, .format_tag = numbersTag(E) } });
            break :slot try c.slot();
        } else slot: {
            const list = try Mem.ArrayList(.read_write).init(c.*);
            for (items) |*e| {
                var at = try list.appendCursor();
                _ = try w.value(E, e, &at);
            }
            break :slot try list.slot();
        };
        if (shared and items.len > 0) try w.memo.put(w.gpa, key, slot);
        return slot;
    }

    fn fields(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot {
        const map = try Mem.HashMap(.read_write).init(c.*);
        const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
        inline for (comptime dumpFields(T)) |name| {
            const F = @FieldType(T, name);
            if (comptime kindOf(Canon(F)) != .void) put: {
                // Null where the field's default is: no key at all.
                if (comptime @typeInfo(F) == .optional and defaultIsNull(T, name)) if (@field(v, name) == null) break :put;
                const was = w.in_blob;
                w.in_blob = was or comptime blob(T, name);
                defer w.in_blob = was;
                try map.putKey(comptime nameKey(name), .{ .bytes = name });
                var at = try map.putCursor(comptime nameKey(name));
                if (comptime cutArray(T, name)) {
                    const all = &@field(v, name);
                    _ = try w.many(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))], &at, false);
                } else if (comptime packed_struct) {
                    const copy: F = @field(v, name);
                    _ = try w.value(F, &copy, &at);
                } else _ = try w.value(F, &@field(v, name), &at);
            }
        }
        return map.slot();
    }
};

fn defaultIsNull(comptime T: type, comptime name: []const u8) bool {
    const F = @FieldType(T, name);
    const attr = @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, name).?];
    const dp = attr.default_value_ptr orelse return false;
    return @as(*const F, @ptrCast(@alignCast(dp))).* == null;
}

/// Reads values a `Put` wrote, by name, as another build may have written
/// them (see above).
pub const Get = struct {
    /// Where what is read is made (a `replica.alloc` field's own allocator
    /// while it is read).
    gpa: std.mem.Allocator,
    /// The reader's own lists'.
    own: std.mem.Allocator,
    /// The texts its blobs' hashes name (Db.zig's `blobs`), by hash.
    blobs: ?Mem.HashMap(.read_only) = null,
    /// Each pointer and slice made so far: what a value met again is, and
    /// what `rollback` frees.
    made: std.ArrayList(Made) = .empty,
    /// Where each value made is: met again, the same one.
    memo: std.AutoHashMapUnmanaged(u128, usize) = .empty,
    /// What a type's `dumpRead` made, freed by its `dumpFree` too.
    customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty,
    /// What was let go, for the person whose session it is.
    notes: std.ArrayList(u8) = .empty,
    /// The field being read, for a note.
    field: []const u8 = "",
    allocs: Allocators = .{},
    /// How many elements the last array read holds (`pastHeld`).
    filled: usize = 0,
    /// How many things (a session's panes) it left out (`holdTo`).
    dropped: usize = 0,

    const Cursor = Mem.Cursor(.read_only);
    pub const Error = error{ BadDump, Incompatible, OutOfMemory };

    pub fn init(gpa: std.mem.Allocator) Get {
        return .{ .gpa = gpa, .own = gpa };
    }

    pub fn deinit(l: *Get) void {
        l.made.deinit(l.own);
        l.memo.deinit(l.own);
        l.customs.deinit(l.own);
        l.notes.deinit(l.own);
    }

    /// Everything read so far freed: a load that fails leaves nothing.
    /// What it was read into must not be used after (nor freed).
    pub fn rollback(l: *Get) void {
        for (l.customs.items) |c| c.free(c.ptr, c.gpa);
        for (l.made.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
        l.customs.clearRetainingCapacity();
        l.made.clearRetainingCapacity();
        l.memo.clearRetainingCapacity();
    }

    fn mark(l: *const Get) Mark {
        return .{ .made = l.made.items.len, .customs = l.customs.items.len };
    }

    /// Load's `letGo`: what was made since `at`, freed, nothing holding it.
    fn letGo(l: *Get, at: Mark) void {
        for (l.customs.items[at.customs..]) |c| c.free(c.ptr, c.gpa);
        l.customs.shrinkRetainingCapacity(at.customs);
        for (l.made.items[at.made..]) |*m| {
            if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
            m.bytes = &.{};
            m.dead = true;
        }
    }

    pub fn note(l: *Get, comptime fmt: []const u8, args: anytype) void {
        if (l.notes.items.len > 4096) return;
        l.notes.print(l.own, fmt ++ "\n", args) catch {};
    }

    /// A note on a type's field, its names given at run time (Load's).
    fn noteField(l: *Get, comptime what: []const u8, type_name: []const u8, field: []const u8) void {
        l.note("{s}.{s}: " ++ what, .{ type_name, field });
    }

    /// The value at `c`, made: what it points at is `gpa`'s.
    pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T {
        // As `Loader.get`: a value that fails leaves nothing made.
        const at = l.mark();
        errdefer l.letGo(at);
        var out: T = undefined;
        try l.fresh(T, &out);
        try l.value(T, c, &out);
        return out;
    }

    /// The struct at `c` read into `out` as it stands: a field the dump
    /// holds is replaced (what it held is not freed), every other one is
    /// left as it is, and one another build cannot give is left too, and
    /// noted.
    pub fn into(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void {
        try l.fields(T, c, out, true);
    }

    /// Where the value of `name` is in the map at `c` (a dump's roots), by
    /// its name; null when it is not there.
    pub fn member(c: Cursor, name: []const u8) Error!?Cursor {
        const map = Mem.HashMap(.read_only).init(c) catch return error.BadDump;
        var it = map.iterator() catch return error.BadDump;
        while (it.next() catch return error.BadDump) |kv_at| {
            const kv = kv_at.readKeyValuePair() catch return error.BadDump;
            var buf: [64]u8 = undefined;
            const got = kv.key_cursor.readBytes(&buf) catch continue;
            if (std.mem.eql(u8, got, name)) return kv.value_cursor;
        }
        return null;
    }

    fn fresh(l: *Get, comptime T: type, out: *T) Error!void {
        freshOf(T, out, l.gpa);
    }

    fn slotWord(slot: xitdb.Slot) u128 {
        return @as(u72, @bitCast(slot));
    }

    fn slotOf(c: Cursor) Error!xitdb.Slot {
        return c.slot() catch error.BadDump;
    }

    /// Whether the value at `slot` has a place of its own (an inline number
    /// or a short text is its slot alone: no identity to share).
    fn placed(slot: xitdb.Slot) bool {
        return switch (slot.tag) {
            .none, .uint, .int, .float, .short_bytes => false,
            else => true,
        };
    }

    /// An allocation made for the value at `slot`, kept: what a value met
    /// again is, and what `rollback` frees.
    fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot, of: u64) Error!usize {
        try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of });
        const at = l.made.items.len - 1;
        // Not kept after all: the caller frees it.
        if (placed(slot)) l.memo.put(l.own, slotWord(slot), at) catch |err| {
            _ = l.made.pop();
            return err;
        };
        return at;
    }

    /// The value made before for the same place, when there was one.
    fn again(l: *Get, slot: xitdb.Slot, comptime E: type) Error!?[]u8 {
        if (!placed(slot)) return null;
        const at = l.memo.get(slotWord(slot)) orelse return null;
        // Made, then let go of by the reader's caller (a dump's mounts).
        if (at >= l.made.items.len) return null;
        const m = l.made.items[at];
        if (m.dead) return error.Incompatible;
        if (m.of != typeWord(E)) return error.BadDump;
        return m.bytes;
    }

    /// `T` read from `c` into `out`, which `fresh` has made ready.
    fn value(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void {
        if (comptime isAtomic(T)) {
            const R = @FieldType(T, "raw");
            var raw: R = undefined;
            try l.fresh(R, &raw);
            try l.value(R, c, &raw);
            out.* = .{ .raw = raw };
            return;
        }
        const slot = try slotOf(c);
        if (comptime isList(T)) {
            const got = try l.slice(@typeInfo(@FieldType(T, "items")).pointer.child, c, slot);
            out.* = .empty;
            out.items = got;
            out.capacity = got.len;
            return;
        }
        switch (comptime kindOf(T)) {
            .skip, .void => {},
            .bool => out.* = switch (slot.tag) {
                .uint => slot.value != 0,
                else => return error.Incompatible,
            },
            .int => out.* = try l.int(T, c, slot),
            .float => out.* = switch (slot.tag) {
                .float => @floatCast(@as(f64, @bitCast(slot.value))),
                else => return error.Incompatible,
            },
            .@"enum" => {
                const e = @typeInfo(T).@"enum";
                switch (slot.tag) {
                    .bytes, .short_bytes => {
                        var buf: [256]u8 = undefined;
                        const name = c.readBytes(&buf) catch return error.Incompatible;
                        inline for (e.field_names) |field| if (std.mem.eql(u8, name, field)) {
                            out.* = @field(T, field);
                            return;
                        };
                        l.note("{s}: no {s} here", .{ l.field, name });
                        return error.Incompatible;
                    },
                    .int, .uint => if (e.mode == .nonexhaustive) {
                        const n: i64 = @bitCast(slot.value);
                        out.* = @fromBackingInt(@intCast(std.math.cast(e.tag_type, n) orelse return error.Incompatible));
                    } else return error.Incompatible,
                    else => return error.Incompatible,
                }
            },
            .optional => {
                const C = @typeInfo(T).optional.child;
                if (slot.tag == .none) {
                    out.* = null;
                    return;
                }
                if (comptime kindOf(Canon(C)) == .skip) {
                    out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
                    return;
                }
                // Through a local, as the byte loader does: a pointer's
                // null is its address.
                if (comptime @typeInfo(C) == .pointer) {
                    var payload: C = undefined;
                    try l.value(C, c, &payload);
                    out.* = payload;
                    return;
                }
                out.* = @as(C, undefined);
                try l.fresh(C, &out.*.?);
                l.value(C, c, &out.*.?) catch |err| {
                    out.* = null;
                    return err;
                };
            },
            .one => {
                const C = @typeInfo(T).pointer.child;
                if (try l.again(slot, C)) |bytes| {
                    out.* = @ptrCast(@alignCast(bytes.ptr));
                    return;
                }
                const one = try l.gpa.create(C);
                const at = l.keep(std.mem.asBytes(one), .of(C), slot, typeWord(C)) catch |err| {
                    l.gpa.destroy(one);
                    return err;
                };
                try l.fresh(C, one);
                l.value(C, c, one) catch |err| {
                    // Left half made: no later value may be it.
                    l.made.items[at].dead = true;
                    return err;
                };
                out.* = one;
            },
            .slice => {
                if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
                out.* = try l.slice(@typeInfo(T).pointer.child, c, slot);
            },
            .array => try l.elements(@typeInfo(T).array.child, c, slot, out),
            .prefix => unreachable,
            .@"struct" => try l.fields(T, c, out, false),
            .@"union" => {
                const u = @typeInfo(T).@"union";
                const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
                var it = map.iterator() catch return error.BadDump;
                const kv_at = (it.next() catch return error.BadDump) orelse return error.Incompatible;
                const kv = kv_at.readKeyValuePair() catch return error.BadDump;
                var buf: [256]u8 = undefined;
                const name = kv.key_cursor.readBytes(&buf) catch return error.Incompatible;
                inline for (u.field_names, u.field_types) |field, F| if (std.mem.eql(u8, name, field)) {
                    out.* = @unionInit(T, field, undefined);
                    try l.fresh(F, &@field(out.*, field));
                    return l.value(F, kv.value_cursor, &@field(out.*, field));
                };
                l.note("{s}: no {s} here", .{ l.field, name });
                return error.Incompatible;
            },
            .err, .error_union => unreachable,
            .custom => {
                const got = c.readBytesObjectAlloc(l.own, most(c)) catch return error.Incompatible;
                defer l.own.free(got.value);
                T.dumpRead(out, l.gpa, got.value) catch |err| {
                    if (err == error.OutOfMemory) return error.OutOfMemory;
                    l.note("{s}: {t}", .{ l.field, err });
                    return error.Incompatible;
                };
                if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
            },
            .bitset => {
                const got = c.readBytesObjectAlloc(l.own, most(c)) catch return error.Incompatible;
                defer l.own.free(got.value);
                if (got.value.len < 8) return error.BadDump;
                const bits = countOf(std.mem.bytesToValue(u64, got.value[0..8])) catch return error.BadDump;
                if (bits / 64 > got.value.len / 8) return error.BadDump;
                const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
                if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump;
                out.* = try .initEmpty(l.gpa, bits);
                l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| {
                    out.deinit(l.gpa);
                    return err;
                };
                if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]);
            },
        }
    }

    fn int(l: *Get, comptime I: type, c: Cursor, slot: xitdb.Slot) Error!I {
        _ = l;
        return switch (slot.tag) {
            .uint => std.math.cast(I, slot.value) orelse error.Incompatible,
            .int => std.math.cast(I, @as(i64, @bitCast(slot.value))) orelse error.Incompatible,
            .bytes, .short_bytes => wide: {
                var buf: [16]u8 = undefined;
                const got = c.readBytesObject(&buf) catch return error.Incompatible;
                if (got.value.len != 16 or !std.mem.eql(u8, &(got.format_tag orelse return error.Incompatible), &wide_tag)) return error.Incompatible;
                break :wide std.math.cast(I, std.mem.bytesToValue(i128, got.value[0..16])) orelse error.Incompatible;
            },
            else => error.Incompatible,
        };
    }

    /// Numbers' `bytes` (format `tag`) as `E`s into `out`, as many as fit:
    /// another width of the same kind (another build's) converted one by
    /// one. How many the bytes hold.
    fn convert(comptime E: type, bytes: []const u8, tag: [2]u8, out: []E) Error!usize {
        const width: usize = if (tag[1] >= '1' and tag[1] <= '8') tag[1] - '0' else return error.BadDump;
        if (bytes.len % width != 0) return error.BadDump;
        const n = bytes.len / width;
        const fits = @min(n, out.len);
        if (std.mem.eql(u8, &tag, &numbersTag(E))) {
            @memcpy(std.mem.sliceAsBytes(out[0..fits]), bytes[0 .. fits * width]);
            return n;
        }
        if (tag[0] != numbersTag(E)[0]) return error.Incompatible;
        for (out[0..fits], 0..) |*e, i| {
            const raw = bytes[i * width ..][0..width];
            e.* = switch (@typeInfo(E)) {
                .int => |info| if (info.signedness == .signed) cast: {
                    var wide: i64 = 0;
                    @memcpy(std.mem.asBytes(&wide)[0..width], raw);
                    if (width < 8) {
                        const shift: u6 = @intCast(64 - width * 8);
                        wide = (wide << shift) >> shift;
                    }
                    break :cast std.math.cast(E, wide) orelse return error.Incompatible;
                } else cast: {
                    var wide: u64 = 0;
                    @memcpy(std.mem.asBytes(&wide)[0..width], raw);
                    break :cast std.math.cast(E, wide) orelse return error.Incompatible;
                },
                .float => if (width == 8) @floatCast(std.mem.bytesToValue(f64, raw[0..8])) else if (width == 4) @floatCast(std.mem.bytesToValue(f32, raw[0..4])) else return error.Incompatible,
                .bool => raw[0] != 0,
                else => unreachable,
            };
        }
        return n;
    }

    /// The numbers' bytes at `c` and their format tag, `alloc`'s.
    fn numbersAt(c: Cursor, alloc: std.mem.Allocator) Error!struct { bytes: []u8, tag: [2]u8 } {
        const got = c.readBytesObjectAlloc(alloc, most(c)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.Incompatible;
        const bytes: []u8 = @constCast(got.value);
        const tag = got.format_tag orelse {
            alloc.free(bytes);
            return error.Incompatible;
        };
        return .{ .bytes = bytes, .tag = tag };
    }

    /// A slice of `E` at `c`: numbers' bytes, a blob's text by its hash, or
    /// a list; one met again is the same.
    fn slice(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot) Error![]E {
        if (try l.again(slot, E)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))];
        if (comptime numbers(E)) {
            switch (slot.tag) {
                .bytes, .short_bytes => {},
                else => return error.Incompatible,
            }
            if (E == u8) if (try l.blob(c, slot)) |text| return text;
            // A text, as it is written: its bytes are the slice.
            if (E == u8) {
                const got = try numbersAt(c, l.gpa);
                if (!std.mem.eql(u8, &got.tag, &numbersTag(u8))) {
                    l.gpa.free(got.bytes);
                    return error.Incompatible;
                }
                if (got.bytes.len == 0) {
                    l.gpa.free(got.bytes);
                    return &.{};
                }
                _ = l.keep(got.bytes, .@"1", slot, typeWord(u8)) catch |err| {
                    l.gpa.free(got.bytes);
                    return err;
                };
                return got.bytes;
            }
            const got = try numbersAt(c, l.own);
            defer l.own.free(got.bytes);
            const width: usize = if (got.tag[1] >= '1' and got.tag[1] <= '8') got.tag[1] - '0' else return error.BadDump;
            const n = got.bytes.len / width;
            if (n == 0) return &.{};
            const many = try l.gpa.alloc(E, n);
            const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| {
                l.gpa.free(many);
                return err;
            };
            _ = convert(E, got.bytes, got.tag, many) catch |err| {
                l.made.items[at].dead = true;
                return err;
            };
            return many;
        }
        const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
        const n = countOf(list.count() catch return error.BadDump) catch return error.BadDump;
        if (n == 0) return &.{};
        // No more than the image's bytes hold slots for: a damaged count
        // sizes nothing.
        if (n > (c.db.core.length() catch return error.BadDump) / (@bitSizeOf(xitdb.Slot) / 8)) return error.BadDump;
        const many = try l.gpa.alloc(E, n);
        const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| {
            l.gpa.free(many);
            return err;
        };
        l.listInto(E, list, many) catch |err| {
            l.made.items[at].dead = true;
            return err;
        };
        // A damaged count past the elements the list holds: the rest would
        // be undefined (a restored image's 256 rows of 0xAA).
        if (l.filled < n) {
            l.made.items[at].dead = true;
            return error.BadDump;
        }
        return many;
    }

    /// A blob's text, when `c` holds a blob's hash: made in `gpa`'s.
    fn blob(l: *Get, c: Cursor, slot: xitdb.Slot) Error!?[]u8 {
        var buf: [32]u8 = undefined;
        const got = c.readBytesObject(&buf) catch return null;
        const tag = got.format_tag orelse return null;
        if (!std.mem.eql(u8, &tag, &blob_tag) or got.value.len != 32) return null;
        const texts = l.blobs orelse return error.BadDump;
        const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump;
        const text = at.readBytesAlloc(l.gpa, most(at)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump;
        const bytes: []u8 = @constCast(text);
        _ = l.keep(bytes, .@"1", slot, typeWord(u8)) catch |err| {
            l.gpa.free(bytes);
            return err;
        };
        return bytes;
    }

    /// An array of `E` at `c`: as many as it holds, the rest as they are.
    fn elements(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot, out: []E) Error!void {
        if (comptime numbers(E)) {
            switch (slot.tag) {
                .bytes, .short_bytes => {},
                else => return error.Incompatible,
            }
            const got = try numbersAt(c, l.own);
            defer l.own.free(got.bytes);
            l.filled = @min(out.len, try convert(E, got.bytes, got.tag, out));
            return;
        }
        const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
        try l.listInto(E, list, out);
    }

    /// The list's elements into `out`, as many as fit (`filled`); an element
    /// of an array of optional pointers (a session's panes) that cannot be
    /// read is left out, not the array.
    fn listInto(l: *Get, comptime E: type, list: Mem.ArrayList(.read_only), out: []E) Error!void {
        const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
        var failed = false;
        var it = list.iterator() catch return error.BadDump;
        var i: usize = 0;
        defer l.filled = i;
        while (it.next() catch return error.BadDump) |at| : (i += 1) {
            if (i >= out.len) break;
            try l.fresh(E, &out[i]);
            const before = l.mark();
            l.value(E, at, &out[i]) catch |err| {
                if (err != error.Incompatible) return err;
                if (droppable) {
                    l.letGo(before);
                    out[i] = null;
                    l.dropped += 1;
                    l.note("{s}[{d}] left out", .{ l.field, i });
                } else failed = true;
            };
        }
        if (failed) return error.Incompatible;
    }

    fn fields(l: *Get, comptime T: type, c: Cursor, out: *T, existing: bool) Error!void {
        const names = comptime dumpFields(T);
        const outer = l.field;
        defer l.field = outer;
        const dropped = l.dropped;
        const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
        var found: std.StaticBitSet(@max(1, names.len)) = .empty;
        var failed = false;
        // How far each array a length cuts was read (Load's `fields`).
        var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0);
        var it = map.iterator() catch return error.BadDump;
        while (it.next() catch return error.BadDump) |kv_at| {
            const kv = kv_at.readKeyValuePair() catch return error.BadDump;
            var buf: [256]u8 = undefined;
            // A key that is no field's name of this build: passed over.
            const name = kv.key_cursor.readBytes(&buf) catch continue;
            const k: ?usize = inline for (names, 0..) |field, k| {
                if (std.mem.eql(u8, name, field)) break k;
            } else null;
            const at = k orelse continue;
            found.set(at);
            inline for (names, 0..) |field, i| if (i == at) {
                l.field = field;
                const before = l.mark();
                if (l.oneField(T, field, kv.value_cursor, out, existing)) {
                    if (comptime pairAt(T, field)) |p| held[p] = l.filled;
                } else |err| {
                    if (err != error.Incompatible) return err;
                    // What the read made before it failed: nothing holds it.
                    l.letGo(before);
                    const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
                    if (comptime attr.default_value_ptr) |dp| {
                        @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
                        l.noteField("its kind changed; its default taken", @typeName(T), field);
                    } else if (existing) {
                        l.noteField("its kind changed; left as it was", @typeName(T), field);
                    } else failed = true;
                }
            };
        }
        // A field the writer did not have (or held null at a null default):
        // its default (`fresh`), or the value cannot be made.
        inline for (names, 0..) |field, i| if (!found.isSet(i)) {
            const F = @FieldType(T, field);
            const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
            if (comptime attr.default_value_ptr == null and kindOf(Canon(F)) != .void) {
                if (!existing) {
                    l.noteField("not in the dump", @typeName(T), field);
                    failed = true;
                }
            } else if (comptime @typeInfo(F) == .optional and defaultIsNull(T, field)) if (existing) {
                // A null left out: null here too.
                @field(out, field) = null;
            };
        };
        if (failed) return error.Incompatible;
        return holdTo(l, T, out, &held, dropped);
    }

    fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void {
        const F = @FieldType(T, field);
        const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
        const gpa = l.gpa;
        defer l.gpa = gpa;
        if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
            l.gpa = a;
        };
        // A field this build compiles out (a void field): passed over,
        // said when it held something.
        if (comptime kindOf(Canon(F)) == .void) {
            if ((try slotOf(c)).tag != .none) l.note("{s}: not in this build", .{l.field});
            return;
        }
        if (comptime cutArray(T, field)) {
            const slot = try slotOf(c);
            return l.elements(@typeInfo(F).array.child, c, slot, &@field(out, field));
        }
        // A struct held in place in one read as it stands (the root's):
        // what it does not hold stays as it is too.
        if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) {
            return l.fields(F, c, &@field(out, field), true);
        };
        if (packed_struct) {
            var copy: F = undefined;
            try l.fresh(F, &copy);
            try l.value(F, c, &copy);
            @field(out, field) = copy;
            return;
        }
        try l.fresh(F, &@field(out, field));
        try l.value(F, c, &@field(out, field));
    }
};

test "a value comes back from its bytes" {
    const E = union(enum) { key: struct { cp: u21, text: []const u8 }, tick, failed: anyerror!u32 };
    var buf: [256]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    const values = [_]E{ .{ .key = .{ .cp = 'x', .text = "x" } }, .tick, .{ .failed = error.FileNotFound }, .{ .failed = 9 } };
    for (&values) |*v| try encode(E, v, &w);
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    var r: Reader = .{ .bytes = w.buffered() };
    for (&values) |*v| try std.testing.expectEqual(digest(E, v), digest(E, &try decode(E, &r, arena.allocator())));
    try std.testing.expectEqual(r.bytes.len, r.at);
}

test "an error is taped by its name, which another build reads back as its own" {
    // The build's number for an error is its own: 451 of 505 names were
    // numbered otherwise in a Linux window's build than a terminal's, so a
    // window replica read a terminal session's FileNotFound as another.
    var buf: [64]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    const failed: error{ FileNotFound, NotDir }!u32 = error.NotDir;
    try encode(@TypeOf(failed), &failed, &w);
    try std.testing.expectEqualSlices(u8, "\x00\x06\x00NotDir", w.buffered());
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    var r: Reader = .{ .bytes = w.buffered() };
    try std.testing.expectError(error.NotDir, try decode(@TypeOf(failed), &r, arena.allocator()));
    // A name this build's set lacks (an OS's own): the tape is another
    // build's, and the replay diverges rather than read some other error.
    r = .{ .bytes = "\x00\x0c\x00FileTooLarge" };
    try std.testing.expectError(error.NoSuchError, decode(@TypeOf(failed), &r, arena.allocator()));
    // An anyerror (a host's report) is read back as one of tape.Failure's.
    const Report = struct { err: anyerror };
    w = .fixed(&buf);
    try encode(Report, &.{ .err = error.FileNotFound }, &w);
    r = .{ .bytes = w.buffered() };
    try std.testing.expectEqual(error.FileNotFound, (try decode(Report, &r, arena.allocator())).err);
}

test "an enum is digested by its name, which another build may number otherwise" {
    // registry.Builtin as a Linux build makes it (Tty9p in it) and as a
    // FreeBSD one does: LocationsConfig is another number in each.
    const Linux = enum { Look, Tty9p, LocationsConfig };
    const FreeBSD = enum { Look, LocationsConfig };
    const S = struct { from: Linux, also: [2]Linux };
    const T = struct { from: FreeBSD, also: [2]FreeBSD };
    try std.testing.expectEqual(digest(S, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }), digest(T, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }));
    try std.testing.expect(digest(S, &.{ .from = .Look, .also = .{ .Look, .Look } }) != digest(S, &.{ .from = .Tty9p, .also = .{ .Look, .Look } }));
}

test "a digest is of values: the same text at two addresses is one digest" {
    const S = struct { name: []const u8, n: u32, next: ?*const u32 };
    const a = "same text";
    var b: [9]u8 = undefined;
    @memcpy(&b, a);
    const x: u32 = 7;
    const y: u32 = 7;
    try std.testing.expectEqual(digest(S, &.{ .name = a, .n = 1, .next = &x }), digest(S, &.{ .name = &b, .n = 1, .next = &y }));
    try std.testing.expect(digest(S, &.{ .name = a, .n = 1, .next = &x }) != digest(S, &.{ .name = a, .n = 2, .next = &x }));
}

test "an annotated field is in no digest, and a length cuts its array" {
    const S = struct {
        kept: u32,
        cache: u32,
        ring: [4]u8,
        ring_len: u8,
        pub const replica = .{ .derived = .{"cache"}, .len = .{.{ "ring", "ring_len" }} };
    };
    try std.testing.expectEqual(
        digest(S, &.{ .kept = 1, .cache = 2, .ring = .{ 1, 2, 9, 9 }, .ring_len = 2 }),
        digest(S, &.{ .kept = 1, .cache = 3, .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 }),
    );
}

test "an optional slice comes back, and the fields after it" {
    const S = struct { before: u32 = 0, command: ?[]u8 = null, after: u32 = 0 };
    var text = "sleep 30".*;
    const bytes = try save(S, std.testing.allocator, &.{ .before = 1, .command = &text, .after = 2 });
    defer std.testing.allocator.free(bytes);
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    const back = try load(S, arena.allocator(), bytes, null);
    try std.testing.expectEqualStrings("sleep 30", back.command.?);
    try std.testing.expectEqual(2, back.after);
}

test "a dump comes back whole: shared things shared, lists and runs as long as they were" {
    const gpa = std.testing.allocator;
    const Leaf = struct { n: u21, name: []const u8 };
    const Mode = enum { a, b, c };
    const S = struct {
        mode: Mode = .a,
        leaf: *Leaf,
        same_leaf: *Leaf,
        text: []u8,
        same_text: []u8,
        list: std.ArrayList(u16) = .empty,
        maybe: ?Leaf = null,
        either: union(enum) { none, some: u32, many: []const u16 } = .none,
        ring: [4]u8 = @splat(0),
        ring_len: u8 = 0,
        room: []i32 = &.{},
        room_len: u8 = 0,
        cache: u64 = 7,
        alloc: std.mem.Allocator,
        flags: packed struct { x: bool = false, y: u3 = 0 } = .{},
        pub const replica = .{ .derived = .{"cache"}, .len = .{ .{ "ring", "ring_len" }, .{ "room", "room_len" } } };
    };
    var leaf: Leaf = .{ .n = 0x1fffff, .name = "leaf" };
    var room = [_]i32{ 4, 5, -1, -1 };
    var text = "shared text".*;
    var list: std.ArrayList(u16) = .empty;
    defer list.deinit(gpa);
    try list.appendSlice(gpa, &.{ 1, 2, 3 });
    const x: S = .{ .mode = .c, .leaf = &leaf, .same_leaf = &leaf, .text = &text, .same_text = &text, .list = list, .maybe = .{ .n = 3, .name = "maybe" }, .either = .{ .many = &.{ 9, 8 } }, .ring = .{ 5, 6, 0xAA, 0xAA }, .ring_len = 2, .room = &room, .room_len = 2, .cache = 99, .alloc = gpa, .flags = .{ .x = true, .y = 5 } };
    const bytes = try save(S, gpa, &x);
    defer gpa.free(bytes);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const y = try load(S, arena.allocator(), bytes, null);
    try std.testing.expectEqual(digest(S, &x), digest(S, &y));
    try std.testing.expect(y.leaf == y.same_leaf and y.text.ptr == y.same_text.ptr);
    try std.testing.expectEqual(@as(u64, 7), y.cache);
    try std.testing.expectEqualSlices(u16, &.{ 1, 2, 3 }, y.list.items);
    try std.testing.expectEqual(true, y.flags.x);
    // A slice its `len` cuts keeps its room.
    try std.testing.expectEqual(@as(usize, 4), y.room.len);
    try std.testing.expectEqualSlices(i32, &.{ 4, 5 }, y.room[0..2]);
    // A fixpoint: what was read is written as it was.
    const again = try save(S, gpa, &y);
    defer gpa.free(again);
    try std.testing.expectEqualSlices(u8, bytes, again);
}

test "a dump crosses builds: a field added takes its default, one removed is passed over, one changed is left out" {
    const gpa = std.testing.allocator;
    const Old = struct {
        const Color = enum { red, green, blue };
        const Pane = struct { name: []const u8, color: Color = .red, gone: u32 = 1, width: u16 = 0, kind: u32 = 0 };
        panes: [3]?*Pane = @splat(null),
        count: u8 = 0,
        renamed: u32 = 0,
    };
    const New = struct {
        // Values renumbered and one added before the others.
        const Color = enum { cyan, blue, red, green };
        const Wide = struct { a: u8 };
        const Pane = struct { added: bool = true, color: Color = .cyan, width: u32 = 0, name: []const u8, kind: Wide = .{ .a = 4 } };
        // A pane's required field changed kind: that pane is left out.
        const Strict = struct { name: u8 };
        panes: [4]?*Pane = @splat(null),
        count: u16 = 0,
        renamed_now: u32 = 5,
    };
    var one: Old.Pane = .{ .name = "one", .color = .blue, .gone = 9, .width = 300, .kind = 2 };
    var two: Old.Pane = .{ .name = "two", .color = .green };
    const old: Old = .{ .panes = .{ &one, null, &two }, .count = 2, .renamed = 7 };
    const bytes = try save(Old, gpa, &old);
    defer gpa.free(bytes);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    // The notes are made where the load's values are.
    var notes: std.ArrayList(u8) = .empty;
    const new = try load(New, arena.allocator(), bytes, &notes);
    try std.testing.expectEqual(@as(u16, 2), new.count);
    try std.testing.expectEqual(@as(u32, 5), new.renamed_now);
    const a = new.panes[0].?;
    try std.testing.expectEqualStrings("one", a.name);
    try std.testing.expectEqual(New.Color.blue, a.color);
    try std.testing.expectEqual(@as(u32, 300), a.width);
    try std.testing.expect(a.added);
    try std.testing.expectEqual(@as(u8, 4), a.kind.a);
    try std.testing.expect(new.panes[1] == null and new.panes[3] == null);
    try std.testing.expectEqual(New.Color.green, new.panes[2].?.color);
    try std.testing.expect(std.mem.indexOf(u8, notes.items, "kind") != null);

    const Strict = struct {
        const Pane = struct { name: u8 };
        panes: [3]?*Pane = @splat(null),
        count: u8 = 0,
    };
    notes.clearRetainingCapacity();
    const strict = try load(Strict, arena.allocator(), bytes, &notes);
    try std.testing.expect(strict.panes[0] == null and strict.panes[2] == null);
    try std.testing.expectEqual(@as(u8, 2), strict.count);
    try std.testing.expect(std.mem.indexOf(u8, notes.items, "left out") != null);

    // And back: the newer build's dump read by the older one.
    const newer = try save(New, gpa, &new);
    defer gpa.free(newer);
    const back = try load(Old, arena.allocator(), newer, null);
    try std.testing.expectEqualStrings("two", back.panes[2].?.name);
    try std.testing.expectEqual(@as(u32, 1), back.panes[0].?.gone);
    try std.testing.expectEqual(Old.Color.blue, back.panes[0].?.color);
}

test "a length past what its buffer holds is refused where it is read back (a tape, a dump, an image), its field named, never walked" {
    // Text's undo (a fixed array a length cuts) and its ranges (room a
    // length cuts): a digest, a copy and a deinit slice each that far.
    const Ring = struct {
        ring: [4]u8 = @splat(0),
        ring_len: u8 = 0,
        pub const replica = .{ .len = .{.{ "ring", "ring_len" }} };
    };
    const Room = struct {
        room: []i32 = &.{},
        room_len: u8 = 0,
        pub const replica = .{ .len = .{.{ "room", "room_len" }} };
    };
    const gpa = std.testing.allocator;
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const a = arena.allocator();

    // A dump: the length is its last byte, after the ring's count and items.
    const ring = try save(Ring, gpa, &.{ .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 });
    defer gpa.free(ring);
    try std.testing.expectEqual(@as(u8, 2), (try load(Ring, a, ring, null)).ring_len);
    // The notes are made where the load's values are.
    var notes: std.ArrayList(u8) = .empty;
    // Past the array, and within it but past the two the dump holds.
    for ([_]u8{ 200, 5, 3 }) |says| {
        ring[ring.len - 1] = says;
        notes.clearRetainingCapacity();
        try std.testing.expectError(error.BadDump, load(Ring, a, ring, &notes));
        try std.testing.expect(std.mem.indexOf(u8, notes.items, "ring_len") != null);
    }
    var room = [_]i32{ 4, 5, 6 };
    const roomy = try save(Room, gpa, &.{ .room = &room, .room_len = 2 });
    defer gpa.free(roomy);
    roomy[roomy.len - 1] = 3;
    try std.testing.expectEqual(@as(u8, 3), (try load(Room, a, roomy, null)).room_len);
    roomy[roomy.len - 1] = 4;
    try std.testing.expectError(error.BadDump, load(Room, a, roomy, null));

    // A tape: an array is taped whole, a slice as long as it is.
    var buf: [64]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    try encode(Ring, &.{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 4 }, &w);
    try encode(Room, &.{ .room = &room, .room_len = 3 }, &w);
    try encode(Ring, &.{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 5 }, &w);
    try encode(Room, &.{ .room = &room, .room_len = 4 }, &w);
    var r: Reader = .{ .bytes = w.buffered() };
    _ = try decode(Ring, &r, a);
    _ = try decode(Room, &r, a);
    try std.testing.expectError(error.BadTape, decode(Ring, &r, a));
    try std.testing.expectError(error.BadTape, decode(Room, &r, a));

    // An image: written as far as the array holds, its length as it says.
    var image: std.Io.Writer.Allocating = .init(gpa);
    defer image.deinit();
    var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
    var put: Put = .{ .gpa = gpa };
    defer put.deinit();
    const Both = struct { ring: Ring, room: Room };
    try db.runContext(struct {
        put: *Put,
        room: []i32,
        pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
            const map = try Mem.HashMap(.read_write).init(cursor.*);
            try ctx.put.member(map, "fits", Both, &.{ .ring = .{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 4 }, .room = .{ .room = ctx.room, .room_len = 3 } });
            try ctx.put.member(map, "ring", Ring, &.{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 9 });
            try ctx.put.member(map, "room", Room, &.{ .room = ctx.room, .room_len = 4 });
        }
    }{ .put = &put, .room = &room });
    var get: Get = .init(a);
    defer get.deinit();
    const root = db.rootCursor().readOnly();
    _ = try get.get(Both, (try Get.member(root, "fits")).?);
    try std.testing.expectError(error.BadDump, get.get(Ring, (try Get.member(root, "ring")).?));
    try std.testing.expect(std.mem.indexOf(u8, get.notes.items, "ring_len") != null);
    try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?));
}

test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image, and so is an entry not where it may be; a place past its thing's last is that last" {
    const S = struct {
        const Self = @This();
        const Inner = struct {
            at: u8 = 0,
            list: [3]u8 = @splat(0),
            n: u8 = 0,
            // Indexes into the struct holding it, held where its fields end.
            pub const replica = .{ .len = .{.{ "list", "n" }}, .index = .{ .{ "at", Self, "there" }, .{ "list", Self, "there" } } };
        };
        things: [4]?u8 = @splat(null),
        live: u8 = 0,
        slot: ?u16 = null,
        scroll: u32 = 0,
        inner: [2]?*Inner = @splat(null),
        edges: [2]u8 = @splat(0),
        pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }}, .within = .{.{ "edges", "inside" }} };
        pub fn there(s: *const Self, i: usize) bool {
            return i < s.things.len and s.things[i] != null;
        }
        pub fn inside(s: *const Self, i: usize) bool {
            return s.edges[i] < 8;
        }
        pub fn last(_: *const Self) usize {
            return 9;
        }
    };
    const gpa = std.testing.allocator;
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const a = arena.allocator();
    var inner: S.Inner = .{ .at = 2, .list = .{ 0, 2, 1 }, .n = 2 };
    const good: S = .{ .things = .{ 1, null, 3, null }, .live = 2, .slot = 3, .scroll = 50, .inner = .{ &inner, null } };
    // Each a value no session has: the field it names.
    const Bad = struct { []const u8, S };
    var bad_at: S.Inner = .{ .at = 1 };
    var bad_list: S.Inner = .{ .list = .{ 0, 3, 0 }, .n = 2 };
    const bad = [_]Bad{
        .{ "S.live says 1", blk: {
            var v = good;
            v.live = 1;
            break :blk v;
        } },
        .{ "S.slot says 4", blk: {
            var v = good;
            v.slot = 4;
            break :blk v;
        } },
        .{ "Inner.at says 1", blk: {
            var v = good;
            v.inner[1] = &bad_at;
            break :blk v;
        } },
        .{ "Inner.list says 3", blk: {
            var v = good;
            v.inner[1] = &bad_list;
            break :blk v;
        } },
        .{ "S.edges[1] is not within", blk: {
            var v = good;
            v.edges = .{ 7, 8 };
            break :blk v;
        } },
    };
    const n_bad = bad.len;
    var notes: std.ArrayList(u8) = .empty;

    // A dump.
    const bytes = try save(S, gpa, &good);
    defer gpa.free(bytes);
    const back = try load(S, a, bytes, null);
    try std.testing.expectEqual(@as(u32, 9), back.scroll);
    try std.testing.expectEqual(@as(?u16, 3), back.slot);
    for (bad) |b| {
        const dumped = try save(S, gpa, &b[1]);
        defer gpa.free(dumped);
        notes.clearRetainingCapacity();
        try std.testing.expectError(error.BadDump, load(S, a, dumped, &notes));
        try std.testing.expect(std.mem.indexOf(u8, notes.items, b[0]) != null);
    }

    // A tape.
    var buf: [256]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    try encode(S, &good, &w);
    for (bad) |b| try encode(S, &b[1], &w);
    var r: Reader = .{ .bytes = w.buffered() };
    try std.testing.expectEqual(@as(u32, 9), (try decode(S, &r, a)).scroll);
    for (bad) |_| try std.testing.expectError(error.BadTape, decode(S, &r, a));

    // An image.
    var image: std.Io.Writer.Allocating = .init(gpa);
    defer image.deinit();
    var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
    var put: Put = .{ .gpa = gpa };
    defer put.deinit();
    try db.runContext(struct {
        put: *Put,
        good: *const S,
        bad: []const Bad,
        pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
            const map = try Mem.HashMap(.read_write).init(cursor.*);
            try ctx.put.member(map, "good", S, ctx.good);
            inline for (0..n_bad) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]);
        }
    }{ .put = &put, .good = &good, .bad = &bad });
    var get: Get = .init(a);
    defer get.deinit();
    const root = db.rootCursor().readOnly();
    try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll);
    inline for (0..n_bad) |i| {
        get.notes.clearRetainingCapacity();
        try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?));
        try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null);
    }
}

test "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held" {
    const Old = struct {
        const Thing = struct { n: u32 = 0 };
        things: [2]?*Thing = @splat(null),
        at: ?u8 = null,
    };
    // A thing whose `n` changed kind, no default: it is left out.
    const New = struct {
        const Self = @This();
        const Thing = struct { n: struct { a: u8 } };
        things: [2]?*Thing = @splat(null),
        at: ?u8 = null,
        pub const replica = .{ .index = .{.{ "at", "there" }}, .left_out = "forget" };
        pub fn there(s: *const Self, i: usize) bool {
            return i < s.things.len and s.things[i] != null;
        }
        pub fn forget(s: *Self) void {
            if (s.at) |i| if (!s.there(i)) {
                s.at = null;
            };
        }
    };
    const Unforgiving = struct {
        const Self = @This();
        things: [2]?*New.Thing = @splat(null),
        at: ?u8 = null,
        pub const replica = .{ .index = .{.{ "at", "there" }} };
        pub fn there(s: *const Self, i: usize) bool {
            return i < s.things.len and s.things[i] != null;
        }
    };
    const gpa = std.testing.allocator;
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    var one: Old.Thing = .{ .n = 1 };
    const bytes = try save(Old, gpa, &.{ .things = .{ &one, null }, .at = 0 });
    defer gpa.free(bytes);
    const new = try load(New, arena.allocator(), bytes, null);
    try std.testing.expect(new.things[0] == null and new.at == null);
    try std.testing.expectError(error.BadDump, load(Unforgiving, arena.allocator(), bytes, null));
}

test "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows" {
    const gpa = std.testing.allocator;
    const B = struct { bits: std.DynamicBitSetUnmanaged = .{}, after: []const u8 = "" };
    var b: B = .{ .bits = try .initEmpty(gpa, 70), .after = "x" };
    defer b.bits.deinit(gpa);
    var arena: std.heap.ArenaAllocator = .init(gpa);
    defer arena.deinit();
    const a = arena.allocator();
    const bytes = try save(B, gpa, &b);
    defer gpa.free(bytes);
    // The bits' count, two words, then the slice's reference, count and byte.
    const at = bytes.len - (8 + 16 + 4 + 8 + 1);
    try std.testing.expectEqual(@as(u64, 70), std.mem.readInt(u64, bytes[at..][0..8], .little));
    std.mem.writeInt(u64, bytes[at..][0..8], std.math.maxInt(u64), .little);
    try std.testing.expectError(error.EndOfDump, load(B, a, bytes, null));
    // Passed over by a build without the field.
    const Without = struct { after: []const u8 = "" };
    try std.testing.expectError(error.EndOfDump, load(Without, a, bytes, null));
    // An image's: the bytes a field of that name holds.
    var image: std.Io.Writer.Allocating = .init(gpa);
    defer image.deinit();
    var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
    var put: Put = .{ .gpa = gpa };
    defer put.deinit();
    const Raw = struct { bits: []const u8 };
    try db.runContext(struct {
        put: *Put,
        pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
            try ctx.put.member(try Mem.HashMap(.read_write).init(cursor.*), "b", Raw, &.{ .bits = &@as([8]u8, @splat(0xff)) });
        }
    }{ .put = &put });
    var get: Get = .init(a);
    defer get.deinit();
    try std.testing.expectError(error.BadDump, get.get(B, (try Get.member(db.rootCursor().readOnly(), "b")).?));
}

test "what a value left out had made is freed: a pane another build cannot give leaks nothing, from a dump or an image" {
    const gpa = std.testing.allocator;
    const Old = struct {
        const Pane = struct { name: []const u8, n: u32 = 0 };
        panes: [2]?*Pane = @splat(null),
    };
    // The pane's `n` changed kind, with no default: the pane is left out,
    // after its name was made.
    const New = struct {
        const Pane = struct { name: []const u8, n: struct { a: u8 } };
        panes: [2]?*Pane = @splat(null),
    };
    var one: Old.Pane = .{ .name = "one", .n = 1 };
    const old: Old = .{ .panes = .{ &one, null } };
    const bytes = try save(Old, gpa, &old);
    defer gpa.free(bytes);
    try std.testing.expect((try load(New, gpa, bytes, null)).panes[0] == null);
    var image: std.Io.Writer.Allocating = .init(gpa);
    defer image.deinit();
    var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
    var put: Put = .{ .gpa = gpa };
    defer put.deinit();
    try db.runContext(struct {
        put: *Put,
        old: *const Old,
        pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
            try ctx.put.member(try Mem.HashMap(.read_write).init(cursor.*), "old", Old, ctx.old);
        }
    }{ .put = &put, .old = &old });
    var get: Get = .init(gpa);
    defer get.deinit();
    try std.testing.expect((try get.get(New, (try Get.member(db.rootCursor().readOnly(), "old")).?)).panes[0] == null);
}

test "a dump that is not one, or is cut short, is refused" {
    const gpa = std.testing.allocator;
    const S = struct { a: u32, b: []const u8 };
    try std.testing.expectError(error.BadDump, load(S, gpa, "not a dump", null));
    const bytes = try save(S, gpa, &.{ .a = 1, .b = "bee" });
    defer gpa.free(bytes);
    // What it made before the end is freed again.
    try std.testing.expectError(error.EndOfDump, load(S, gpa, bytes[0 .. bytes.len - 2], null));
}

test "a blob of 4 KiB and up is digested by its length, what it holds told by its keeper's revision; a smaller one by its bytes" {
    const gpa = std.testing.allocator;
    const File = struct {
        pub const replica = .{ .blob = .{"content"} };
        content: []u8,
        revision: u32 = 0,
    };
    const text = try gpa.alloc(u8, 64 << 10);
    defer gpa.free(text);
    @memset(text, 'a');
    var f: File = .{ .content = text };
    const before = digest(File, &f);
    // Written in place: the same digest, until its revision says so.
    text[1000] = 'b';
    try std.testing.expectEqual(before, digest(File, &f));
    f.revision += 1;
    try std.testing.expect(digest(File, &f) != before);
    // Another length is another digest.
    f.revision = 0;
    f.content = text[0 .. text.len - 1];
    try std.testing.expect(digest(File, &f) != before);
    // A small one by its bytes.
    var small = "abc".*;
    f.content = &small;
    const was = digest(File, &f);
    small[1] = 'x';
    try std.testing.expect(digest(File, &f) != was);
}

test "a shape's numbers are written as {d} writes them" {
    inline for (.{ 0, 7, 10, 65535, -1, -300, std.math.minInt(i128), std.math.maxInt(u128) }) |n|
        try std.testing.expectEqualStrings(std.fmt.comptimePrint("{d}", .{n}), comptime decimal(n));
}