ferrosys 0.8.0

Pure-Rust filesystem formatter and reader: ext4, ext3, ext2, FAT32, FAT16, FAT12, exFAT, btrfs, and APFS — rootless, in userspace, byte-reproducible
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
//! The reader: parse a FAT volume back into a geometry, a directory tree, and file
//! contents.
//!
//! It reads volumes other tools wrote, not only the ones this crate writes. All three types
//! are followed through one implementation, because the only differences are the width of a
//! table entry and where the root directory sits; long names are reassembled from the
//! entries that carry them and tied to their short entry by checksum; and the type is
//! derived from the volume's own geometry rather than read out of the type string, which is
//! documentation that no conformant driver looks at.
//!
//! One shape the format permits is outside what this reads: a volume with more than two
//! allocation tables. The count is refused in the geometry, below the policy threshold, so
//! it is refused under [`ReadPolicy::Lenient`] as well as under `Strict` — see
//! [`GeometryError::FatCountUnsupported`](crate::fat::GeometryError::FatCountUnsupported).
//! `fsck.fat` refuses the same volume, so this is where the ecosystem sits rather than a
//! narrowness of this crate's own.
//!
//! # Robustness and strictness
//!
//! Two properties are kept apart. *Robustness* is always on: every on-disk field is
//! bounds-checked and every fallible step returns a [`ReadError`] rather than panicking or
//! reading out of range, on any input — including one built to break it.
//!
//! *Conformance strictness* is a policy: a threshold over the [`Severity`] of the
//! [`Anomaly`] a deviation carries. [`ReadPolicy::Strict`], the default, is fatal at any
//! deviation a FAT volume this crate writes would not carry, so a strict read either yields
//! the filesystem the image describes or names the deviation that stopped it. A state a
//! driver leaves behind is the exception: a volume left dirty, or a recorded failure of the
//! medium, is reported at [`Severity::Cosmetic`] and a strict read goes on.
//!
//! **A strict read accepts every volume this crate's own writer produces, and every state a
//! conformant driver can leave behind.** The first half is the line the severities are drawn
//! against, and it is what makes the two halves of the family one thing rather than two: a format followed by a strict open is a round trip at every input
//! the writer accepts — every geometry a
//! [`PlanRequest`](crate::fat::PlanRequest) reaches and every value a
//! [`FormatOptions`](crate::fat::FormatOptions) carries alike, since a field the writer
//! accepts and this refuses breaks the round trip as surely as a misplaced cluster would.
//! It holds for the deliberately non-conformant geometries too: an undersized FAT32 is
//! something this crate emits on request, and so is remarked on rather than refused.
//!
//! The line runs both ways. Where a value has a set the format defines and this reader
//! enforces it — the media descriptor is the one such field — the writer refuses what falls
//! outside it, rather than emitting a volume neither end would read back.
//!
//! [`ReadPolicy::Lenient`] moves that threshold above every severity, so nothing is fatal. A
//! whole-volume [`scan`](Reader::scan) checks the parameter block, every copy of the file
//! allocation table against the first, the information sector, every directory entry, and
//! every cluster chain — including the clusters that are allocated and reached by nothing —
//! collecting each deviation as an [`Anomaly`] into a [`ScanReport`] instead of stopping at
//! the first. The report projects to JSON, SARIF, or a human table, and
//! [`ScanReport::has_fatal`] applies a policy's threshold back to what the scan found.
//!
//! # What a FAT volume does not tell you
//!
//! There is no owner, no permission bits, no second name for a file, and no field for the
//! code page an eleven-byte short name is written in. The first three are filled from the
//! caller's [`Synthesis`] on the extraction surface and named there; the fourth is
//! [`ShortNameCharset`], which defaults to interpreting nothing.
//!
//! The handle opens over any [`Read`] + [`Seek`] source at an arbitrary byte offset, so it
//! reads a volume inside a partitioned disk image as readily as a bare one.

use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::ControlFlow;

use crate::bytes::get_u16;
use crate::fidelity::Synthesis;
use crate::finding::{Family, Finding, Findings, Severity};
use crate::io::{Bounded, offset_of, read_exact_at};
use crate::path::{is_hostile_component, is_reserved_name_char};
use crate::policy::MAX_PATH;
use crate::policy::{Limits, ReadPolicy};
use crate::time::{DosTimestamp, Timestamp};
use crate::tree::{Attributes, Bound, Child, FsTree, NodeKind, TreeEntry, TreeError, Usage};

use super::charset::ShortNameCharset;
use super::geometry::{
    FatLayout, FatType, MAX_BYTES_PER_CLUSTER, MAX_CLUSTERS_FAT12, MIN_CLUSTERS_FAT16,
    layout_from_boot,
};
use super::model::{MAX_DIRECTORY_BYTES, MAX_DIRECTORY_ENTRIES};
use super::ondisk::{
    Attributes as DirAttributes, BootSector, BootSectorTail, DIR_ENTRY_SIZE, DirEntry, FsInfo,
    LFN_CHARS_PER_ENTRY, LFN_LAST_ENTRY, LFN_MAX_ENTRIES, LFN_PADDING, LfnEntry, NAME_DELETED,
    NAME_END, NAME_LEADING_E5, ParseError, VOLUME_DIRTY,
};
use super::table;

/// The subsystem a deviation was found in.
///
/// A FAT volume has four, and they are not ext's: there is no superblock, no group
/// descriptor, and no extent tree, and a family's own words for its own parts are the whole
/// reason a category stays with its family rather than hoisting.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Category {
    /// The boot sector and its BIOS parameter block, or the backup copy of it.
    BootSector,
    /// The FAT32 information sector, or its backup.
    InfoSector,
    /// A copy of the file allocation table, or the allocation it records.
    AllocationTable,
    /// A directory, its entries, or the long names they carry.
    Directory,
    /// The source the filesystem is read from, rather than the filesystem: a read the
    /// source failed for a reason other than ending. A scan holds these apart from its
    /// findings, as [`source_failures`](crate::ScanReport::source_failures).
    Source,
}

impl Category {
    /// The lowercase name of this subsystem, for a rendered report.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Category::BootSector => "boot sector",
            Category::InfoSector => "information sector",
            Category::AllocationTable => "allocation table",
            Category::Directory => "directory",
            Category::Source => "source",
        }
    }
}

crate::naming::serialize_as_name!(Category);

/// Where in the volume a deviation sits. Every field is optional: a deviation carries only
/// the coordinates that locate it.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Location {
    /// Sector number within the volume, when the deviation is sector-addressed. This is
    /// what becomes the byte offset a [`Finding`] carries.
    pub sector: Option<u32>,
    /// Cluster number, when the deviation is cluster-addressed.
    pub cluster: Option<u32>,
    /// Index of a directory entry within its directory, counting 32-byte slots from zero.
    pub entry: Option<u32>,
}

impl Location {
    /// This location with any coordinate `other` carries that this one does not.
    ///
    /// A deviation knows where it is in its own terms — a table entry knows its cluster —
    /// and the walk that met it knows the rest. Merging rather than replacing is what keeps
    /// the more specific of the two.
    fn or(self, other: Self) -> Self {
        Self {
            sector: self.sector.or(other.sector),
            cluster: self.cluster.or(other.cluster),
            entry: self.entry.or(other.entry),
        }
    }
}

/// A typed deviation from what this crate would emit, carrying its severity, the subsystem
/// it was found in, where it sits, and a human description.
///
/// This is FAT's structured value, and it stays FAT's: the subsystem is a [`Category`]
/// rather than a word, and the place is a cluster and a sector rather than a byte offset,
/// because those are what a consumer reasoning about a FAT volume acts on.
///
/// Rendering goes through [`to_finding`](Self::to_finding), which projects into the crate's
/// [`Finding`] — the frame every family shares and every renderer consumes.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Anomaly {
    /// How serious the deviation is.
    pub severity: Severity,
    /// The subsystem it was found in.
    pub category: Category,
    /// Where it sits in the volume.
    pub location: Location,
    /// A human-readable description.
    pub detail: String,
}

impl crate::Deviation for Anomaly {
    fn severity(&self) -> Severity {
        self.severity
    }

    fn is_source_failure(&self) -> bool {
        self.category == Category::Source
    }

    /// The sector size is the addressing unit a FAT location is stated in.
    fn to_finding(&self, unit: u32) -> Finding {
        Anomaly::to_finding(self, unit)
    }
}

impl Anomaly {
    /// Project this anomaly into the crate's family-agnostic [`Finding`], resolving a
    /// sector-addressed location to the byte offset that sector sits at under
    /// `bytes_per_sector`.
    ///
    /// The coordinates carry FAT's own words, outermost first — `cluster`, then `sector`,
    /// then `entry` — which is the order a person reads a location in. A cluster number is
    /// not converted to an offset, because where it sits depends on the layout rather than
    /// on the number alone, so an anomaly located only by one carries no offset.
    #[must_use]
    pub fn to_finding(&self, bytes_per_sector: u32) -> Finding {
        // Destructured exhaustively on purpose: a field added to `Anomaly` is a compile
        // error here, which forces a decision about what the projection carries rather than
        // letting a new fact about a finding go silently unreported.
        let Self {
            severity,
            category,
            location,
            detail,
        } = self;
        let Location {
            sector,
            cluster,
            entry,
        } = *location;

        crate::finding::project(
            *severity,
            Family::Fat,
            category.as_str(),
            &[
                ("cluster", cluster.map(u64::from)),
                ("sector", sector.map(u64::from)),
                ("entry", entry.map(u64::from)),
            ],
            // The sector is what addresses bytes. A cluster number does not: where it sits
            // depends on the layout rather than on the number alone.
            sector.map(u64::from),
            bytes_per_sector,
            detail,
        )
    }
}

/// A failure reading a FAT volume.
///
/// The variants divide into three kinds. A few are the source's rather than the image's
/// ([`Io`](Self::Io)) or a caller's bound being reached
/// ([`FileTooLarge`](Self::FileTooLarge), [`WalkTooLarge`](Self::WalkTooLarge)). Most are
/// deviations from what a FAT volume this crate writes carries, each of which projects to a
/// typed [`Anomaly`] through [`anomaly`](Self::anomaly) — so the same fault is an error
/// under [`ReadPolicy::Strict`] and a collected finding under a scan, described the same way
/// either time. The rest are a caller asking for something that is not there.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ReadError {
    /// The underlying source could not be read or sought.
    /// Carried as [`TreeError::Io`] describes, which is where the rule
    /// this crate records an i/o failure by is written out: the kind beside the message, so a
    /// caller tells a truncated image from an environment failure without matching on text.
    #[error("i/o error: {message}")]
    #[non_exhaustive]
    Io {
        /// How the underlying [`std::io::Error`] classified itself.
        kind: std::io::ErrorKind,
        /// The error rendered as text, for a message a person reads.
        message: String,
    },
    /// An on-disk structure could not be recovered from its bytes.
    #[error(transparent)]
    Parse(#[from] ParseError),
    /// The BIOS parameter block does not describe a FAT volume: a field holds a value no
    /// FAT volume carries, or the fields do not agree with each other.
    ///
    /// This is what detection answers "not ours" to. The reader names the field instead,
    /// because a caller who reached the reader has already been told the image is a FAT
    /// volume and needs to know why it is not readable as one.
    #[error("{field} = {value} is not a value a FAT volume's parameter block carries")]
    #[non_exhaustive]
    BadBootSector {
        /// The parameter block field, in the format's own spelling.
        field: &'static str,
        /// That field's value, or the number derived from it that failed.
        value: u64,
    },
    /// The volume's cluster count falls in the band the specification and Windows read as
    /// different types, so the two would follow its chains through tables of different entry
    /// widths.
    ///
    /// The reader agrees with the specification and with Linux, which is what the count
    /// derivation says; the deviation is that the volume is one no formatter should have
    /// written. This crate's planner steps down out of the band rather than emitting one.
    #[error(
        "a count of {clusters} clusters is FAT16 to the specification and to Linux and FAT12 \
         to Windows; the two follow its chains through tables of different entry widths"
    )]
    #[non_exhaustive]
    AmbiguousClusterCount {
        /// The volume's cluster count.
        clusters: u32,
    },
    /// The volume's cluster is larger than 32 KiB, which the format's own guidance says a
    /// cluster should never be (documented).
    ///
    /// More than one widely deployed driver holds a cluster's byte count in sixteen bits, so
    /// a volume like this is one some drivers misread. It reads here, and this crate's writer
    /// does not create one; the remark is that the volume is outside what the guidance covers.
    #[error(
        "the volume's clusters are {bytes} bytes, past the 32768 the format advises a cluster \
         never exceed"
    )]
    #[non_exhaustive]
    LargeCluster {
        /// Bytes per cluster.
        bytes: u32,
    },
    /// A directory's entry records a length, where the format records none for a directory
    /// (documented): its length is its chain.
    ///
    /// No driver reads the field for a directory, so the directory reads whole; the pinned
    /// `fsck.fat` clears it (observed).
    #[error(
        "the directory at entry {index} records a length of {size} bytes, where a directory records none"
    )]
    #[non_exhaustive]
    DirectoryWithSize {
        /// The entry's index within its directory.
        index: u32,
        /// The length the entry records.
        size: u32,
    },
    /// An entry carries the volume-label attribute and the directory attribute together, and
    /// is neither a label nor a directory.
    ///
    /// A label is an entry carrying the volume-label attribute and neither the long-name
    /// combination nor the directory attribute — the one definition this reader holds both
    /// `volume_label` and a directory read to. Such an entry is not a name in the tree, as no
    /// entry carrying the volume-label attribute is; the pinned `fsck.fat` reads it as a
    /// directory and `mlabel` as no label (observed).
    #[error(
        "entry {index} carries the volume-label and directory attributes together, which is \
         neither a label nor a directory"
    )]
    #[non_exhaustive]
    LabelWithDirectoryAttribute {
        /// The entry's index within its directory.
        index: u32,
    },
    /// The root directory holds a second volume label, where the format defines one.
    ///
    /// The first is the label, as every driver and `fatlabel` read it, and the second is a
    /// record nothing reads. The pinned `fsck.fat` accepts it and `mlabel` reads the first
    /// (observed).
    #[error("entry {index} is a second volume label, and the first is the volume's")]
    #[non_exhaustive]
    SecondVolumeLabel {
        /// The entry's index within the root directory.
        index: u32,
    },
    /// The root's volume label entry begins with a space, which a name field's first byte may
    /// not be (documented). The pinned `fsck.fat` removes such a label (observed). Its padding
    /// is not a label, so [`Reader::volume_label`] reads a field of nothing but spaces as no
    /// label at all.
    #[error("entry {index} is a volume label beginning with a space")]
    #[non_exhaustive]
    LabelBeginsWithSpace {
        /// The entry's index within the root directory.
        index: u32,
    },
    /// The information sector's free-cluster count names more clusters than the volume has.
    ///
    /// The count is a hint and may be stale, but a value past the clusters is not a stale
    /// count — it is one no driver kept. The pinned `fsck.fat` replaces it (observed).
    #[error("the free-cluster hint is {stated}, more clusters than this volume's {clusters}")]
    #[non_exhaustive]
    FreeCountOutOfRange {
        /// The count the information sector records.
        stated: u32,
        /// Clusters the volume has.
        clusters: u32,
    },
    /// The information sector's free-cluster count is not how many clusters the table marks
    /// free.
    ///
    /// The format calls the count the last known one, not necessarily correct (documented),
    /// so a stale one is a number nobody was obliged to update — a remark, and not a fault.
    #[error("the free-cluster hint is {stated} and the table marks {counted} clusters free")]
    #[non_exhaustive]
    FreeCountStale {
        /// The count the information sector records.
        stated: u32,
        /// The clusters the table marks free.
        counted: u32,
    },
    /// A long name's slots are not filled as the format fills them: a name shorter than its
    /// entries ends in one zero unit and is padded with `0xFFFF` after it (documented).
    ///
    /// A name with no zero before its padding, or with something other than padding after
    /// its zero, reads all the same: the name ends at the first of the two values, and the
    /// rest is bytes nothing reads. The pinned `fsck.fat` accepts both (observed).
    #[error("the long name ending at entry {index} is not padded the way the format pads one")]
    #[non_exhaustive]
    LongNamePadding {
        /// The entry the run ended at.
        index: u32,
    },
    /// A structure names a cluster the volume does not have.
    #[error("cluster {cluster} is not a cluster this volume has")]
    #[non_exhaustive]
    ClusterOutOfRange {
        /// The cluster named.
        cluster: u32,
    },
    /// A structure names a sector past the volume's own sector count.
    #[error("sector {sector} is past the volume's {total_sectors} sectors")]
    #[non_exhaustive]
    SectorOutOfRange {
        /// The first sector the read would have needed.
        sector: u32,
        /// The sectors the volume describes.
        total_sectors: u32,
    },
    /// A long name holds more UTF-16 units than the format defines for one.
    ///
    /// Twenty entries of thirteen units can carry 260, and the format caps a name at 255 —
    /// this crate's own writer refuses a longer one. The name is still read, so the tree
    /// stays enumerable under a lenient read; what could not happen is writing the name
    /// back to a volume of this family.
    #[error(
        "the long name ending at entry {index} holds {units} UTF-16 units, past the format's 255"
    )]
    #[non_exhaustive]
    LongNameTooLong {
        /// The entry the run ended at.
        index: u32,
        /// The units the run holds.
        units: usize,
    },
    /// A chain's table entry holds a value no chain may contain: free, reserved, or the
    /// bad-cluster mark.
    #[error("the table entry for cluster {cluster} is {entry:#x}, which no chain may contain")]
    #[non_exhaustive]
    BadChainEntry {
        /// The cluster whose entry was read.
        cluster: u32,
        /// The value found there.
        entry: u32,
    },
    /// A chain did not end within the clusters the volume has, so it repeats one.
    #[error("the chain from cluster {start} does not end within the volume's {clusters} clusters")]
    #[non_exhaustive]
    ChainTooLong {
        /// The chain's first cluster.
        start: u32,
        /// Clusters the volume has, which bounds any chain in it.
        clusters: u32,
    },
    /// A chain ended before the length the entry that owns it records.
    ///
    /// FAT has no sparse files: a length is a claim about clusters, and a chain that stops
    /// short means the length and the allocation disagree. Handing back a short buffer would
    /// report success for a file that is not all there.
    #[error("a chain from cluster {start} ends before byte {read} of the {size} its entry records")]
    #[non_exhaustive]
    ChainTooShort {
        /// The chain's first cluster.
        start: u32,
        /// The length the directory entry records.
        size: u64,
        /// The file byte offset the read required and the chain ends before. A read from
        /// an offset reports the offset it needed, not a walk of the whole chain — the
        /// chain may end earlier still.
        read: u64,
    },
    /// A copy of the file allocation table differs from the first.
    ///
    /// FAT carries no checksums, and the mirror is what stands in for one: two copies of an
    /// allocation record that disagree mean at least one of them is wrong and nothing in the
    /// volume says which.
    #[error(
        "file allocation table {copy} holds {other:#x} for cluster {cluster} where table 0 \
         holds {first:#x}"
    )]
    #[non_exhaustive]
    TableMismatch {
        /// Which copy differs, counting from zero.
        copy: u32,
        /// The cluster whose entry differs.
        cluster: u32,
        /// What the first table holds.
        first: u32,
        /// What this copy holds.
        other: u32,
    },
    /// A copy of the file allocation table differs from the first beyond its last entry.
    ///
    /// The bytes past the entry for the last cluster address nothing, so a difference there
    /// misallocates nothing — it is a formatter's padding rather than an allocation record.
    #[error("file allocation table {copy} differs from table 0 in the padding past its last entry")]
    #[non_exhaustive]
    TablePaddingMismatch {
        /// Which copy differs, counting from zero.
        copy: u32,
    },
    /// A reserved entry of the file allocation table does not hold the value the format
    /// defines for it.
    ///
    /// Entry 1's two status bits are not compared here: clearing one is how a driver records
    /// a state, which is [`VolumeDirty`](Self::VolumeDirty) or
    /// [`MediaFailure`](Self::MediaFailure). This is for a value no driver writes.
    #[error("table entry {index} is {found:#x} where the format defines {expected:#x}")]
    #[non_exhaustive]
    BadReservedEntry {
        /// The entry's index: 0 carries the media descriptor, 1 the status bits.
        index: u32,
        /// The value found.
        found: u32,
        /// The value the format defines.
        expected: u32,
    },
    /// The volume was not cleanly unmounted: a driver had it mounted and did not put it down.
    ///
    /// A FAT volume records this in either of two places, and either is reported here, once.
    /// The FAT specification defines a clean-shutdown bit in table entry 1 on FAT16 and FAT32,
    /// which a driver clears. A Linux driver sets bit 0 of the boot sector's reserved byte,
    /// [`VolumeInfo::reserved`](super::ondisk::VolumeInfo::reserved), while it has the volume
    /// mounted, and leaves the table alone (observed).
    ///
    /// The volume is well-formed either way — the record is the format working rather than
    /// failing — so it is [`Severity::Cosmetic`] and a strict read is unaffected by it.
    #[error("{}", crate::finding::NOT_CLEANLY_UNMOUNTED)]
    VolumeDirty,
    /// A driver recorded a failure of the medium the volume is on, by clearing the hard-error
    /// bit the FAT specification defines in table entry 1 on FAT16 and FAT32.
    #[error("{}", crate::finding::MEDIUM_FAILURE)]
    MediaFailure,
    /// The backup boot sector is not a copy of sector 0.
    ///
    /// It exists to be used when sector 0 cannot be read, so a copy that has drifted is
    /// worse than none: it would restore a geometry the volume does not have.
    #[error("the backup boot sector at sector {sector} is not a copy of sector 0")]
    #[non_exhaustive]
    BackupBootSectorDiffers {
        /// Where the backup sits.
        sector: u32,
    },
    /// The sector the parameter block points at as the information sector is not one.
    #[error("sector {sector} is named as the information sector and does not hold one")]
    #[non_exhaustive]
    BadInfoSector {
        /// Where the parameter block said to look.
        sector: u32,
    },
    /// A run of long-name entries does not belong to the entry that follows it: the
    /// checksum over the short name does not match.
    ///
    /// This is what stops a driver without long-name support from orphaning a name onto the
    /// wrong file, so a mismatch means the long name describes some file that is no longer
    /// there. The short name is what the entry is then read under.
    #[error(
        "the long name before entry {index} checksums to {found:#04x} and its short name to \
         {expected:#04x}"
    )]
    #[non_exhaustive]
    LongNameChecksum {
        /// The short entry's index within its directory.
        index: u32,
        /// The checksum the long-name entries carry.
        found: u8,
        /// The checksum of the short name they precede.
        expected: u8,
    },
    /// A run of long-name entries is not followed by the short entry it belongs to, or its
    /// ordinals do not run down to one without a gap.
    #[error("the long-name entries ending at entry {index} do not form a complete run")]
    #[non_exhaustive]
    OrphanedLongName {
        /// Where the run ended.
        index: u32,
    },
    /// A long name's code units are not well-formed UTF-16: it carries a surrogate with no
    /// partner, which stands for no character.
    ///
    /// The name is still read, with each such unit replaced by U+FFFD, so a tree carrying
    /// one is still enumerable under a lenient read.
    #[error("the long name at entry {index} is not well-formed UTF-16")]
    #[non_exhaustive]
    IllFormedLongName {
        /// The short entry's index within its directory.
        index: u32,
    },
    /// One of an entry's three times holds a value the encoding does not define.
    ///
    /// A month of zero, a day of 31 in February, a twenty-fifth hour, or a hundredths byte
    /// past 199. A read reports the instant the arithmetic reaches, which is what every driver
    /// does; this is the judgment that says the field was never an instant.
    ///
    /// The creation and access times are the format's optional ones, and a wholly zero field
    /// is how it records that they were not kept — so a zero field is not reported. Nothing
    /// short of the whole field is that record: a date of zero beside a time that is not is a
    /// field that was written and not a field that was skipped.
    #[error("the {field} at entry {index} holds a value the encoding does not define")]
    #[non_exhaustive]
    MalformedTimestamp {
        /// The entry's index within its directory.
        index: u32,
        /// Which of the three times, in the format's own words.
        field: &'static str,
    },
    /// A short name carries a byte above ASCII and no code page was named, so what
    /// character it stands for is not something the volume records.
    ///
    /// Name a [`ShortNameCharset`] to interpret it. The name is still read under a lenient
    /// policy, with its bytes exactly as they sit on disk.
    #[error(
        "the short name at entry {index} carries byte {byte:#04x}, above ASCII, and this \
         volume records no code page; name one to interpret it"
    )]
    #[non_exhaustive]
    UninterpretedShortName {
        /// The entry's index within its directory.
        index: u32,
        /// The first byte above ASCII in the name.
        byte: u8,
    },
    /// An entry's name is one no directory can hold: `.` or `..`, or a name carrying a path
    /// separator or a NUL.
    ///
    /// The first two name a directory rather than something inside it, a separator would
    /// traverse out of the tree, and a NUL would truncate the path a consumer forms from the
    /// name. Neither field a name arrives in rules one out: a long name is UTF-16 and can
    /// encode any of them, and a short name is eleven bytes an image chooses. The format
    /// reserves a wider set in both, which [`ReservedCharacter`](Self::ReservedCharacter)
    /// reports; these four are the ones no directory can hold whatever its format says, and
    /// so the ones never handed back.
    ///
    /// The name itself is not repeated in the message. It is the image's, an image is
    /// untrusted input, and a name built to be one a directory cannot hold is equally free to
    /// carry the control bytes that would rewrite the line it is printed on.
    #[error("the name at entry {index} is one no directory can hold")]
    #[non_exhaustive]
    HostileName {
        /// The entry's index within its directory, counting 32-byte slots from zero.
        index: u32,
    },
    /// An entry's name carries a character the format reserves in it (documented, FAT
    /// specification 1.03).
    ///
    /// A long name may not hold a control code or `" * / : < > ? \ |`, the set this crate's
    /// writer refuses in a name. A short name's field may not hold those, `+ , . ; = [ ]`, or
    /// 0x7F, nor begin with a space; 0x05 in its first byte stands for 0xE5 and is not one.
    /// The writer substitutes an underscore for each in the short names it derives. The name
    /// is still read and, where the policy allows, handed back as it is stored.
    #[error(
        "the {field} name at entry {index} carries {code:#06x}, a character the format \
         reserves in it"
    )]
    #[non_exhaustive]
    ReservedCharacter {
        /// The entry's index within its directory.
        index: u32,
        /// `long` or `short`: which of the entry's names carries it.
        field: &'static str,
        /// The character: a UTF-16 code point in a long name, a byte in a short one.
        code: u32,
    },
    /// Two entries of one directory carry names no driver tells apart: equal once their case
    /// is folded, whether long names, short names, or one entry's long name and another's
    /// short name — every driver matches a lookup against both.
    ///
    /// A lookup reaches the first of the two, and the second cannot be reached by its own
    /// name. This crate's writer refuses such a pair; a driver creating a file looks the name
    /// up first and cannot write one.
    #[error(
        "entry {index} carries a name entry {first} carries too, once case is folded, so a \
         lookup reaches only the first"
    )]
    #[non_exhaustive]
    IndistinguishableNames {
        /// The entry's index within its directory.
        index: u32,
        /// The index of the earlier entry it cannot be told from.
        first: u32,
    },
    /// A directory entry names a directory the tree already reaches by another name, or one
    /// of its own ancestors: two entries share the cluster a directory begins at. A FAT
    /// directory has one name, so the volume contradicts itself. A walk never descends into
    /// such a directory twice; a strict read refuses the volume for it, and a lenient one
    /// passes the repeat over.
    #[error(
        "a directory entry names the directory at cluster {cluster}, which the tree reaches \
         by another name as well"
    )]
    #[non_exhaustive]
    RepeatedDirectory {
        /// The first cluster both names lead to.
        cluster: u32,
    },
    /// An entry records a length and no first cluster.
    ///
    /// FAT has no holes — a file's bytes are its chain — so a length is a claim about clusters
    /// and a first cluster of zero says there are none. An entry making both claims describes
    /// contents no read can reach, and the incoherence surfaces halfway through an extraction
    /// rather than at the entry that carries it.
    #[error("the entry at {index} records {size} bytes and no first cluster")]
    #[non_exhaustive]
    SizeWithoutAllocation {
        /// The entry's index within its directory.
        index: u32,
        /// The length the directory entry records.
        size: u32,
    },
    /// A subdirectory's `.` or `..` entry is missing or is not the entry the format puts
    /// there, or a dot entry sits where the format puts none.
    ///
    /// The format puts the two in a subdirectory's first two slots, named in the short-name
    /// field, carrying the directory attribute, and nowhere else — the root holds neither
    /// (documented). The pinned `fsck.fat` repairs each departure (observed). A dot entry
    /// anywhere else is still not an entry of the directory: it is passed over, as every dot
    /// entry is, and reported.
    #[error("{detail}")]
    #[non_exhaustive]
    BadDotEntry {
        /// What is wrong with it.
        detail: String,
    },
    /// A subdirectory's `.` or `..` entry names a cluster other than the one the format
    /// requires: the directory's own first cluster for `.`, and its parent's for `..`, or zero
    /// where the parent is the root (documented, on FAT32 as well).
    ///
    /// The entry and the tree it sits in disagree about where a directory is, which is what
    /// a directory moved without its `..` rewritten looks like. The pinned `fsck.fat` repairs
    /// it (observed), the high half of a FAT32 cluster number included.
    #[error(
        "{}the `{name}` entry names cluster {found} where the format requires {expected}",
        if path.is_empty() { String::new() } else { format!("{}: ", crate::escape::printable(path)) }
    )]
    #[non_exhaustive]
    DotEntryTarget {
        /// The directory's path, or empty where the read does not know it.
        path: Vec<u8>,
        /// `.` or `..`.
        name: &'static str,
        /// The cluster the entry names.
        found: u32,
        /// The cluster the format requires it to name.
        expected: u32,
    },
    /// A directory holds entries after the one that marks its end, which no reader will
    /// reach.
    #[error("directory entry {index} follows the end marker and no reader reaches it")]
    #[non_exhaustive]
    EntriesAfterEnd {
        /// The index of the first entry past the marker.
        index: u32,
    },
    /// A directory is larger than the format lets one be.
    ///
    /// The bound is [`MAX_DIRECTORY_BYTES`], on the directory's
    /// own size, so its first slot past the bound is the finding whatever that slot holds. A
    /// driver following the format grows no directory past it, and a directory that has been
    /// grown past it reads whole, as a Linux kernel reads it (observed).
    #[error(
        "the directory reaches entry {index}, past the {limit} bytes the format lets one \
         directory be"
    )]
    #[non_exhaustive]
    DirectoryTooLong {
        /// The index of the first entry past the bound.
        index: u32,
        /// [`MAX_DIRECTORY_BYTES`].
        limit: u64,
    },
    /// A volume label entry sits somewhere other than the root directory, where it is the
    /// one place the format defines for it.
    #[error("a volume label entry sits at entry {index} of a directory that is not the root")]
    #[non_exhaustive]
    MisplacedVolumeLabel {
        /// The entry's index within its directory.
        index: u32,
    },
    /// Clusters are marked allocated in the file allocation table and no chain reaches
    /// them, so the space is spent and holds nothing a reader can find.
    #[error("{count} clusters are allocated and reached by no chain, the first at {first}")]
    #[non_exhaustive]
    LostClusters {
        /// How many.
        count: u32,
        /// The lowest-numbered one.
        first: u32,
    },
    /// A path names nothing in the volume.
    #[error("no such path: {}", crate::escape::printable(.path))]
    #[non_exhaustive]
    NotFound {
        /// The path as given.
        path: Vec<u8>,
    },
    /// A path traverses through something that is not a directory.
    #[error("not a directory: {}", crate::escape::printable(.path))]
    #[non_exhaustive]
    NotADirectory {
        /// The path as given.
        path: Vec<u8>,
    },
    /// A whole-file read would exceed [`Limits::max_file_bytes`].
    #[error("a file of {size} bytes exceeds the {limit}-byte read limit")]
    #[non_exhaustive]
    FileTooLarge {
        /// The length the entry records.
        size: u64,
        /// The limit in force.
        limit: u64,
    },
    /// A walk reached a name whose path is longer than the longest a walk builds, 4,096
    /// bytes, which is Linux's `PATH_MAX`.
    ///
    /// Nothing in either format bounds how deep a tree nests, and a walk's entry cap counts
    /// *names* rather than the bytes their paths occupy — so a caterpillar tree of sixty-five
    /// thousand directories, each holding one entry naming the next, stays under every count
    /// while its paths grow by one component each and cost the walk their sum. A 32 MiB
    /// volume reaches tens of gigabytes of path bytes that way. A walk hands out every name's
    /// whole path, so it holds each to this bound.
    ///
    /// The tree is well-formed, so this is a limit rather than damage: the shared surface
    /// reports it as [`TreeError::LimitExceeded`] with [`Bound::PathBytes`], and a
    /// [`scan`](Reader::scan) reads the tree whole.
    #[error("a walked path is longer than the {limit} bytes a walk builds")]
    #[non_exhaustive]
    PathTooLong {
        /// The longest path a walk builds.
        limit: usize,
    },
    /// A whole-tree walk would gather more names than the bounds allow.
    #[error("the tree holds more than {limit} names")]
    #[non_exhaustive]
    WalkTooLarge {
        /// The bound that applied.
        limit: usize,
    },
}

crate::io::io_error!(ReadError);

impl ReadError {
    /// How this failure classifies as a deviation from what this crate emits.
    ///
    /// Every variant answers, so a scan describes a fault exactly as a strict read would
    /// have. A source that failed a read for a reason other than ending is not the image's,
    /// and files under [`Category::Source`], which a scan holds apart from its findings. A
    /// caller's own bound is not the image's either, and classifies as
    /// [`Severity::Structural`] all the same: from a scan's point of view the volume could
    /// not be followed past that point.
    #[must_use]
    pub fn anomaly(&self) -> Anomaly {
        let at = |sector: Option<u32>, cluster: Option<u32>, entry: Option<u32>| Location {
            sector,
            cluster,
            entry,
        };
        let (severity, category, location) = match self {
            ReadError::Io {
                kind: std::io::ErrorKind::UnexpectedEof,
                ..
            } => (
                Severity::Structural,
                Category::BootSector,
                Location::default(),
            ),
            ReadError::Io { .. } => (Severity::Structural, Category::Source, Location::default()),
            ReadError::Parse(_) | ReadError::BadBootSector { .. } => (
                Severity::Structural,
                Category::BootSector,
                at(Some(0), None, None),
            ),
            // Valid, and read the way the specification and Linux read it — but a volume no
            // formatter should write, because the other mainstream driver reads it
            // differently.
            ReadError::AmbiguousClusterCount { .. } => (
                Severity::Conformance,
                Category::BootSector,
                at(Some(0), None, None),
            ),
            // Readable here and outside what the format's guidance covers.
            ReadError::LargeCluster { .. } => (
                Severity::Cosmetic,
                Category::BootSector,
                at(Some(0), None, None),
            ),
            // A field nothing reads for a directory, and bytes nothing reads after a name.
            ReadError::DirectoryWithSize { index, .. } | ReadError::LongNamePadding { index } => (
                Severity::Cosmetic,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            ReadError::LabelWithDirectoryAttribute { index }
            | ReadError::SecondVolumeLabel { index }
            | ReadError::LabelBeginsWithSpace { index } => (
                Severity::Conformance,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            // A hint, stale, against a value the field cannot hold: exFAT's fullness is graded
            // the same pair of ways.
            ReadError::FreeCountStale { .. } => (
                Severity::Cosmetic,
                Category::InfoSector,
                Location::default(),
            ),
            ReadError::FreeCountOutOfRange { .. } => (
                Severity::Conformance,
                Category::InfoSector,
                Location::default(),
            ),
            ReadError::ClusterOutOfRange { cluster } => (
                Severity::Structural,
                Category::AllocationTable,
                at(None, Some(*cluster), None),
            ),
            ReadError::SectorOutOfRange { sector, .. } => (
                Severity::Structural,
                Category::BootSector,
                at(Some(*sector), None, None),
            ),
            ReadError::BadChainEntry { cluster, .. } => (
                Severity::Structural,
                Category::AllocationTable,
                at(None, Some(*cluster), None),
            ),
            ReadError::ChainTooLong { start, .. } | ReadError::ChainTooShort { start, .. } => (
                Severity::Structural,
                Category::AllocationTable,
                at(None, Some(*start), None),
            ),
            // The mirror is what a FAT volume has instead of a checksum, so two copies that
            // disagree are self-inconsistent bytes rather than a matter of form.
            ReadError::TableMismatch { cluster, .. } => (
                Severity::Integrity,
                Category::AllocationTable,
                at(None, Some(*cluster), None),
            ),
            ReadError::TablePaddingMismatch { .. } => (
                Severity::Cosmetic,
                Category::AllocationTable,
                Location::default(),
            ),
            ReadError::BadReservedEntry { index, .. } => (
                Severity::Conformance,
                Category::AllocationTable,
                at(None, Some(*index), None),
            ),
            // A state a driver left the volume in: the format recording it rather than
            // departing from it, so the volume is well-formed and a strict read carries on.
            // Each is filed where it is recorded — the dirty state where a Linux driver keeps
            // it, the medium failure in the one entry that holds it.
            ReadError::VolumeDirty => (
                Severity::Cosmetic,
                Category::BootSector,
                at(Some(0), None, None),
            ),
            ReadError::MediaFailure => (
                Severity::Cosmetic,
                Category::AllocationTable,
                at(None, Some(1), None),
            ),
            ReadError::BackupBootSectorDiffers { sector } => (
                Severity::Conformance,
                Category::BootSector,
                at(Some(*sector), None, None),
            ),
            ReadError::BadInfoSector { sector } => (
                Severity::Conformance,
                Category::InfoSector,
                at(Some(*sector), None, None),
            ),
            ReadError::LongNameChecksum { index, .. } | ReadError::OrphanedLongName { index } => (
                Severity::Integrity,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            // The name reads back whole and unambiguously; what it violates is the
            // format's own cap, which is a matter of conformance rather than of damage.
            ReadError::LongNameTooLong { index, .. } => (
                Severity::Conformance,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            // A name a directory cannot hold is not a matter of form: no driver creates one
            // and this crate's writer refuses one, so an entry carrying it describes a tree
            // that does not exist rather than one written to a different convention.
            //
            // A length with no clusters behind it is the same kind of fault one field along:
            // an entry describing bytes that are not there.
            ReadError::HostileName { index } | ReadError::SizeWithoutAllocation { index, .. } => (
                Severity::Structural,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            // Two names for one directory: every entry parses, and the entries disagree about
            // the tree they make.
            ReadError::RepeatedDirectory { cluster } => (
                Severity::Integrity,
                Category::Directory,
                at(None, Some(*cluster), None),
            ),
            // Two names a lookup cannot tell apart: every entry parses, and the directory
            // answers one name with two entries.
            ReadError::IndistinguishableNames { index, .. } => (
                Severity::Integrity,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            ReadError::IllFormedLongName { index }
            | ReadError::ReservedCharacter { index, .. }
            | ReadError::UninterpretedShortName { index, .. }
            | ReadError::EntriesAfterEnd { index }
            // Read whole, as a driver reads it, and larger than the format lets a driver grow
            // one.
            | ReadError::DirectoryTooLong { index, .. }
            // A recovered field outside the range the format states for it. The entry reads
            // back whole and one field of it means nothing.
            | ReadError::MalformedTimestamp { index, .. }
            | ReadError::MisplacedVolumeLabel { index } => (
                Severity::Conformance,
                Category::Directory,
                at(None, None, Some(*index)),
            ),
            ReadError::BadDotEntry { .. } => (
                Severity::Conformance,
                Category::Directory,
                Location::default(),
            ),
            // The entry and the tree disagree about where a directory is, as two names for
            // one directory do.
            ReadError::DotEntryTarget { .. } => (
                Severity::Integrity,
                Category::Directory,
                Location::default(),
            ),
            ReadError::LostClusters { first, .. } => (
                Severity::Conformance,
                Category::AllocationTable,
                at(None, Some(*first), None),
            ),
            ReadError::NotFound { .. } | ReadError::NotADirectory { .. } => (
                Severity::Structural,
                Category::Directory,
                Location::default(),
            ),
            ReadError::FileTooLarge { .. }
            | ReadError::PathTooLong { .. }
            | ReadError::WalkTooLarge { .. } => (
                Severity::Structural,
                Category::Directory,
                Location::default(),
            ),
        };
        Anomaly {
            severity,
            category,
            location,
            detail: self.to_string(),
        }
    }
}

/// The FAT family's half of the shared path resolution: a directory listing to find a name in,
/// matched the way a driver matches one.
///
/// The link half of the trait is defaulted, because the format has none: an entry is a file, a
/// directory, or the volume label, and a path through this volume goes exactly where its
/// components say.
impl<R: Read + Seek> crate::resolve::Resolve for Reader<R> {
    /// The node itself. There is nothing to re-read on the way back up: a FAT [`Node`] is four
    /// fixed-size fields, so a locator would cost as much as the node — the same reason the
    /// walk's frontier holds one.
    type Ancestor = Node;
    type Node = Node;
    type Error = ReadError;

    fn root_node(&mut self) -> Result<Node, ReadError> {
        Ok(self.root())
    }

    fn ancestor_of(&self, node: &Node) -> Node {
        *node
    }

    fn node_at(&mut self, ancestor: Node) -> Result<Node, ReadError> {
        Ok(ancestor)
    }

    fn is_directory(&self, node: &Node) -> bool {
        node.is_dir()
    }

    fn find_name(&mut self, dir: &Node, name: &[u8]) -> Result<Option<Node>, ReadError> {
        // An entry answers to its short name as well as to its long one: the 8.3 alias is a
        // name the volume holds for it, and the one a short-name consumer knows it by.
        //
        // The directory is streamed, as ext's is, and nothing is gathered: an exact match on
        // a long name ends the read where it is, so neither the walk's cap nor an entry past
        // the match can fail a lookup that found its name. Every weaker match is remembered,
        // the first of each kind, in case nothing stronger follows — an exact alias, then a
        // case-folded long name, then a case-folded alias — which is the one case that reads
        // on to the end. A directory a driver wrote holds no name that is another entry's
        // alias, so the order decides nothing there; it is what keeps an exact match ahead
        // of a folded one, and a long name ahead of a short one, in a directory that does.
        let policy = self.policy;
        let mut exact = None;
        let mut exact_alias = None;
        let mut folded = None;
        let mut folded_alias = None;
        self.parse_entries(
            dir,
            Placement::UNKNOWN,
            &mut OnDeviation::Policy(policy),
            |_, e, _| {
                if e.name == name {
                    exact = Some(e.node);
                    return Ok(ControlFlow::Break(()));
                }
                if exact_alias.is_none() && e.short_name == name {
                    exact_alias = Some(e.node);
                }
                if folded.is_none() && e.name.eq_ignore_ascii_case(name) {
                    folded = Some(e.node);
                }
                if folded_alias.is_none() && e.short_name.eq_ignore_ascii_case(name) {
                    folded_alias = Some(e.node);
                }
                Ok(ControlFlow::Continue(()))
            },
        )?;
        Ok(exact.or(exact_alias).or(folded).or(folded_alias))
    }

    fn not_found(&self, path: &[u8]) -> ReadError {
        ReadError::NotFound {
            path: path.to_vec(),
        }
    }

    fn not_a_directory(&self, _node: &Node, path: &[u8]) -> ReadError {
        ReadError::NotADirectory {
            path: path.to_vec(),
        }
    }
}

/// A walk entry beside what its `..` must name, which the entry itself does not say: the first
/// cluster of the directory it was listed in, or zero where that is the root.
pub(crate) struct Placed {
    entry: WalkEntry,
    parent: u32,
}

/// The FAT family's half of the shared walk: a resolved entry on the frontier, a first
/// cluster as the cycle key, and a directory listing as the children.
impl<R: Read + Seek> crate::walk::Walk for Reader<R> {
    /// A whole entry and its parent. Unlike the ext family, there is nothing to re-read at
    /// the pop: a FAT [`Node`] is four fixed-size fields, so a locator would cost as much as
    /// the node.
    type Pending = Placed;
    type Entry = Placed;
    /// The directory's first cluster. The root region has none and is entered once by
    /// construction, so it needs no key.
    type Key = u32;
    type Error = ReadError;

    fn cap(&mut self) -> usize {
        self.limits.max_walk_entries.min(self.max_names())
    }

    fn seed(&mut self) -> Result<crate::walk::Seed<Self>, ReadError> {
        let root = self.root();
        let occupied = match root.storage {
            Storage::Chain(start) => vec![start],
            Storage::None | Storage::RootRegion => Vec::new(),
        };
        Ok((self.walk_children(&root, &[], None)?, occupied))
    }

    fn resolve(&mut self, pending: Placed) -> Result<Placed, ReadError> {
        Ok(pending)
    }

    fn descend_key(&self, placed: &Placed) -> Option<u32> {
        let entry = &placed.entry;
        if !entry.node.is_dir() {
            return None;
        }
        match entry.node.storage {
            Storage::Chain(start) => Some(start),
            // A directory entry naming no cluster has no storage to descend into.
            Storage::None | Storage::RootRegion => None,
        }
    }

    fn children(&mut self, placed: &Placed) -> Result<Vec<Placed>, ReadError> {
        self.walk_children(&placed.entry.node, &placed.entry.path, Some(placed.parent))
    }

    fn repeated(&mut self, placed: &Placed) -> Result<(), ReadError> {
        let Storage::Chain(cluster) = placed.entry.node.storage else {
            return Ok(());
        };
        let err = ReadError::RepeatedDirectory { cluster };
        if self.policy.is_fatal(err.anomaly().severity) {
            return Err(err);
        }
        Ok(())
    }

    fn too_large(limit: usize) -> ReadError {
        ReadError::WalkTooLarge { limit }
    }
}

/// How a read failure classifies in the crate's family-agnostic frame.
impl From<ReadError> for TreeError {
    fn from(err: ReadError) -> Self {
        match err {
            ReadError::Io { kind, message } => TreeError::Io { kind, message },
            ReadError::FileTooLarge { .. } => TreeError::limit(Family::Fat, Bound::FileBytes, &err),
            ReadError::PathTooLong { .. } => TreeError::limit(Family::Fat, Bound::PathBytes, &err),
            ReadError::WalkTooLarge { .. } => TreeError::limit(Family::Fat, Bound::Entries, &err),
            other => TreeError::Malformed {
                family: Family::Fat,
                detail: other.to_string(),
            },
        }
    }
}

/// What a whole-volume [`scan`](Reader::scan) found, in FAT's own taxonomy.
///
/// This is the crate's [`ScanReport`](crate::ScanReport) over FAT's [`Anomaly`]: an anomaly
/// names the subsystem as a [`Category`] value and its place as a [`Location`] of cluster,
/// sector, and entry, which is what a consumer reasoning about a FAT volume wants. The
/// addressing unit is the volume's sector size, so a sector-addressed anomaly projects to the
/// byte offset that sector sits at.
pub type ScanReport = crate::ScanReport<Anomaly>;

/// Where a node's bytes are.
///
/// The domain is closed and the type is exhaustive: a FAT node's storage is a chain, or the
/// one fixed region a FAT12 or FAT16 volume reserves for its root, or nothing at all. There
/// is no fourth, and a fifth arriving *should* break a caller that switches on it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Storage {
    /// The node owns no cluster: an empty file, whose entry records a first cluster of zero.
    None,
    /// A cluster chain beginning at this cluster.
    Chain(u32),
    /// The fixed-capacity root directory region of a FAT12 or FAT16 volume, which is not a
    /// chain and has no entry in the file allocation table.
    RootRegion,
}

/// The three times a directory entry records.
///
/// The root directory has none — the format stores no entry for it on any type — which is
/// why [`Node::times`] is an [`Option`] rather than three fields that would have to hold
/// something invented.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Times {
    /// When the entry was created, to ten milliseconds, or `None` where the entry's creation
    /// field is wholly zero, which is how the format records a time not kept.
    pub create: Option<Timestamp>,
    /// When it was last accessed, or `None` where the entry's access date is zero, which is
    /// how the format records a date not kept — the same rule the creation field follows. The
    /// format stores a date and no time of day, so a date kept is always midnight UTC.
    pub access: Option<Timestamp>,
    /// When it was last written, to two seconds.
    pub modify: Timestamp,
}

/// A handle to one node: where its bytes are, what it is, how long it is, and when.
///
/// This is what a walk hands back and what every by-node operation takes. There is no
/// number in it, and deliberately: FAT has no inodes, so there is nothing that distinguishes
/// a file from a second name for it — the format has no second names.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Node {
    /// Where the node's bytes are.
    pub storage: Storage,
    /// The entry's attribute byte.
    pub attributes: DirAttributes,
    /// The length the entry records, in bytes. Zero for a directory, whose length is
    /// however many clusters its chain holds.
    pub size: u32,
    /// The times the entry records, or `None` for the root directory, which has no entry.
    pub times: Option<Times>,
}

impl Node {
    /// Whether the node is a directory.
    #[must_use]
    pub const fn is_dir(&self) -> bool {
        self.attributes.contains(DirAttributes::DIRECTORY)
            || matches!(self.storage, Storage::RootRegion)
    }

    /// Whether the node is the volume label rather than a file or a directory.
    #[must_use]
    pub const fn is_volume_label(&self) -> bool {
        !self.attributes.contains(DirAttributes::DIRECTORY)
            && self.attributes.contains(DirAttributes::VOLUME_ID)
    }
}

/// One resolved directory entry: the name it is found under, the short name it always has,
/// and a handle to what it points at.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Entry {
    /// The name the entry is found under: the long name where it has one, and otherwise the
    /// short name rendered with its dot.
    ///
    /// Always a name a directory can hold. An entry whose name resolves to `.` or `..`, or
    /// carries a path separator or a NUL, is [`HostileName`](ReadError::HostileName) rather
    /// than an [`Entry`], so a path built by joining this onto its directory's stays inside
    /// the tree.
    pub name: Vec<u8>,
    /// The short name, always, rendered with its dot and with the padding trimmed.
    ///
    /// Kept beside the name because the two differing is an observable fact about the volume
    /// rather than an implementation detail: a foreign tool listing the tree shows both
    /// columns, and a name that is already its own short name shows one of them empty.
    ///
    /// **The safety promise above belongs to [`name`](Self::name) alone.** This field shows
    /// the stored bytes, and where a long name is what the entry is found under, these
    /// eleven bytes go unchecked: a crafted volume can put a path separator, a NUL, or a
    /// dot-name here beside a clean long name. Build paths from `name`; treat this as a
    /// display column.
    ///
    /// A byte above ASCII here is not itself a deviation. What
    /// [`UninterpretedShortName`](ReadError::UninterpretedShortName) is about is a name the
    /// reader cannot say the meaning of and is handing back as the name anyway — so it
    /// applies where these eleven bytes *are* [`name`](Self::name), and not where a long
    /// name, which is UTF-16 and unambiguous, is what the entry is found under. A short name
    /// beside a long one is a legacy second record of it.
    pub short_name: Vec<u8>,
    /// Whether the name came from long-name entries rather than from the short name field.
    pub has_long_name: bool,
    /// A handle to what the entry points at.
    pub node: Node,
}

/// One name a [`walk`](Reader::walk) reached: its path, and a handle to what is there.
///
/// There is no number beside the path, unlike the ext family's walk: FAT has no second name
/// for a node, so a path and a node are the same thing and nothing has to distinguish them.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct WalkEntry {
    /// Absolute path from the volume root, `/`-joined, always beginning with `/`.
    pub path: Vec<u8>,
    /// A handle to what is at the path.
    pub node: Node,
}

/// How a FAT volume is opened: where it begins, how strictly it is read, what it may
/// allocate, and how the bytes of a short name above ASCII are interpreted.
///
/// Every input to [`Reader::open_with`] is a field here rather than a parameter, so a knob
/// the reader grows arrives as a field a caller may ignore.
///
/// The first three are the crate's family-agnostic [`OpenOptions`](crate::OpenOptions) and
/// mean exactly what they mean there. The fourth is why this type exists: a FAT volume
/// records no code page for its short names, and no other family has that question.
///
/// ```
/// # use ferrosys::fat::{OpenOptions, ShortNameCharset};
/// # use ferrosys::ReadPolicy;
/// // A volume inside a partition, read leniently so a scan can describe what is wrong with
/// // it rather than the open refusing it, with its short names read as code page 437.
/// let options = OpenOptions::new()
///     .base(1 << 20)
///     .policy(ReadPolicy::Lenient)
///     .charset(ShortNameCharset::Cp437);
/// # let _ = options;
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct OpenOptions {
    /// Where the volume begins, how strictly it is read, and what one read may allocate —
    /// the crate's [`OpenOptions`](crate::OpenOptions), which mean exactly what they mean
    /// there.
    ///
    /// Held rather than flattened, so an input every family takes is added in one place and
    /// reaches every family at once. The three builders below set through it, so a caller
    /// writes `OpenOptions::new().base(..)` either way.
    pub common: crate::OpenOptions,
    /// How the bytes of a short name above ASCII are interpreted. Defaults to
    /// [`ShortNameCharset::Verbatim`], which interprets nothing.
    ///
    /// Naming a page is a claim the caller is making: the volume does not record one, and
    /// there is no field or heuristic that recovers it. What naming one *does* change is the
    /// severity of meeting such a byte — unrecognized bytes are a conformance deviation and
    /// a strict read stops at them, while bytes the caller has said how to read are a
    /// cosmetic remark and a strict read carries on.
    pub charset: ShortNameCharset,
}

impl OpenOptions {
    /// Open at the start of the source, strictly, with the default limits, interpreting no
    /// byte of a short name.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            common: crate::OpenOptions::new(),
            charset: ShortNameCharset::Verbatim,
        }
    }

    /// Open a volume that begins `base` bytes into the source.
    #[must_use]
    pub const fn base(mut self, base: u64) -> Self {
        self.common = self.common.base(base);
        self
    }

    /// Hold the filesystem to the `len` bytes from its base on.
    #[must_use]
    pub const fn len(mut self, len: u64) -> Self {
        self.common = self.common.len(len);
        self
    }

    /// Read under `policy`.
    #[must_use]
    pub const fn policy(mut self, policy: ReadPolicy) -> Self {
        self.common = self.common.policy(policy);
        self
    }

    /// Cap what one read may allocate.
    #[must_use]
    pub const fn limits(mut self, limits: Limits) -> Self {
        self.common = self.common.limits(limits);
        self
    }

    /// Take the shared inputs from `common`, leaving this family's own alone.
    #[must_use]
    pub const fn common(mut self, common: crate::OpenOptions) -> Self {
        self.common = common;
        self
    }

    /// Interpret the bytes of a short name above ASCII as `charset` gives them.
    #[must_use]
    pub const fn charset(mut self, charset: ShortNameCharset) -> Self {
        self.charset = charset;
        self
    }
}

/// A read-only handle over a FAT volume on any [`Read`] + [`Seek`] source.
///
/// The volume may sit at an arbitrary byte offset within the source — a partition inside a
/// whole-disk image — fixed at open time. Reads seek relative to that offset and return
/// owned buffers, so nothing is borrowed from the source between calls.
pub struct Reader<R> {
    /// The source, ending where the caller's region does.
    src: Bounded<R>,
    base: u64,
    boot: BootSector,
    layout: FatLayout,
    policy: ReadPolicy,
    limits: Limits,
    charset: ShortNameCharset,
    /// The deviations found while validating the parameter block, kept so a scan reports
    /// them without re-deriving the geometry and a lenient caller can see them without one.
    open_anomalies: Vec<Anomaly>,
    /// A two-sector window on the first file allocation table.
    ///
    /// Following a chain reads one entry at a time and the entries of a chain are usually
    /// near each other, so a window turns a walk of a large file from one seek per cluster
    /// into one per sector. Two sectors rather than one because a FAT12 entry may straddle
    /// the boundary between them. The image is read-only, so a cached window can never go
    /// stale.
    fat_window: Option<(u32, Vec<u8>)>,
    /// Whether the volume records that a driver did not put it down, read at open.
    volume_dirty: bool,
    /// Whether the volume records a failure of its medium, read at open.
    media_failure: bool,
    /// Where a chain walk left off: the chain's first cluster, the index within it, and the
    /// cluster at that index.
    ///
    /// A read at an offset has to skip to the cluster holding it, and skipping from the
    /// start every time makes a sequential read of one file quadratic in its length. Kept
    /// here so a read that continues where the last one stopped resumes rather than
    /// restarts.
    chain_cursor: Option<(u32, u64, u32)>,
}

/// What a directory parse does with a deviation it meets.
///
/// One parser serves both dispositions, which is what makes a scan describe a fault exactly
/// as the read that stops at it would have.
enum OnDeviation<'a> {
    /// An ordinary read: fatal under the policy, and otherwise passed over.
    Policy(ReadPolicy),
    /// A scan: every deviation collected, none fatal.
    Collect(&'a mut Findings<Anomaly>),
}

/// Where a directory sits in the tree, as far as the read that reaches it knows: what its `..`
/// entry must name, and the path a finding about it names.
///
/// A walk and a scan come to a directory from its parent and know both; a caller handing
/// [`Reader::read_dir`] a node, and a lookup, know neither, and a read there holds the dot
/// entries to everything the directory says about itself and nothing more.
#[derive(Clone, Copy)]
struct Placement<'p> {
    /// The parent's first cluster as a `..` entry records it — zero where the parent is the
    /// root — or `None` where the read did not come from the parent.
    parent: Option<u32>,
    /// The directory's path, or `None` where the read does not know it.
    path: Option<&'p [u8]>,
}

impl Placement<'_> {
    /// A directory reached without its parent.
    const UNKNOWN: Self = Self {
        parent: None,
        path: None,
    };
}

impl<'p> Placement<'p> {
    /// The directory at `path`, reached from a parent whose first cluster is `parent`.
    const fn at(path: &'p [u8], parent: u32) -> Self {
        Self {
            parent: Some(parent),
            path: Some(path),
        }
    }
}

/// The 11-byte name fields the format gives a subdirectory's first two entries, in slot order.
const DOT_NAMES: [&[u8; 11]; 2] = [b".          ", b"..         "];

impl OnDeviation<'_> {
    /// Record `err`, having happened at `at`. Returns it as an error where the policy in
    /// force makes it fatal.
    fn record(&mut self, at: Location, err: ReadError) -> Result<(), ReadError> {
        match self {
            OnDeviation::Policy(policy) => {
                if policy.is_fatal(err.anomaly().severity) {
                    Err(err)
                } else {
                    Ok(())
                }
            }
            OnDeviation::Collect(findings) => {
                let mut anomaly = err.anomaly();
                anomaly.location = anomaly.location.or(at);
                findings.push(anomaly);
                Ok(())
            }
        }
    }
}

impl<R: Read + Seek> Reader<R> {
    /// Open the FAT volume at the start of `src` under the default options.
    ///
    /// # Errors
    ///
    /// [`ReadError::BadBootSector`] when the parameter block does not describe a FAT volume,
    /// [`ReadError::Io`] when the source cannot be read, and — under
    /// [`ReadPolicy::Strict`] — whichever deviation the parameter block carries at a severity
    /// the policy is fatal at. A volume a driver left dirty is reported, not refused.
    pub fn open(src: R) -> Result<Self, ReadError> {
        Self::open_with(src, &OpenOptions::new())
    }

    /// Open the FAT volume `src` holds, under `options`.
    ///
    /// The parameter block is validated through the same function detection classifies
    /// with, so a volume detection claims is one this opens and a volume it does not claim
    /// is one this refuses. What the reader adds is a reason.
    ///
    /// # Errors
    ///
    /// As [`open`](Self::open).
    pub fn open_with(src: R, options: &OpenOptions) -> Result<Self, ReadError> {
        let mut src = Bounded::new(src, options.common.base, options.common.len);
        let end = src.seek(SeekFrom::End(0))?;
        let available = end.saturating_sub(options.common.base);
        let sector = read_exact_at(&mut src, options.common.base, BootSector::SIZE)?;
        let boot = BootSector::read_from(&sector)?;
        let layout = layout_from_boot(&boot, available).map_err(|d| ReadError::BadBootSector {
            field: d.field,
            value: d.value,
        })?;

        // The one deviation the geometry itself carries. A count in the disputed band is
        // read the way the specification and Linux read it, and said to be one no formatter
        // should have written — which under a strict policy is where the open stops.
        let mut open_anomalies = Vec::new();
        if layout.fat_type == FatType::Fat16
            && layout.clusters > MAX_CLUSTERS_FAT12
            && layout.clusters < MIN_CLUSTERS_FAT16
        {
            let err = ReadError::AmbiguousClusterCount {
                clusters: layout.clusters,
            };
            if options.common.policy.is_fatal(err.anomaly().severity) {
                return Err(err);
            }
            open_anomalies.push(err.anomaly());
        }
        if layout.bytes_per_cluster() > MAX_BYTES_PER_CLUSTER {
            open_anomalies.push(
                ReadError::LargeCluster {
                    bytes: layout.bytes_per_cluster(),
                }
                .anomaly(),
            );
        }

        let mut reader = Self {
            src,
            base: options.common.base,
            boot,
            layout,
            policy: options.common.policy,
            limits: options.common.limits,
            charset: options.charset,
            open_anomalies,
            fat_window: None,
            volume_dirty: false,
            media_failure: false,
            chain_cursor: None,
        };
        reader.read_volume_state();
        Ok(reader)
    }

    /// Read how the last driver to have the volume put it down, from the two places a FAT
    /// volume records it: the boot sector's reserved byte, and the status bits of table
    /// entry 1.
    ///
    /// The byte is read only where the extended boot signature says the record holding it is
    /// present. An entry 1 that cannot be read leaves its two states unrecorded rather than
    /// failing the open: a table that cannot be read fails the first chain that needs it, and
    /// a scan reports it as what it is.
    fn read_volume_state(&mut self) {
        let volume = self.boot.tail.volume();
        let marked = volume.ext_boot_signature == super::ondisk::EXTENDED_BOOT_SIGNATURE
            && volume.reserved & VOLUME_DIRTY != 0;
        let (clean, no_error) = table::status_bits(self.layout.fat_type);
        let (cleared, failed) = match self.table_entry(1) {
            Ok(entry) => (entry & clean != clean, entry & no_error != no_error),
            Err(_) => (false, false),
        };
        self.volume_dirty = marked || cleared;
        self.media_failure = failed;
    }

    /// The volume's geometry, as its parameter block describes it.
    ///
    /// This is the same type the planner produces, recovered rather than computed — so a
    /// layout planned and a layout read back from the image it produced compare equal, which
    /// is what makes a format-then-read a round trip rather than two descriptions that
    /// happen to agree.
    #[must_use]
    pub const fn layout(&self) -> &FatLayout {
        &self.layout
    }

    /// The boot sector exactly as it was parsed.
    #[must_use]
    pub const fn boot_sector(&self) -> &BootSector {
        &self.boot
    }

    /// Which of the three types the volume's geometry derives to.
    #[must_use]
    pub const fn fat_type(&self) -> FatType {
        self.layout.fat_type
    }

    /// The strictness this reader was opened under.
    #[must_use]
    pub const fn policy(&self) -> ReadPolicy {
        self.policy
    }

    /// Whether a driver had this volume mounted and did not put it down: the clean-shutdown
    /// bit of table entry 1 cleared, or bit 0 of the boot sector's reserved byte set, which
    /// is where a Linux driver records it.
    ///
    /// The volume is well-formed either way — the record is the format recording a state, not
    /// a departure from it — and it is the one condition under which what the metadata says
    /// and what the volume contains are allowed to differ.
    #[must_use]
    pub const fn volume_dirty(&self) -> bool {
        self.volume_dirty
    }

    /// Whether a driver recorded a failure of the medium this volume is on, in the hard-error
    /// bit of table entry 1.
    #[must_use]
    pub const fn media_failure(&self) -> bool {
        self.media_failure
    }

    /// How this reader interprets the bytes of a short name above ASCII.
    #[must_use]
    pub const fn charset(&self) -> ShortNameCharset {
        self.charset
    }

    /// The root directory.
    ///
    /// Its storage is the fixed region on FAT12 and FAT16 and the chain the parameter block
    /// names on FAT32, and it carries no times, because the format records no entry for it
    /// on any type.
    #[must_use]
    pub fn root(&self) -> Node {
        let storage = match self.layout.fat32 {
            Some(f) => Storage::Chain(f.root_cluster),
            None => Storage::RootRegion,
        };
        Node {
            storage,
            attributes: DirAttributes::DIRECTORY,
            size: 0,
            times: None,
        }
    }

    /// The FAT32 information sector, or `None` on a volume that has no such sector.
    ///
    /// Both of its counts are hints. A driver may update them, ignore them, or leave them
    /// stale, so a reader that trusted one over the file allocation table would be trusting
    /// a cache nothing is obliged to invalidate.
    ///
    /// # Errors
    ///
    /// [`ReadError::Io`] when the sector cannot be read, and [`ReadError::BadInfoSector`]
    /// when the sector the parameter block names does not hold one.
    pub fn info_sector(&mut self) -> Result<Option<FsInfo>, ReadError> {
        let Some(fat32) = self.layout.fat32 else {
            return Ok(None);
        };
        let sector = u32::from(fat32.fs_info_sector);
        let bytes = self.read_sectors(sector, 1)?;
        match FsInfo::read_from(&bytes) {
            Ok(info) => Ok(Some(info)),
            Err(_) => Err(ReadError::BadInfoSector { sector }),
        }
    }

    /// The volume label, or `None` for a volume that carries none.
    ///
    /// The authority is the entry in the root directory carrying
    /// [`Attributes::VOLUME_ID`](DirAttributes::VOLUME_ID), which is what a driver and
    /// `fatlabel` both read and what a rename updates. The copy in the boot sector is a
    /// second record of the same thing that nothing keeps in step, so it is used only where
    /// the root holds no such entry.
    ///
    /// The bytes are the eleven-byte field with its trailing padding trimmed, read under
    /// this reader's [`charset`](Self::charset) like any other short name.
    ///
    /// # Errors
    ///
    /// [`ReadError`] variants if the root directory cannot be read.
    pub fn volume_label(&mut self) -> Result<Option<Vec<u8>>, ReadError> {
        let root = self.root();
        let mut found = None;
        // `for_each_slot` hands back *every* slot, live or not, because that is what the
        // scan needs. A label is a live entry like any other, so the free and deleted markers
        // and the end of the directory are applied here — `fatlabel` and every driver read
        // the live label, and a deleted slot or one past the end holds a name the volume no
        // longer answers to.
        self.for_each_slot::<ReadError>(&root, |_, slot| {
            let first = slot.entry.name[0];
            if first == NAME_END {
                return Ok(ControlFlow::Break(()));
            }
            if first == NAME_DELETED {
                return Ok(ControlFlow::Continue(()));
            }
            if is_volume_label(slot.entry.attributes) {
                found = Some(slot.entry.name);
                return Ok(ControlFlow::Break(()));
            }
            Ok(ControlFlow::Continue(()))
        })?;
        if let Some(name) = found {
            // A field of nothing but padding names nothing.
            let label = volume_label(&name);
            if label.is_empty() {
                return Ok(None);
            }
            return Ok(Some(self.charset.decode(&label)));
        }
        let stored = self.boot.tail.volume().label;
        if stored == super::ondisk::VolumeInfo::NO_NAME {
            return Ok(None);
        }
        let trimmed = volume_label(&stored);
        if trimmed.is_empty() {
            return Ok(None);
        }
        Ok(Some(self.charset.decode(&trimmed)))
    }

    // -- byte-level access ------------------------------------------------------------

    /// The byte offset of `sector` within the source, or [`None`] where it leaves the 64-bit
    /// range.
    ///
    /// Checked, for the reason every address in this crate is: `base` is the caller's and a
    /// sector number is the volume's, so a sum near the top of the range wraps into a small
    /// offset — which is not a read that fails but a successful read of the wrong bytes.
    ///
    /// What makes it unreachable today is `layout_from_boot`, which refuses a volume whose
    /// sectors do not fit the bytes the source holds from `base` onward: every sector this is
    /// asked for is therefore inside a source that already ends at or below `u64::MAX`. The
    /// check remains because that is a bound another function applies, held on the far side
    /// of the parameter block, and nothing here should depend on it — an overflow in a
    /// filesystem's addressing is silent, and the only cost of refusing one is a branch.
    fn sector_offset(&self, sector: u32) -> Option<u64> {
        offset_of(
            self.base,
            u64::from(sector),
            u64::from(self.layout.bytes_per_sector),
        )
    }

    /// `count` sectors from `first`, refusing a range the volume does not describe.
    ///
    /// The bound is the volume's own sector count, so a structure naming a sector past the
    /// filesystem is answered rather than read out of whatever follows it in the source.
    fn read_sectors(&mut self, first: u32, count: u32) -> Result<Vec<u8>, ReadError> {
        // The refusal names the sector asked for and the volume's own bound: which
        // structure named the sector varies by caller, so pinning the message to one
        // parameter-block field would blame a field whose value may be fine.
        let out_of_range = || ReadError::SectorOutOfRange {
            sector: first,
            total_sectors: self.layout.total_sectors,
        };
        let end = first
            .checked_add(count)
            .filter(|end| *end <= self.layout.total_sectors)
            .ok_or_else(out_of_range)?;
        debug_assert!(end <= self.layout.total_sectors);
        let offset = self.sector_offset(first).ok_or_else(out_of_range)?;
        let len = count as usize * self.layout.bytes_per_sector as usize;
        Ok(read_exact_at(&mut self.src, offset, len)?)
    }

    /// How many sectors a read must cover to hold the whole entry at `sector_in_table`,
    /// counted from the start of whichever copy of the table is being read.
    ///
    /// Two, because a FAT12 entry may begin in the last byte of one sector and end in the
    /// first of the next. One where the copy has no next sector — which is an entry the
    /// caller's own bound already refused, or one wholly inside the last sector.
    ///
    /// The end is the copy's own, not the first copy's. The copies are laid end to end, so
    /// reading one sector past the live table would splice the *next* copy's first entry
    /// onto a FAT12 entry that straddles the boundary, and the value read would belong to
    /// neither. Refusing there is what makes the two ways of reading an entry — the windowed
    /// walk and the copy-by-copy comparison — agree on every entry they both reach.
    const fn table_window_sectors(&self, sector_in_table: u32) -> u32 {
        if sector_in_table.saturating_add(1) < self.layout.fat_sectors {
            2
        } else {
            1
        }
    }

    /// The file allocation table's entry for `cluster`, from the copy the volume says is
    /// live.
    ///
    /// Read through the two-sector window, so a chain walk pays one read per table sector
    /// rather than one per cluster.
    fn table_entry(&mut self, cluster: u32) -> Result<u32, ReadError> {
        let fat_type = self.layout.fat_type;
        if cluster >= self.layout.max_table_entries() {
            return Err(ReadError::ClusterOutOfRange { cluster });
        }
        let copy = self.active_fat();
        let offset = table::entry_offset(fat_type, cluster);
        let bytes_per_sector = u64::from(self.layout.bytes_per_sector);
        let sector_in_table = u32::try_from(offset / bytes_per_sector)
            .map_err(|_| ReadError::ClusterOutOfRange { cluster })?;
        let within = (offset % bytes_per_sector) as usize;
        let start = self
            .layout
            .fat_start_sector(copy)
            .ok_or(ReadError::ClusterOutOfRange { cluster })?;
        let sector = start
            .checked_add(sector_in_table)
            .ok_or(ReadError::ClusterOutOfRange { cluster })?;

        let window_sectors = self.table_window_sectors(sector_in_table);
        let need_reload = match &self.fat_window {
            Some((at, buf)) => {
                *at != sector || buf.len() < window_sectors as usize * bytes_per_sector as usize
            }
            None => true,
        };
        if need_reload {
            let buf = self.read_sectors(sector, window_sectors)?;
            self.fat_window = Some((sector, buf));
        }
        let (_, buf) = self.fat_window.as_ref().expect("just loaded");
        table::read_entry(fat_type, &buf[within..], 0).map_or(
            Err(ReadError::ClusterOutOfRange { cluster }),
            |raw| {
                // `read_entry` at index 0 of a slice beginning mid-table reads the low
                // twelve bits of the pair there, which is the even-cluster packing. An odd
                // FAT12 cluster owns the high twelve of the same pair.
                if fat_type == FatType::Fat12 && cluster & 1 == 1 {
                    let pair = u32::from(get_u16(buf, within));
                    Ok(pair >> 4)
                } else {
                    Ok(raw)
                }
            },
        )
    }

    /// The cluster that follows `cluster` in its chain, or `None` where the chain ends.
    ///
    /// # Errors
    ///
    /// [`ReadError::BadChainEntry`] for a value no chain may contain, and
    /// [`ReadError::ClusterOutOfRange`] for one naming a cluster the volume does not have.
    fn next_cluster(&mut self, cluster: u32) -> Result<Option<u32>, ReadError> {
        let fat_type = self.layout.fat_type;
        let entry = self.table_entry(cluster)?;
        if table::is_end_of_chain(fat_type, entry) {
            return Ok(None);
        }
        if !table::is_cluster(fat_type, entry) {
            return Err(ReadError::BadChainEntry { cluster, entry });
        }
        if entry - 2 >= self.layout.clusters {
            return Err(ReadError::ClusterOutOfRange { cluster: entry });
        }
        Ok(Some(entry))
    }

    /// The cluster at `index` in the chain beginning at `start`, or `None` where the chain
    /// is shorter than that.
    ///
    /// Resumes from [`chain_cursor`](Self::chain_cursor) where it can, so reading one file
    /// in order costs one pass over its chain rather than one per call.
    fn cluster_at(&mut self, start: u32, index: u64) -> Result<Option<u32>, ReadError> {
        let (mut at, mut current) = match self.chain_cursor {
            Some((cursor_start, cursor_index, cursor_cluster))
                if cursor_start == start && cursor_index <= index =>
            {
                (cursor_index, cursor_cluster)
            }
            _ => (0, start),
        };
        if start < 2 || start - 2 >= self.layout.clusters {
            return Err(ReadError::ClusterOutOfRange { cluster: start });
        }
        while at < index {
            match self.next_cluster(current)? {
                Some(next) => {
                    current = next;
                    at += 1;
                }
                None => return Ok(None),
            }
            // A chain longer than the volume has clusters must repeat one, so the bound is
            // the geometry's rather than a limit a caller sets.
            if at > u64::from(self.layout.clusters) {
                return Err(ReadError::ChainTooLong {
                    start,
                    clusters: self.layout.clusters,
                });
            }
        }
        self.chain_cursor = Some((start, at, current));
        Ok(Some(current))
    }

    /// The whole chain beginning at `start`, in order.
    ///
    /// Two bounds apply, and the tighter one wins. The structural bound is the volume's
    /// cluster count, which is what a chain cannot exceed without repeating a cluster; the
    /// caller's is [`Limits::max_walk_entries`], since a chain is collected whole for the
    /// same reason a walk is and a maximal FAT32 chain is four bytes times a quarter of a
    /// billion clusters. Reaching either is an error rather than a shortened list: a caller
    /// handed part of a chain would follow it somewhere the file does not go.
    ///
    /// # Errors
    ///
    /// [`ReadError::ClusterOutOfRange`] or [`ReadError::BadChainEntry`] where the chain
    /// leaves the volume, [`ReadError::ChainTooLong`] where it does not end, and
    /// [`ReadError::WalkTooLarge`] where it is longer than the caller's cap.
    pub fn chain(&mut self, start: u32) -> Result<Vec<u32>, ReadError> {
        if start < 2 || start - 2 >= self.layout.clusters {
            return Err(ReadError::ClusterOutOfRange { cluster: start });
        }
        let cap = self.limits.max_walk_entries;
        let mut out = vec![start];
        let mut current = start;
        while let Some(next) = self.next_cluster(current)? {
            if out.len() as u64 > u64::from(self.layout.clusters) {
                return Err(ReadError::ChainTooLong {
                    start,
                    clusters: self.layout.clusters,
                });
            }
            if out.len() >= cap {
                return Err(ReadError::WalkTooLarge { limit: cap });
            }
            out.push(next);
            current = next;
        }
        Ok(out)
    }

    /// The bytes of cluster `n`.
    fn read_cluster(&mut self, n: u32) -> Result<Vec<u8>, ReadError> {
        let first = self
            .layout
            .cluster_start_sector(n)
            .ok_or(ReadError::ClusterOutOfRange { cluster: n })?;
        self.read_sectors(first, self.layout.sectors_per_cluster)
    }

    // -- directories ------------------------------------------------------------------

    /// Hand every 32-byte slot of a directory's storage to `visit`, in order.
    ///
    /// One region is held at a time — the fixed root region, or a single cluster — so what
    /// this allocates is the largest region the geometry defines and not the directory's own
    /// size. That is the difference between a bound the *structure* implies and one a caller
    /// can rely on: a crafted directory whose chain spans the volume is the volume's size,
    /// and reading it whole would be an allocation the size of the image however tight a
    /// [`Limits`] the caller set. Streaming it costs one cluster whatever the chain does.
    ///
    /// `visit` says whether to keep going, so a caller that has found what it came for stops
    /// rather than reading the rest of the chain.
    fn for_each_slot<E: From<ReadError>>(
        &mut self,
        node: &Node,
        mut visit: impl FnMut(&mut Self, Slot) -> Result<ControlFlow<()>, E>,
    ) -> Result<(), E> {
        let entries_per_sector = (self.layout.bytes_per_sector as usize / DIR_ENTRY_SIZE).max(1);
        // Where the next slot sits, carried across regions: the index counts the whole
        // directory, and the sector is recomputed within each region from the index.
        let mut index = 0u32;

        // What is left to read. The fixed root region is one region and a chain is one per
        // cluster, which is the only difference between the two shapes.
        let mut next = match node.storage {
            Storage::None => None,
            Storage::RootRegion => self
                .layout
                .root_dir_start_sector()
                .map(|first| (first, self.layout.root_dir_sectors, None)),
            Storage::Chain(start) => Some((0, 0, Some(start))),
        };
        // Clusters this walk has already read. `steps` alone bounds the walk at the
        // volume's cluster count, which for a cycling chain means re-reading the same
        // cluster that many times before the refusal — and a scan absorbs that error and
        // moves on, so the cost is paid afresh for every directory. A 32 MiB volume can
        // spend gigabytes that way. A repeat is a cycle whatever it costs, so it ends the
        // chain the moment it is seen.
        //
        // The set is the volume's own domain, one bit per cluster, which is the answer this
        // file gives that question everywhere it is asked.
        let mut visited = ClusterSet::new(self.layout.clusters);
        if let Storage::Chain(start) = node.storage {
            visited.insert(start);
        }
        let mut steps = 0u64;

        while let Some((mut first, mut count, cluster)) = next {
            if let Some(current) = cluster {
                first = self
                    .layout
                    .cluster_start_sector(current)
                    .ok_or(ReadError::ClusterOutOfRange { cluster: current })?;
                count = self.layout.sectors_per_cluster;
            }
            let bytes = self.read_sectors(first, count).map_err(E::from)?;
            for (i, chunk) in bytes.as_chunks::<DIR_ENTRY_SIZE>().0.iter().enumerate() {
                // Every chunk is exactly `DIR_ENTRY_SIZE` bytes, so the parse cannot be
                // short; the error path stands because the parser is fallible in general.
                let Ok(entry) = DirEntry::read_from(chunk) else {
                    continue;
                };
                let slot = Slot {
                    entry,
                    index,
                    sector: first + (i / entries_per_sector) as u32,
                };
                index = index.saturating_add(1);
                if visit(self, slot)?.is_break() {
                    return Ok(());
                }
            }

            next = match cluster {
                None => None,
                Some(current) => match self.next_cluster(current).map_err(E::from)? {
                    None => None,
                    Some(following) => {
                        steps += 1;
                        let repeat = !visited.insert(following);
                        if repeat || steps > u64::from(self.layout.clusters) {
                            let Storage::Chain(start) = node.storage else {
                                unreachable!("only a chain steps between clusters")
                            };
                            return Err(E::from(ReadError::ChainTooLong {
                                start,
                                clusters: self.layout.clusters,
                            }));
                        }
                        Some((0, 0, Some(following)))
                    }
                },
            };
        }
        Ok(())
    }

    /// The entries of a directory, with long names reassembled.
    ///
    /// The volume label entry and the dot entries are not among them: the first is
    /// [`volume_label`](Self::volume_label)'s and the other two are the walk's own business,
    /// and none of the three is a name a consumer of a tree wants handed to it. The dot
    /// entries are recognized by their eleven-byte name field, which is where the format
    /// defines them, so a long-name run attached to one does not make it a name in the tree.
    ///
    /// Every name that *is* handed back is one a directory can hold. A name resolving to `.`
    /// or `..`, or carrying a path separator or a NUL, is
    /// [`HostileName`](ReadError::HostileName) — an error under [`ReadPolicy::Strict`] and a
    /// finding a [`scan`](Self::scan) collects, never an entry in the returned list.
    ///
    /// The directory's storage is read a region at a time and never held whole, so what one
    /// call allocates is the entries it produces plus a single cluster — the volume's size
    /// does not enter into it, however many clusters a directory chains together. The
    /// entries themselves are bounded by [`Limits::max_walk_entries`] and by the volume's
    /// whole directory capacity, whichever is smaller.
    ///
    /// # Errors
    ///
    /// [`ReadError`] variants when the directory's storage cannot be read,
    /// [`ReadError::WalkTooLarge`] when it holds more entries than that bound, and — under
    /// [`ReadPolicy::Strict`] — whichever deviation its entries carry, including
    /// [`ReadError::HostileName`].
    pub fn read_dir(&mut self, node: &Node) -> Result<Vec<Entry>, ReadError> {
        let policy = self.policy;
        self.parse_dir(node, Placement::UNKNOWN, &mut OnDeviation::Policy(policy))
    }

    /// A directory's entries gathered into a list, held to [`Limits::max_walk_entries`] and
    /// the volume's whole directory capacity.
    fn parse_dir(
        &mut self,
        node: &Node,
        placement: Placement<'_>,
        deviations: &mut OnDeviation<'_>,
    ) -> Result<Vec<Entry>, ReadError> {
        // The directory's own entries are held, and its storage is not: a crafted directory
        // is bounded by what a caller allowed rather than by how many clusters it chained
        // together. The structural half of the cap is the volume's whole directory capacity,
        // which a well-formed directory can never reach.
        let cap = self.limits.max_walk_entries.min(self.max_names());
        let mut out: Vec<Entry> = Vec::new();
        // Every name the directory answers to, folded as a driver compares it, beside the
        // entry that first carried it. A second entry carrying one is reported once the whole
        // directory is read, since `deviations` is the parser's while it runs.
        let mut names: std::collections::HashMap<Vec<u8>, u32> = std::collections::HashMap::new();
        let mut repeats = Vec::new();
        self.parse_entries(node, placement, deviations, |_, entry, at| {
            if out.len() >= cap {
                return Err(ReadError::WalkTooLarge { limit: cap });
            }
            let index = at.entry.unwrap_or_default();
            let keys = lookup_keys(&entry);
            if let Some(&first) = keys.iter().find_map(|key| names.get(key)) {
                repeats.push((at, ReadError::IndistinguishableNames { index, first }));
            }
            for key in keys {
                names.entry(key).or_insert(index);
            }
            out.push(entry);
            Ok(ControlFlow::Continue(()))
        })?;
        for (at, repeat) in repeats {
            deviations.record(at, repeat)?;
        }
        Ok(out)
    }

    /// The shared directory parser, which is the one place an entry's bytes become a name.
    ///
    /// Each entry is handed to `each` as it is assembled, and `each` says whether to go on,
    /// so a lookup stops at the name it came for rather than reading the directory to its end.
    /// Nothing is held but the long-name run in flight.
    ///
    /// It is also where a subdirectory's `.` and `..` are held to the format, since they are
    /// its first two slots and every read passes them: the name field, the directory
    /// attribute, and the cluster `.` names, wherever the directory is read; the cluster `..`
    /// names, where `placement` says what the parent is; and a dot entry anywhere else.
    fn parse_entries(
        &mut self,
        node: &Node,
        placement: Placement<'_>,
        deviations: &mut OnDeviation<'_>,
        mut each: impl FnMut(&mut Self, Entry, Location) -> Result<ControlFlow<()>, ReadError>,
    ) -> Result<(), ReadError> {
        if !node.is_dir() {
            return Err(ReadError::NotADirectory { path: Vec::new() });
        }
        let is_root = matches!(node.storage, Storage::RootRegion)
            || self
                .layout
                .fat32
                .is_some_and(|f| node.storage == Storage::Chain(f.root_cluster));
        let charset = self.charset;
        let fat_type = self.layout.fat_type;
        let mut pending = LongName::default();
        let mut ended = false;
        let mut reported_after_end = false;
        let mut last_slot = None;
        // How many slots were read, and whether the read stopped because `each` asked it to:
        // a directory whose storage ends before its second slot holds no `..`, and one a
        // lookup stopped reading early holds whatever it holds.
        let mut slots = 0u32;
        let mut stopped = false;
        // Volume labels met in the root, the first of which is the volume's.
        let mut labels = 0u32;
        let own = match node.storage {
            Storage::Chain(start) => start,
            Storage::None | Storage::RootRegion => 0,
        };
        let shown = |path: Option<&[u8]>| {
            path.map_or_else(String::new, |p| {
                format!("{}: ", crate::escape::printable(p))
            })
        };

        self.for_each_slot::<ReadError>(node, |reader, slot| {
            let index = slot.index;
            let at = Location {
                sector: Some(slot.sector),
                cluster: None,
                entry: Some(index),
            };
            last_slot = Some((at, index));
            slots = index + 1;
            // The format bounds the directory's own size, so the first slot past it is the
            // finding wherever it lies: a used entry, a free one, or one past the end marker.
            // The read goes on, as a driver's does.
            if u64::from(index) == MAX_DIRECTORY_ENTRIES {
                deviations.record(
                    at,
                    ReadError::DirectoryTooLong {
                        index,
                        limit: MAX_DIRECTORY_BYTES,
                    },
                )?;
            }
            let entry = slot.entry;
            let first = entry.name[0];

            // A subdirectory's first two slots are its `.` and `..`, before anything else
            // about the slot is decided: an end marker, a deleted entry, or a long-name slot
            // there is the dot entry missing, as much as another name is.
            if !is_root && let Some(&want) = DOT_NAMES.get(index as usize) {
                let dot = if index == 0 { "." } else { ".." };
                let is_dot = !ended
                    && first != NAME_END
                    && first != NAME_DELETED
                    && !entry.attributes.is_long_name()
                    && entry.name == *want;
                if !is_dot {
                    deviations.record(
                        at,
                        ReadError::BadDotEntry {
                            detail: format!(
                                "{}entry {index} is not the `{dot}` entry the format puts there",
                                shown(placement.path)
                            ),
                        },
                    )?;
                } else {
                    if !entry.attributes.contains(DirAttributes::DIRECTORY) {
                        deviations.record(
                            at,
                            ReadError::BadDotEntry {
                                detail: format!(
                                    "{}the `{dot}` entry does not carry the directory attribute",
                                    shown(placement.path)
                                ),
                            },
                        )?;
                    }
                    let expected = if index == 0 {
                        Some(own)
                    } else {
                        placement.parent
                    };
                    let found = first_cluster(&entry, fat_type);
                    if let Some(expected) = expected
                        && found != expected
                    {
                        deviations.record(
                            at,
                            ReadError::DotEntryTarget {
                                path: placement.path.unwrap_or_default().to_vec(),
                                name: dot,
                                found,
                                expected,
                            },
                        )?;
                    }
                }
            }

            if ended {
                // Everything after the end marker should be free. A used slot there is
                // storage no reader reaches — including this one: every driver stops at the
                // marker, so yielding what is past it would show a caller names that nothing
                // else on the volume can see. It is reported once rather than once per slot,
                // and never handed back.
                if first != NAME_END && !reported_after_end {
                    deviations.record(at, ReadError::EntriesAfterEnd { index })?;
                    reported_after_end = true;
                }
                return Ok(ControlFlow::Continue(()));
            }
            if first == NAME_END {
                // A run still in flight at the end marker decorated nothing: the marker
                // says the names are over, so the run's slots are storage no driver reads
                // a name out of.
                if !matches!(pending.take(), LongRun::None) {
                    deviations.record(at, ReadError::OrphanedLongName { index })?;
                }
                ended = true;
                return Ok(ControlFlow::Continue(()));
            }
            if first == NAME_DELETED {
                // The classic shape of this corruption: the short entry was deleted and
                // its long-name slots were not, so the run in flight belongs to nothing.
                if !matches!(pending.take(), LongRun::None) {
                    deviations.record(at, ReadError::OrphanedLongName { index })?;
                }
                return Ok(ControlFlow::Continue(()));
            }
            if entry.attributes.is_long_name() {
                let lfn = LfnEntry::read_from(&raw_bytes(&entry))?;
                if pending.accept(&lfn) {
                    // A fresh sequence start wiped a run still being assembled, whose
                    // slots now belong to nothing.
                    deviations.record(at, ReadError::OrphanedLongName { index })?;
                }
                return Ok(ControlFlow::Continue(()));
            }

            // A short entry ends whatever run preceded it.
            let run = pending.take();
            let short_name = render_short(&entry.name, entry.case_flags);

            // No entry carrying the volume-label attribute is a name in the tree. One that is a
            // label by the one definition is the volume's label in the root, misplaced
            // elsewhere, and a second label after the first; one carrying the directory
            // attribute as well is neither a label nor a directory.
            if entry.attributes.contains(DirAttributes::VOLUME_ID) {
                if !is_volume_label(entry.attributes) {
                    deviations.record(at, ReadError::LabelWithDirectoryAttribute { index })?;
                } else if !is_root {
                    deviations.record(at, ReadError::MisplacedVolumeLabel { index })?;
                } else {
                    labels += 1;
                    if labels > 1 {
                        deviations.record(at, ReadError::SecondVolumeLabel { index })?;
                    }
                    if entry.name[0] == b' ' {
                        deviations.record(at, ReadError::LabelBeginsWithSpace { index })?;
                    }
                }
                // A run in front of the label belongs to nothing: the format hangs a long
                // name off an ordinary entry alone, and the label is not a name in the
                // tree under any circumstances.
                if !matches!(run, LongRun::None) {
                    deviations.record(at, ReadError::OrphanedLongName { index })?;
                }
                return Ok(ControlFlow::Continue(()));
            }
            // The dot entries, recognized by the field the format defines them in. A run of
            // long-name entries in front of one decorates nothing: what the format says
            // sits in these two slots is a directory's link to itself and to its parent,
            // and a name hung off one of them is not an entry the directory holds. The
            // *name* is rightly dropped; the slots are the same debris they are in front
            // of the label one arm above, and are reported the same way. One anywhere but
            // the first two slots of a subdirectory is passed over all the same, and
            // reported: the format puts none there.
            if crate::path::is_dot_entry(&short_name) {
                if !matches!(run, LongRun::None) {
                    deviations.record(at, ReadError::OrphanedLongName { index })?;
                }
                if is_root || index >= 2 {
                    deviations.record(
                        at,
                        ReadError::BadDotEntry {
                            detail: format!(
                                "{}entry {index} is a `{}` entry, where the format puts none",
                                shown(placement.path),
                                crate::escape::printable(&short_name)
                            ),
                        },
                    )?;
                }
                return Ok(ControlFlow::Continue(()));
            }

            let mut has_long_name = false;
            let mut name = None;
            match run {
                LongRun::None => {}
                LongRun::Incomplete => {
                    deviations.record(at, ReadError::OrphanedLongName { index })?;
                }
                LongRun::Complete {
                    units,
                    checksum,
                    padded,
                } => {
                    if !padded {
                        deviations.record(at, ReadError::LongNamePadding { index })?;
                    }
                    let expected = entry.lfn_checksum();
                    if checksum != expected {
                        deviations.record(
                            at,
                            ReadError::LongNameChecksum {
                                index,
                                found: checksum,
                                expected,
                            },
                        )?;
                    } else {
                        // Twenty entries carry up to 260 units and the format caps a name
                        // at 255, so a run can be whole and still hold a name no volume of
                        // this family should carry — one this crate's own writer refuses.
                        // The name is read anyway, so the tree stays enumerable.
                        if units.len() > super::name::MAX_NAME_UNITS {
                            deviations.record(
                                at,
                                ReadError::LongNameTooLong {
                                    index,
                                    units: units.len(),
                                },
                            )?;
                        }
                        let (decoded, ill_formed) = decode_utf16(&units);
                        if ill_formed {
                            deviations.record(at, ReadError::IllFormedLongName { index })?;
                        }
                        has_long_name = true;
                        name = Some(decoded);
                    }
                }
            }

            let name = match name {
                Some(name) => name,
                None => {
                    // Falling back to the short name is where its code page matters, so the
                    // deviation is raised for the name that is actually handed back.
                    if let Some(byte) = short_name.iter().copied().find(|b| *b >= 0x80) {
                        let err = ReadError::UninterpretedShortName { index, byte };
                        // Naming a charset is what makes the bytes recognized, so the same
                        // volume is a conformance deviation under `Verbatim` and a cosmetic
                        // remark once a caller has said how to read it.
                        if charset == ShortNameCharset::Verbatim {
                            deviations.record(at, err)?;
                        } else {
                            let mut anomaly = err.anomaly();
                            anomaly.severity = Severity::Cosmetic;
                            anomaly.detail = format!(
                                "the short name at entry {index} carries byte {byte:#04x}, \
                                 above ASCII, read as code page {}",
                                charset.as_str()
                            );
                            if let OnDeviation::Collect(findings) = deviations {
                                anomaly.location = anomaly.location.or(at);
                                findings.push(anomaly);
                            }
                        }
                    }
                    charset.decode(&short_name)
                }
            };

            // The resolved name is what a caller receives and what a path is built from, so
            // it is where a name no directory can hold is refused. Either field reaches it,
            // and a long-name run reaches it past every test above: the run is reassembled
            // after the dot entries are recognized by their name field, so one spelling `..`
            // belongs to an ordinary short entry and is well-formed in every other way.
            // Refusing it here keeps the four names out of every surface at once — the entry
            // list, a walk's paths, and an archive built from them.
            if is_hostile_component(&name) {
                deviations.record(at, ReadError::HostileName { index })?;
                return Ok(ControlFlow::Continue(()));
            }
            // What the format reserves in either name, which the writer keeps out of both.
            // The long name is held to it as decoded, and the short one as stored.
            if has_long_name
                && let Some(ch) = String::from_utf8_lossy(&name)
                    .chars()
                    .find(|&ch| is_reserved_name_char(ch))
            {
                deviations.record(
                    at,
                    ReadError::ReservedCharacter {
                        index,
                        field: "long",
                        code: u32::from(ch),
                    },
                )?;
            }
            if let Some((_, &byte)) =
                entry.name.iter().enumerate().find(|&(position, &byte)| {
                    super::name::is_reserved_short_byte_at(byte, position)
                })
            {
                deviations.record(
                    at,
                    ReadError::ReservedCharacter {
                        index,
                        field: "short",
                        code: u32::from(byte),
                    },
                )?;
            }

            check_times(&entry, index, at, deviations)?;

            // The two fields an entry describes its contents with, held against each other
            // where they are read. FAT has no holes, so a length is a claim about clusters and
            // a first cluster below two says there are none — and the disagreement is invisible
            // to everything downstream: the storage the node carries is the same `None` a
            // legitimately empty file has, so the scan's size-against-chain comparison has no
            // chain to make it against and a read fails much later, at the cluster it cannot
            // follow.
            let node = node_of(&entry, reader.layout.fat_type);
            if node.size != 0 && node.is_dir() {
                // A directory's length is its chain, and the field it would record one in
                // is zero (documented).
                deviations.record(
                    at,
                    ReadError::DirectoryWithSize {
                        index,
                        size: node.size,
                    },
                )?;
            } else if node.size != 0 && matches!(node.storage, Storage::None) {
                deviations.record(
                    at,
                    ReadError::SizeWithoutAllocation {
                        index,
                        size: node.size,
                    },
                )?;
            }

            let flow = each(
                reader,
                Entry {
                    name,
                    short_name: charset.decode(&short_name),
                    has_long_name,
                    node,
                },
                at,
            )?;
            stopped = flow.is_break();
            Ok(flow)
        })?;
        // A subdirectory whose storage ended before its second slot, read to its end. The
        // slots it has were held to the format above.
        if !is_root && !stopped {
            for index in slots..2 {
                let dot = if index == 0 { "." } else { ".." };
                deviations.record(
                    Location {
                        entry: Some(index),
                        ..Location::default()
                    },
                    ReadError::BadDotEntry {
                        detail: format!(
                            "{}the directory ends before its `{dot}` entry",
                            shown(placement.path)
                        ),
                    },
                )?;
            }
        }
        // The fifth way a run can end: the storage itself runs out, on a directory whose
        // every slot is used and whose last slots are the run. The finding sits at the
        // run's last slot, which is the last slot there was.
        if !matches!(pending.take(), LongRun::None)
            && let Some((at, index)) = last_slot
        {
            deviations.record(at, ReadError::OrphanedLongName { index })?;
        }
        Ok(())
    }

    /// Resolve `path` against the volume's own root.
    ///
    /// Components are matched exactly first and, failing that, without regard to the case of
    /// their ASCII letters — which is how every FAT driver finds a name, since the eleven-byte
    /// short name field is upper case by construction and a long name preserves a case no
    /// driver requires a caller to reproduce. Bytes above ASCII are compared as they stand,
    /// because folding them would need the code page the volume does not record.
    ///
    /// A `..` component ascends to the directory the resolution descended from, staying at the
    /// root where there is nothing to ascend to — so nothing outside the volume can be named.
    /// It is an ascent rather than a lookup of the entry of that name, which a FAT
    /// subdirectory carries and this reader refuses as a name.
    ///
    /// Each directory is read only as far as the name it resolves and nothing is gathered, so
    /// [`Limits::max_walk_entries`] does not govern a lookup, and an entry past the name is
    /// not read. A name found only without regard to case reads on to the directory's end,
    /// since an exact match further on would be the one returned.
    ///
    /// # Errors
    ///
    /// [`ReadError::NotFound`] where no component matches, [`ReadError::NotADirectory`]
    /// where the path traverses through a file, and the read errors of the directories along
    /// the way, as far as the name.
    pub fn lookup(&mut self, path: &[u8]) -> Result<Node, ReadError> {
        crate::resolve::drive(self, path, true)
    }

    // -- file contents ----------------------------------------------------------------

    /// Fill `buf` from `offset` in a regular file, returning how many bytes were placed.
    ///
    /// A short fill means the file ends there. A node that is not a regular file holds no
    /// bytes and yields none: a directory's storage is its entries, and handing those back
    /// as file contents would be a directory entry read as data.
    ///
    /// # Errors
    ///
    /// [`ReadError`] variants where the chain cannot be followed.
    pub fn read_into(
        &mut self,
        node: &Node,
        offset: u64,
        buf: &mut [u8],
    ) -> Result<usize, ReadError> {
        if node.is_dir() || node.is_volume_label() {
            return Ok(0);
        }
        let Storage::Chain(start) = node.storage else {
            return Ok(0);
        };
        let size = u64::from(node.size);
        if offset >= size || buf.is_empty() {
            return Ok(0);
        }
        let bytes_per_cluster = u64::from(self.layout.bytes_per_cluster());
        let want = buf.len().min((size - offset) as usize);
        let mut done = 0usize;
        while done < want {
            let at = offset + done as u64;
            let index = at / bytes_per_cluster;
            let within = (at % bytes_per_cluster) as usize;
            let Some(cluster) = self.cluster_at(start, index)? else {
                // The chain ran out with bytes still to come, which is the length and the
                // allocation disagreeing. What is reported is the byte this read needed:
                // a read from an offset lands here without walking the earlier clusters,
                // so where exactly the chain ends is not known — only that it ends before
                // the byte that was asked for.
                return Err(ReadError::ChainTooShort {
                    start,
                    size,
                    read: at,
                });
            };
            let bytes = self.read_cluster(cluster)?;
            let take = (bytes.len() - within).min(want - done);
            buf[done..done + take].copy_from_slice(&bytes[within..within + take]);
            done += take;
        }
        Ok(done)
    }

    /// A file's length as a whole-file read sees it: the length its directory entry records,
    /// held to [`Limits::max_file_bytes`].
    ///
    /// Every whole-file form goes through this, so the cap governs what a read hands back and
    /// what a stream into a caller's writer produces alike. Nothing accumulates in the second
    /// of those, which is exactly why it needs the cap named here: what it *writes* follows
    /// the length the image declares rather than the working memory it uses.
    ///
    /// # Errors
    ///
    /// [`ReadError::FileTooLarge`] if the length exceeds the cap.
    fn whole_file_len(&self, node: &Node) -> Result<u64, ReadError> {
        let size = u64::from(node.size);
        if size > self.limits.max_file_bytes {
            return Err(ReadError::FileTooLarge {
                size,
                limit: self.limits.max_file_bytes,
            });
        }
        Ok(size)
    }

    /// Stream a file's whole contents into `out`, returning how many bytes were written.
    ///
    /// Nothing accumulates, so a file of any size costs one cluster of working memory.
    ///
    /// # Errors
    ///
    /// [`ReadError::FileTooLarge`] where the length exceeds [`Limits::max_file_bytes`],
    /// [`ReadError`] variants where the chain cannot be followed,
    /// [`ReadError::ChainTooShort`] where it ends before the length the entry records, and
    /// whatever `out` returns.
    pub fn read_data_to(&mut self, node: &Node, mut out: impl Write) -> Result<u64, ReadError> {
        if node.is_dir() || node.is_volume_label() {
            return Ok(0);
        }
        let size = self.whole_file_len(node)?;
        let mut buf = vec![0u8; self.layout.bytes_per_cluster() as usize];
        let mut done = 0u64;
        while done < size {
            let want = buf.len().min((size - done) as usize);
            let got = self.read_into(node, done, &mut buf[..want])?;
            if got == 0 {
                return Err(ReadError::ChainTooShort {
                    start: match node.storage {
                        Storage::Chain(start) => start,
                        _ => 0,
                    },
                    size,
                    read: done,
                });
            }
            out.write_all(&buf[..got])?;
            done += got as u64;
        }
        Ok(done)
    }

    /// A file's whole contents.
    ///
    /// The buffer grows as bytes arrive rather than being sized from the length field up
    /// front, so a crafted length costs nothing beyond the bytes the volume actually holds.
    ///
    /// # Errors
    ///
    /// [`ReadError::FileTooLarge`] where the length exceeds
    /// [`Limits::max_file_bytes`], and the errors of
    /// [`read_data_to`](Self::read_data_to).
    pub fn read_data(&mut self, node: &Node) -> Result<Vec<u8>, ReadError> {
        let mut out = Vec::new();
        self.read_data_to(node, &mut out)?;
        Ok(out)
    }

    // -- walking ----------------------------------------------------------------------

    /// Every name in the tree, depth-first, a parent before its children.
    ///
    /// # Errors
    ///
    /// [`ReadError`] variants if any directory along the walk cannot be read,
    /// [`ReadError::RepeatedDirectory`] under [`ReadPolicy::Strict`] if an entry names a
    /// directory the tree already reaches, and [`ReadError::WalkTooLarge`] if the tree holds
    /// more names than the bounds allow.
    pub fn walk(&mut self) -> Result<Vec<WalkEntry>, ReadError> {
        let mut out = Vec::new();
        self.walk_with::<ReadError>(|_, entry| {
            out.push(entry);
            Ok(())
        })?;
        Ok(out)
    }

    /// Walk the whole tree, handing each [`WalkEntry`] to `visit` as it is reached rather
    /// than gathering them all first.
    ///
    /// `visit` receives the reader itself, so it may read each entry's contents as it goes.
    /// The error type is the consumer's, and the walk's own [`ReadError`]s convert into it,
    /// so a consumer's failure and the volume's each reach the caller as themselves.
    ///
    /// What the walk holds is the frontier — the names reached and not yet visited — rather
    /// than the tree, so a tree far larger than memory is walked without accumulating it.
    /// The frontier answers to the same bound the walk does: the names it holds count
    /// against [`Limits::max_walk_entries`](crate::Limits::max_walk_entries) and the volume's
    /// own directory capacity as the names already visited do.
    ///
    /// # Errors
    ///
    /// Whatever `visit` returns, or the [`walk`](Self::walk) errors converted into it.
    pub fn walk_with<E: From<ReadError>>(
        &mut self,
        mut visit: impl FnMut(&mut Self, WalkEntry) -> Result<(), E>,
    ) -> Result<(), E> {
        crate::walk::drive(self, |reader, placed: Placed| visit(reader, placed.entry))
    }

    /// The child entries of `node` in reverse name order, so a stack pops them in order, each
    /// beside the cluster its own `..` must name.
    ///
    /// `parent` is what `node`'s `..` must name, or `None` where `node` is the root and has
    /// none. Every name here is one a directory can hold: [`parse_dir`](Self::parse_dir) is
    /// the one place an entry's bytes become a name, and it refuses the four that are not
    /// rather than handing one back for a path to be built from.
    fn walk_children(
        &mut self,
        node: &Node,
        prefix: &[u8],
        parent: Option<u32>,
    ) -> Result<Vec<Placed>, ReadError> {
        let policy = self.policy;
        let placement = match parent {
            Some(parent) => Placement::at(prefix, parent),
            None => Placement {
                parent: None,
                path: Some(prefix),
            },
        };
        let mut entries = self.parse_dir(node, placement, &mut OnDeviation::Policy(policy))?;
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        let here = self.parent_mark(node);
        let mut children = Vec::new();
        for e in entries.iter().rev() {
            let path = crate::walk::child_path(prefix, &e.name)
                .ok_or(ReadError::PathTooLong { limit: MAX_PATH })?;
            children.push(Placed {
                entry: WalkEntry { path, node: e.node },
                parent: here,
            });
        }
        Ok(children)
    }

    /// What the `..` of a directory listed in `node` must name: `node`'s first cluster, or
    /// zero where `node` is the root, on FAT32 as well (documented).
    fn parent_mark(&self, node: &Node) -> u32 {
        match (node.storage, self.layout.fat32) {
            (Storage::Chain(start), Some(f)) if start == f.root_cluster => 0,
            (Storage::Chain(start), _) => start,
            (Storage::None | Storage::RootRegion, _) => 0,
        }
    }

    /// The most names the volume's own storage could hold, which bounds a walk regardless
    /// of what a caller asked for.
    ///
    /// Every name spends at least one 32-byte slot, and every slot is in the root region or
    /// in a cluster, so the volume's directory capacity is a hard ceiling that a well-formed
    /// tree can never reach.
    fn max_names(&self) -> usize {
        let root = u64::from(self.layout.root_entries);
        let data = u64::from(self.layout.clusters) * u64::from(self.layout.bytes_per_cluster())
            / DIR_ENTRY_SIZE as u64;
        usize::try_from(root.saturating_add(data)).unwrap_or(usize::MAX)
    }

    // -- verification -----------------------------------------------------------------

    /// Check every copy of the file allocation table against the first.
    ///
    /// This is what a FAT volume has instead of a checksum. Two copies of one allocation
    /// record that disagree mean at least one of them is wrong, and nothing in the volume
    /// says which — so the disagreement is the finding.
    ///
    /// A volume whose mirroring is switched off in `BPB_ExtFlags` keeps only one table live
    /// and the others are not obliged to agree, so nothing is compared and the fact is
    /// reported instead.
    ///
    /// # Errors
    ///
    /// [`ReadError::TableMismatch`] at the first entry two copies disagree about,
    /// [`ReadError::TablePaddingMismatch`] where they differ only past the last entry, and
    /// [`ReadError::Io`] where a table cannot be read.
    pub fn verify_tables(&mut self) -> Result<(), ReadError> {
        match self.table_faults()?.into_iter().next() {
            Some(err) => Err(err),
            None => Ok(()),
        }
    }

    /// Every way the copies of the table disagree, in the order found.
    fn table_faults(&mut self) -> Result<Vec<ReadError>, ReadError> {
        let mut out = Vec::new();
        if self.mirroring_disabled() || self.layout.fats < 2 {
            return Ok(out);
        }
        let fat_type = self.layout.fat_type;
        let sectors = self.layout.fat_sectors;
        let bytes_per_sector = self.layout.bytes_per_sector;
        // Where the entries stop and the formatter's padding begins: one past the last byte
        // the highest cluster's entry touches. The highest cluster *number* is one past the
        // count, and on FAT12 its entry may end in the low nibble of a byte it shares — so
        // the bound is the entry's span rather than the next entry's offset, which on that
        // width is a byte short whenever the highest cluster is even.
        let highest = self.layout.clusters + 1;
        let live_bytes = table::entry_offset(fat_type, highest) + table::entry_span(fat_type);

        for copy in 1..self.layout.fats {
            let mut padding_only = false;
            let mut found = false;
            // Both tables exist: `copy` is below the count and zero always is, so the
            // placement is the layout's rather than something to fall back from.
            let (Some(first_start), Some(copy_start)) = (
                self.layout.fat_start_sector(0),
                self.layout.fat_start_sector(copy),
            ) else {
                continue;
            };
            // Compared a batch of sectors at a time rather than one: the copies of a
            // maximal FAT32 table span megabytes, and a seek and an allocation per
            // 512-byte sector on each side turns one comparison into millions of round
            // trips. A mebibyte per side bounds the memory whatever the table's size.
            let batch = (1u32 << 20) / bytes_per_sector.max(1);
            let mut s = 0u32;
            while s < sectors {
                let count = batch.clamp(1, sectors - s);
                let a = self.read_sectors(first_start + s, count)?;
                let b = self.read_sectors(copy_start + s, count)?;
                if a == b {
                    s += count;
                    continue;
                }
                let base = u64::from(s) * u64::from(bytes_per_sector);
                let at = a
                    .iter()
                    .zip(b.iter())
                    .position(|(x, y)| x != y)
                    .expect("the batches differ") as u64
                    + base;
                if at >= live_bytes {
                    padding_only = true;
                    s += count;
                    continue;
                }
                // The cluster whose entry that byte belongs to. Every width divides the
                // offset the same way its own packing does — except the middle byte of a
                // FAT12 pair, which two entries share: its low nibble is the even one's top
                // four bits and its high nibble is the odd one's bottom four. Both are
                // candidates there, and the finding names whichever actually differs, so a
                // consumer repairing by cluster number repairs the entry that is wrong.
                let (candidate, shared) = match fat_type {
                    FatType::Fat12 => {
                        let even = (at * 2 / 3) as u32;
                        let odd = (at % 3 == 1 && even < highest).then_some(even + 1);
                        (even, odd)
                    }
                    FatType::Fat16 => ((at / 2) as u32, None),
                    FatType::Fat32 => ((at / 4) as u32, None),
                };
                let mut mismatch = None;
                for cluster in [Some(candidate), shared].into_iter().flatten() {
                    let first = self.table_entry_in(0, cluster)?;
                    let other = self.table_entry_in(copy, cluster)?;
                    if first != other {
                        mismatch = Some((cluster, first, other));
                        break;
                    }
                }
                // Every bit of a differing byte belongs to one of the candidates, so one of
                // them differs. The fallback keeps the report total rather than describing a
                // case that can arise.
                let (cluster, first, other) = match mismatch {
                    Some(found) => found,
                    None => (
                        candidate,
                        self.table_entry_in(0, candidate)?,
                        self.table_entry_in(copy, candidate)?,
                    ),
                };
                out.push(ReadError::TableMismatch {
                    copy,
                    cluster,
                    first,
                    other,
                });
                found = true;
                break;
            }
            if !found && padding_only {
                out.push(ReadError::TablePaddingMismatch { copy });
            }
        }
        Ok(out)
    }

    /// The entry for `cluster` in copy `index` of the table, read without the window.
    ///
    /// The window is [`table_entry`](Self::table_entry)'s optimization for a chain walk,
    /// which reads one copy repeatedly; this reads each copy once per differing byte, so it
    /// keeps nothing. What it does keep is that function's bounds — the same ceiling on the
    /// entry, and the same refusal to read past this copy's own end — because the two are
    /// compared against each other and a value only one of them would splice together is not
    /// a disagreement between the copies.
    fn table_entry_in(&mut self, index: u32, cluster: u32) -> Result<u32, ReadError> {
        let fat_type = self.layout.fat_type;
        if cluster >= self.layout.max_table_entries() {
            return Err(ReadError::ClusterOutOfRange { cluster });
        }
        let offset = table::entry_offset(fat_type, cluster);
        let bytes_per_sector = u64::from(self.layout.bytes_per_sector);
        let sector_in_table = u32::try_from(offset / bytes_per_sector)
            .map_err(|_| ReadError::ClusterOutOfRange { cluster })?;
        let within = (offset % bytes_per_sector) as usize;
        let first = self
            .layout
            .fat_start_sector(index)
            .ok_or(ReadError::ClusterOutOfRange { cluster })?;
        let sector = first
            .checked_add(sector_in_table)
            .ok_or(ReadError::ClusterOutOfRange { cluster })?;
        let count = self.table_window_sectors(sector_in_table);
        let bytes = self.read_sectors(sector, count)?;
        let raw = table::read_entry(fat_type, &bytes[within..], 0)
            .ok_or(ReadError::ClusterOutOfRange { cluster })?;
        if fat_type == FatType::Fat12 && cluster & 1 == 1 {
            Ok(u32::from(get_u16(&bytes, within)) >> 4)
        } else {
            Ok(raw)
        }
    }

    /// Whether the parameter block says only one table is live.
    const fn mirroring_disabled(&self) -> bool {
        match self.boot.tail {
            BootSectorTail::Fat32 { params, .. } => params.ext_flags & 0x0080 != 0,
            BootSectorTail::Fat1216 { .. } => false,
        }
    }

    /// The copy of the file allocation table every chain is resolved through.
    ///
    /// `BPB_ExtFlags` bit 7 switches mirroring off; when it is set, bits 0-3 name the one
    /// copy the driver maintains and the rest are stale by design. Following a stale copy
    /// yields a different tree and different file bytes from the ones a conformant driver
    /// returns — and silently, because the mirror check is suppressed on exactly these
    /// volumes, so the disagreement that would otherwise be reported is not there to see.
    ///
    /// With mirroring on, every copy is held identical and copy 0 is as good as any. FAT12
    /// and FAT16 have no such field and always mirror.
    ///
    /// A named copy the volume does not have is incoherent, and there is nothing to resolve
    /// through a table that is not there — so copy 0 is read and [`scan`](Self::scan)
    /// reports the field. Refusing the volume outright would make a one-nibble fault
    /// unreadable where a driver still reads it.
    const fn active_fat(&self) -> u32 {
        match self.boot.tail {
            BootSectorTail::Fat32 { params, .. } if params.ext_flags & 0x0080 != 0 => {
                let index = (params.ext_flags & 0x000F) as u32;
                if index < self.layout.fats { index } else { 0 }
            }
            _ => 0,
        }
    }

    // -- the scan ---------------------------------------------------------------------

    /// Walk the whole volume, collecting every deviation from what this crate's writer
    /// emits rather than stopping at the first.
    ///
    /// The parameter block, the backup boot sector, the information sector, every copy of
    /// the file allocation table, every directory entry, every cluster chain, and the
    /// clusters that are allocated and reached by nothing. Nothing here fails: a scan
    /// describes a volume rather than accepting or refusing it, and
    /// [`ScanReport::has_fatal`] applies a policy's threshold afterwards.
    ///
    /// **Memory.** Reaching the lost-cluster question needs one bit per cluster, which is a
    /// thirty-second of one copy of the table on any volume — so a scan's working set is
    /// bounded by the volume's own geometry and is small beside the structure it is reading.
    /// The count itself is held at open to what the type addresses, so the ceiling is
    /// [`MAX_CLUSTERS_FAT32`](crate::fat::MAX_CLUSTERS_FAT32) bits — 32 MiB, against the
    /// gibibyte of table a volume that large has to carry. Everything else a scan holds is a
    /// sector, a cluster, or one directory's entries.
    #[must_use]
    pub fn scan(&mut self) -> ScanReport {
        let mut findings = Findings::new(self.limits.max_findings);
        for anomaly in self.open_anomalies.clone() {
            findings.push(anomaly);
        }
        if self.volume_dirty {
            findings.push(ReadError::VolumeDirty.anomaly());
        }
        if self.media_failure {
            findings.push(ReadError::MediaFailure.anomaly());
        }
        self.scan_reserved(&mut findings);
        self.scan_tables(&mut findings);
        let reached = self.scan_tree(&mut findings);
        // A scan its source failed did not look at what the failed reads held, so it cannot
        // say what nothing reaches, as a walk cut short cannot.
        let reached = reached.filter(|_| !findings.met_source_failure());
        self.scan_usage(&mut findings, reached.as_ref());
        findings.into_report(self.layout.bytes_per_sector)
    }

    /// The backup boot sector and the information sector, on the type that has them.
    fn scan_reserved(&mut self, findings: &mut Findings<Anomaly>) {
        let Some(fat32) = self.layout.fat32 else {
            return;
        };
        // `BPB_FSVer` is the field a driver reads to decide whether it understands the
        // volume at all: zero is the only version ever defined, and neither Windows nor
        // Linux mounts anything else. A volume carrying another value is one no driver will
        // touch, so a read that said nothing about it would open and scan clean an image
        // that in practice does not exist — against the promise to name the deviation.
        if let BootSectorTail::Fat32 { params, .. } = self.boot.tail
            && params.version != 0
        {
            findings.push(Anomaly {
                severity: Severity::Conformance,
                category: Category::BootSector,
                location: Location::default(),
                detail: format!(
                    "BPB_FSVer is {:#06x}: zero is the only FAT32 version defined, and a \
                     driver refuses a volume whose version it does not know",
                    params.version
                ),
            });
        }
        if let Some(backup) = fat32.backup_boot_sector {
            let backup = u32::from(backup);
            match (self.read_sectors(0, 1), self.read_sectors(backup, 1)) {
                (Ok(mut primary), Ok(mut copy)) => {
                    // A driver marks the volume dirty in the primary alone, so the bit is a
                    // state rather than a difference between the copies, and is reported as
                    // one above.
                    let dirty_at = self.boot.tail.volume_offset() + 1;
                    for sector in [&mut primary, &mut copy] {
                        if let Some(byte) = sector.get_mut(dirty_at) {
                            *byte &= !VOLUME_DIRTY;
                        }
                    }
                    if primary != copy {
                        findings
                            .push(ReadError::BackupBootSectorDiffers { sector: backup }.anomaly());
                    }
                }
                (Err(e), _) | (_, Err(e)) => findings.push(e.anomaly()),
            }
        }
        // The bottom half of the trailing signature, which is two zero bytes. The parser does
        // not require the signature because its top half duplicates the boot signature and a
        // foreign tool may have written that for reasons of its own — an argument that
        // reaches exactly those two bytes and not these. Nothing accounts for a value here,
        // so it is remarked on; the field is inert, so it is a remark and not a fault.
        let info_sector = u32::from(fat32.fs_info_sector);
        if let Ok(bytes) = self.read_sectors(info_sector, 1)
            && let Some(low) = bytes
                .get(FsInfo::TRAIL_OFFSET..FsInfo::TRAIL_OFFSET + 2)
                .map(|b| get_u16(b, 0))
            && low != 0
        {
            findings.push(Anomaly {
                severity: Severity::Cosmetic,
                category: Category::InfoSector,
                location: Location {
                    sector: Some(info_sector),
                    ..Location::default()
                },
                detail: format!(
                    "the information sector's trailing signature carries {low:#06x} where the \
                     format defines two zero bytes"
                ),
            });
        }
        match self.info_sector() {
            Ok(Some(info)) => {
                // Both counts are hints a driver may leave stale, so a stale one is a
                // remark rather than a fault — but it is worth remarking on, because this
                // crate's writer leaves both accurate.
                if let Some(next) = info.next_free_cluster
                    && next >= self.layout.clusters + 2
                {
                    findings.push(Anomaly {
                        severity: Severity::Cosmetic,
                        category: Category::InfoSector,
                        location: Location {
                            sector: Some(u32::from(fat32.fs_info_sector)),
                            cluster: Some(next),
                            entry: None,
                        },
                        detail: format!(
                            "the next-free hint names cluster {next}, which this volume does \
                             not have"
                        ),
                    });
                }
            }
            Ok(None) => {}
            Err(e) => findings.push(e.anomaly()),
        }
    }

    /// The reserved entries of the table, and every copy against the first.
    fn scan_tables(&mut self, findings: &mut Findings<Anomaly>) {
        let fat_type = self.layout.fat_type;
        let expected_media = table::media_entry(fat_type, self.boot.media);
        let expected_tail = table::tail_entry(fat_type);
        // Entry 1's status bits are a state a driver records, reported at open, so they are
        // taken as set here and the comparison is of the rest of the entry.
        let (clean, no_error) = table::status_bits(fat_type);
        for (index, expected, state) in [
            (0u32, expected_media, 0),
            (1, expected_tail, clean | no_error),
        ] {
            match self.table_entry(index) {
                Ok(found) if found | state != expected => findings.push(
                    ReadError::BadReservedEntry {
                        index,
                        found,
                        expected,
                    }
                    .anomaly(),
                ),
                Ok(_) => {}
                Err(e) => findings.push(e.anomaly()),
            }
        }
        if self.mirroring_disabled() {
            let named = match self.boot.tail {
                BootSectorTail::Fat32 { params, .. } => u32::from(params.ext_flags & 0x000F),
                BootSectorTail::Fat1216 { .. } => 0,
            };
            findings.push(Anomaly {
                severity: Severity::Conformance,
                category: Category::AllocationTable,
                location: Location::default(),
                detail: format!(
                    "BPB_ExtFlags switches mirroring off, so only table {named} is live and \
                     the copies are not obliged to agree"
                ),
            });
            // A live copy the volume does not have leaves nothing to resolve chains
            // through. Reads fall back to copy 0, which is a different table from the one
            // the volume names, so the fault is reported at the weight of a wrong read
            // rather than as a cosmetic field.
            if named >= self.layout.fats {
                findings.push(Anomaly {
                    severity: Severity::Integrity,
                    category: Category::AllocationTable,
                    location: Location::default(),
                    detail: format!(
                        "BPB_ExtFlags names table {named} as the live one, but the volume \
                         has {} — chains are resolved through table 0 instead",
                        self.layout.fats
                    ),
                });
            }
            return;
        }
        match self.table_faults() {
            Ok(faults) => {
                for fault in faults {
                    findings.push(fault.anomaly());
                }
            }
            Err(e) => findings.push(e.anomaly()),
        }
    }

    /// Every directory and every chain, returning the clusters the tree reaches.
    ///
    /// Each name is reported by its [label](crate::walk::label), so a tree of any depth is
    /// read whole.
    ///
    /// `None` where the walk did not finish — because the findings cap was reached or a
    /// walk bound was — in which case the lost-cluster question has no answer, since every
    /// cluster the walk never got to would look unreachable. A count derived from a partial
    /// traversal reads as a fact and is not one, so it is not produced at all.
    fn scan_tree(&mut self, findings: &mut Findings<Anomaly>) -> Option<ClusterSet> {
        let mut reached = ClusterSet::new(self.layout.clusters);
        // The directories this walk has descended into, in the same set the clusters it has
        // claimed are held in: both questions are "which clusters has this been to", over the
        // volume's own cluster numbers, and a second structure over them would be a second
        // answer to keep in step.
        let mut visited = ClusterSet::new(self.layout.clusters);
        // Each directory beside what its `..` must name; the root has none to name.
        let mut queue = vec![(Vec::new(), self.root(), None)];
        if let Storage::Chain(start) = self.root().storage {
            visited.insert(start);
        }
        let mut names = 0usize;
        let cap = self.limits.max_walk_entries.min(self.max_names());

        while let Some((label, node, parent)) = queue.pop() {
            if findings.is_full() {
                // The tree is not fully walked, so the clusters it did not reach are not
                // evidence of anything. Saying so is the only honest answer: the
                // alternative is a lost-cluster count computed from a partial traversal,
                // which is a number that reads as a fact and is not one.
                return None;
            }
            // The node's own chain, claimed cluster by cluster so a second claim is a
            // cross-link rather than a second traversal.
            let claimed = self.claim_chain(&node, &label, &mut reached, findings);
            if node.is_dir() {
                let mut deviations = OnDeviation::Collect(findings);
                let placement = Placement {
                    parent,
                    path: Some(&label),
                };
                let entries = match self.parse_dir(&node, placement, &mut deviations) {
                    Ok(entries) => entries,
                    // A directory that alone holds more names than the bound allows stops
                    // the traversal for the same reason the running count below does: what
                    // was not reached is not evidence, and a lost-cluster count taken from a
                    // partial walk reads as a fact and is not one.
                    Err(e @ ReadError::WalkTooLarge { .. }) => {
                        findings.push(e.anomaly());
                        return None;
                    }
                    Err(e) => {
                        findings.push(e.anomaly());
                        continue;
                    }
                };
                let here = self.parent_mark(&node);
                for entry in entries {
                    names += 1;
                    if names > cap {
                        findings.push(ReadError::WalkTooLarge { limit: cap }.anomaly());
                        // Likewise: a walk that stopped short reached fewer clusters than
                        // the tree owns, and every one it did not reach would be reported
                        // as allocated and unreferenced.
                        return None;
                    }
                    let child = crate::walk::label(&label, &entry.name);
                    let descend = match entry.node.storage {
                        Storage::Chain(start) if entry.node.is_dir() => visited.insert(start),
                        _ => false,
                    };
                    if descend || !entry.node.is_dir() {
                        queue.push((child, entry.node, Some(here)));
                    }
                }
            } else if let Some(chain_bytes) = claimed {
                // A file's length is a claim about its clusters, and FAT has no holes, so
                // the two disagreeing is worth saying even where every cluster reads. This
                // compares a length against a chain and so needs one: the shape with no chain
                // at all is `SizeWithoutAllocation`, raised where the entry is parsed.
                let size = u64::from(node.size);
                let bpc = u64::from(self.layout.bytes_per_cluster());
                let need = size.div_ceil(bpc.max(1)) * bpc;
                if chain_bytes != need {
                    findings.push(Anomaly {
                        severity: Severity::Conformance,
                        category: Category::AllocationTable,
                        location: Location::default(),
                        detail: format!(
                            "{}: a length of {size} bytes needs {need} bytes of clusters and \
                             its chain holds {chain_bytes}",
                            crate::escape::printable(&label)
                        ),
                    });
                }
            }
        }
        Some(reached)
    }

    /// Follow one node's chain, marking each cluster reached and reporting a cluster two
    /// chains both claim. Returns the bytes the chain holds, where it could be followed.
    fn claim_chain(
        &mut self,
        node: &Node,
        path: &[u8],
        reached: &mut ClusterSet,
        findings: &mut Findings<Anomaly>,
    ) -> Option<u64> {
        let Storage::Chain(start) = node.storage else {
            return None;
        };
        let mut current = start;
        let mut count = 0u64;
        let mut own = std::collections::HashSet::new();
        loop {
            if !reached.insert(current) {
                // Whose claim is repeated decides what the finding says: a cluster this
                // walk already stepped through is the chain looping onto itself, and one
                // another walk claimed is two chains sharing storage. Blaming "another
                // chain" for a loop would send a reader hunting for a second file that
                // does not exist.
                let detail = if own.contains(&current) {
                    format!(
                        "{}: the chain from cluster {start} returns to cluster {current}, \
                         and a chain that loops never ends",
                        crate::escape::printable(path)
                    )
                } else {
                    format!(
                        "{}: cluster {current} is already part of another chain",
                        crate::escape::printable(path)
                    )
                };
                findings.push(Anomaly {
                    severity: Severity::Structural,
                    category: Category::AllocationTable,
                    location: Location {
                        cluster: Some(current),
                        ..Location::default()
                    },
                    detail,
                });
                return None;
            }
            own.insert(current);
            count += 1;
            if count > u64::from(self.layout.clusters) {
                findings.push(
                    ReadError::ChainTooLong {
                        start,
                        clusters: self.layout.clusters,
                    }
                    .anomaly(),
                );
                return None;
            }
            match self.next_cluster(current) {
                Ok(Some(next)) => current = next,
                Ok(None) => break,
                Err(e) => {
                    findings.push(e.anomaly());
                    return None;
                }
            }
        }
        Some(count * u64::from(self.layout.bytes_per_cluster()))
    }

    /// Count what the table says of every cluster: free, and allocated with no chain in
    /// `reached` holding it. Without `reached`, nothing is counted lost.
    fn census(&mut self, reached: Option<&ClusterSet>) -> Census {
        let bad = table::bad_cluster(self.layout.fat_type);
        let mut census = Census {
            free: 0,
            lost: 0,
            first_lost: None,
            failed: None,
        };
        for cluster in 2..self.layout.clusters + 2 {
            let entry = match self.table_entry(cluster) {
                Ok(entry) => entry,
                Err(e) => {
                    census.failed = Some(e);
                    break;
                }
            };
            if entry == table::FREE {
                census.free += 1;
                continue;
            }
            if entry == bad || reached.is_none_or(|reached| reached.contains(cluster)) {
                continue;
            }
            census.lost += 1;
            census.first_lost.get_or_insert(cluster);
        }
        census
    }

    /// What the table says of every cluster: the ones it marks allocated that no chain
    /// reached, where `reached` is the whole tree's, and the ones it marks free, against the
    /// count the information sector keeps.
    fn scan_usage(&mut self, findings: &mut Findings<Anomaly>, reached: Option<&ClusterSet>) {
        // A table that cannot be read past where the census stopped has already been reported
        // by whatever tried to follow a chain through it, and neither count is whole.
        let Census {
            free,
            lost,
            first_lost: first,
            failed,
        } = self.census(reached);
        let whole = failed.is_none();
        if let Some(first) = first {
            findings.push(ReadError::LostClusters { count: lost, first }.anomaly());
        }
        // The information sector's count of free clusters, on the type that has one: a value
        // past the clusters is one no driver kept, and one that is merely out of date is a
        // hint nobody was obliged to update.
        let Ok(Some(info)) = self.info_sector() else {
            return;
        };
        let Some(stated) = info.free_clusters else {
            return;
        };
        let sector = self.layout.fat32.map(|f| u32::from(f.fs_info_sector));
        let at = Location {
            sector,
            ..Location::default()
        };
        let err = if stated > self.layout.clusters {
            ReadError::FreeCountOutOfRange {
                stated,
                clusters: self.layout.clusters,
            }
        } else if whole && stated != free {
            ReadError::FreeCountStale {
                stated,
                counted: free,
            }
        } else {
            return;
        };
        let mut anomaly = err.anomaly();
        anomaly.location = anomaly.location.or(at);
        findings.push(anomaly);
    }
}

/// What the table says of every cluster, counted once for a scan and for a volume's usage.
struct Census {
    /// The clusters it marks free.
    free: u32,
    /// The clusters it marks allocated that no chain the census was handed holds.
    lost: u32,
    /// The first of those.
    first_lost: Option<u32>,
    /// Where a read of the table failed, which stops the count there.
    failed: Option<ReadError>,
}

/// One 32-byte slot of a directory, with where it sits: its index within the directory, and
/// the sector holding it.
struct Slot {
    entry: DirEntry,
    index: u32,
    sector: u32,
}

/// A dense set over the volume's clusters, one bit each.
///
/// Sized from the count the parameter block reaches, which is a bound rather than a claim:
/// the geometry refuses a count above what the type addresses and one whose sectors do not
/// fit in the source, so the widest set this reaches is
/// [`MAX_CLUSTERS_FAT32`](super::geometry::MAX_CLUSTERS_FAT32) bits — a thirty-second of the
/// one copy of the table such a volume must carry to describe those clusters at all.
///
/// This is the one answer to "which clusters has this been to", and every question of that
/// shape asks it: the chain a directory follows, the directories a scan has descended into,
/// and the clusters a scan has claimed. The domain is the same in all three — a cluster number
/// of this volume — and a second structure over it would be a second answer to keep in step.
struct ClusterSet {
    bits: Vec<u64>,
    clusters: u32,
}

impl ClusterSet {
    fn new(clusters: u32) -> Self {
        // Clusters number from 2, so the set is sized for the highest number rather than
        // for the count.
        let highest = clusters as usize + 2;
        Self {
            bits: vec![0u64; highest.div_ceil(64)],
            clusters,
        }
    }

    /// Add `cluster`, answering whether it was not already there.
    fn insert(&mut self, cluster: u32) -> bool {
        if cluster < 2 || cluster - 2 >= self.clusters {
            return true;
        }
        let (word, bit) = (cluster as usize / 64, cluster as usize % 64);
        let was = self.bits[word] & (1 << bit) != 0;
        self.bits[word] |= 1 << bit;
        !was
    }

    fn contains(&self, cluster: u32) -> bool {
        if cluster < 2 || cluster - 2 >= self.clusters {
            return false;
        }
        self.bits[cluster as usize / 64] & (1 << (cluster as usize % 64)) != 0
    }
}

/// What a run of long-name entries came to.
enum LongRun {
    /// There was none.
    None,
    /// There was one and it is not a whole name.
    Incomplete,
    /// A whole name, the checksum its entries claim to be for, and whether its slots past the
    /// name are filled the way the format fills them.
    Complete {
        units: Vec<u16>,
        checksum: u8,
        padded: bool,
    },
}

/// A run of long-name entries being assembled.
///
/// The entries sit immediately before their short entry and in reverse order, so the first
/// one a forward reader meets carries the name's last characters and is flagged as the last
/// in the sequence. Chunks are placed by their ordinal rather than appended, so a run whose
/// ordinals skip or repeat comes out incomplete rather than silently reordered.
#[derive(Default)]
struct LongName {
    chunks: Vec<Option<[u16; LFN_CHARS_PER_ENTRY]>>,
    checksum: Option<u8>,
    broken: bool,
}

impl LongName {
    fn clear(&mut self) {
        self.chunks.clear();
        self.checksum = None;
        self.broken = false;
    }

    /// Fold one entry into the run, answering whether a run still being assembled was
    /// discarded to start over.
    ///
    /// The last-in-sequence flag opens a new run whatever preceded it, so one arriving
    /// mid-run wipes what was in flight — slots that then belong to nothing, which is the
    /// caller's to report since only it knows where they sit.
    fn accept(&mut self, entry: &LfnEntry) -> bool {
        let ordinal = usize::from(entry.order & !LFN_LAST_ENTRY);
        let mut discarded = false;
        if entry.order & LFN_LAST_ENTRY != 0 {
            // The last in the sequence starts a new run, whatever preceded it.
            discarded = self.is_live();
            self.clear();
            if ordinal == 0 || ordinal > LFN_MAX_ENTRIES {
                self.broken = true;
                return discarded;
            }
            self.chunks = vec![None; ordinal];
            self.checksum = Some(entry.checksum);
        }
        if ordinal == 0 || ordinal > self.chunks.len() || self.checksum != Some(entry.checksum) {
            self.broken = true;
            return discarded;
        }
        if self.chunks[ordinal - 1].is_some() {
            self.broken = true;
            return discarded;
        }
        self.chunks[ordinal - 1] = Some(entry.name);
        discarded
    }

    /// Whether a run is being assembled: entries accepted and not yet taken.
    fn is_live(&self) -> bool {
        !self.chunks.is_empty() || self.broken
    }

    fn take(&mut self) -> LongRun {
        let run = if self.chunks.is_empty() && !self.broken {
            LongRun::None
        } else if self.broken || self.chunks.iter().any(Option::is_none) {
            LongRun::Incomplete
        } else {
            let mut units = Vec::with_capacity(self.chunks.len() * LFN_CHARS_PER_ENTRY);
            for chunk in self.chunks.iter().flatten() {
                units.extend_from_slice(chunk);
            }
            // A name shorter than the entries holding it is terminated by one zero and
            // padded after it; one that fills them exactly has neither. Either value ends the
            // name, so a run padded with no zero in front of the padding does not hand the
            // padding back as characters.
            let mut padded = true;
            if let Some(end) = units.iter().position(|u| *u == 0 || *u == LFN_PADDING) {
                let after = if units[end] == 0 { end + 1 } else { end };
                padded = units[end] == 0 && units[after..].iter().all(|u| *u == LFN_PADDING);
                units.truncate(end);
            }
            match self.checksum {
                Some(checksum) => LongRun::Complete {
                    units,
                    checksum,
                    padded,
                },
                None => LongRun::Incomplete,
            }
        };
        self.clear();
        run
    }
}

/// A directory entry's bytes, for handing to the long-name parser.
///
/// A long-name entry and a short one occupy the same 32 bytes and differ only in how they
/// are read, so the short parse is undone and the bytes re-laid rather than the region being
/// read twice from the source.
fn raw_bytes(entry: &DirEntry) -> [u8; DIR_ENTRY_SIZE] {
    let mut buf = [0u8; DIR_ENTRY_SIZE];
    // The write cannot be short: the buffer is exactly the structure's size.
    let _ = entry.write_to(&mut buf);
    buf
}

/// Bit of a directory entry's byte 12 meaning the eight-character base is lower case.
const NT_LOWER_BASE: u8 = 0x08;

/// Bit of a directory entry's byte 12 meaning the three-character extension is lower case.
const NT_LOWER_EXT: u8 = 0x10;

/// The eleven-byte name field as a name: padding trimmed, the dot restored, the substituted
/// leading byte put back, and the case flags at byte 12 applied.
///
/// **The case flags are honoured here and never written.** Byte 12 is reserved by the
/// format's own specification, which says an implementation must never look at it, and
/// implementations take it at its word — Linux honours it under two of its four
/// `shortname=` settings and ignores it under the other two, and a minimal firmware driver
/// skips it entirely. So a name carried only there is `readme.txt` on one mount and
/// `README.TXT` on another, which is why this crate's writer gives every such name a
/// long-name run instead. Reading is the opposite call for the opposite reason: understanding
/// what somebody else wrote costs nothing, and a volume that used the flags meant the name
/// the flags describe.
///
/// The folding is over ASCII alone. A byte above ASCII has no case without the code page the
/// volume does not record, and inventing one would be a name the entry does not carry.
fn render_short(name: &[u8; 11], case_flags: u8) -> Vec<u8> {
    let fold = |bytes: &mut Vec<u8>, lower: bool| {
        if lower {
            bytes.make_ascii_lowercase();
        }
    };
    let mut base = name[..8].to_vec();
    while base.last() == Some(&b' ') {
        base.pop();
    }
    if base.first() == Some(&NAME_LEADING_E5) {
        base[0] = NAME_DELETED;
    }
    fold(&mut base, case_flags & NT_LOWER_BASE != 0);
    let mut ext = name[8..].to_vec();
    while ext.last() == Some(&b' ') {
        ext.pop();
    }
    fold(&mut ext, case_flags & NT_LOWER_EXT != 0);
    if ext.is_empty() {
        base
    } else {
        base.push(b'.');
        base.extend_from_slice(&ext);
        base
    }
}

/// The volume label an eleven-byte name field holds.
///
/// Three things separate this from the field's plain padding rule
/// ([`unpadded`](crate::fat::ondisk::unpadded)), which is why it is its own function rather
/// than a call to that one. A label has no dot and no extension, so the eleven bytes are one
/// field rather than a base and a three-byte tail. A NUL is trimmed here as well as a space,
/// because a formatter that filled the field with either wrote the same label. And the
/// leading-byte substitution is undone.
fn volume_label(name: &[u8; 11]) -> Vec<u8> {
    let mut end = name.len();
    while end > 0 && (name[end - 1] == b' ' || name[end - 1] == 0) {
        end -= 1;
    }
    let mut out = name[..end].to_vec();
    // The substitution a leading `0xE5` takes on disk, undone. `0xE5` in the first byte is
    // the deleted marker, so a name really beginning with it is stored as `0x05` — and a
    // label read back without undoing that is one byte different from the label that was
    // set. The short-name renderer does this; a label bypasses it, since a label is one
    // eleven-byte field rather than a base and an extension.
    if out.first() == Some(&NAME_LEADING_E5) {
        out[0] = 0xE5;
    }
    out
}

/// UTF-16 code units as UTF-8 bytes, and whether any unit stood for no character.
///
/// A unit with no partner is replaced rather than refused, so a tree carrying one is still
/// enumerable; the caller raises the deviation.
fn decode_utf16(units: &[u16]) -> (Vec<u8>, bool) {
    let mut ill_formed = false;
    let text: String = char::decode_utf16(units.iter().copied())
        .map(|r| {
            r.unwrap_or_else(|_| {
                ill_formed = true;
                char::REPLACEMENT_CHARACTER
            })
        })
        .collect();
    (text.into_bytes(), ill_formed)
}

/// Judge the three times a directory entry records, each against the range the encoding
/// defines for its fields.
///
/// A read hands back the instant the arithmetic reaches, which is what every driver does and
/// what [`DosTimestamp::decode`] documents deferring. This is the site it defers to: month
/// zero, day 31 of February, a twenty-fifth hour and a hundredths byte past 199 are each a
/// field no encoder produces and an image may carry.
///
/// The write time is the one the format requires. The creation and access times are optional,
/// and a wholly zero field is how the format records that an implementation did not keep them
/// — so a zero field is passed over rather than reported as the month-zero date it spells.
/// Nothing short of the whole field counts: a zero date beside a time that is not zero is a
/// field that was written, and written wrongly.
///
/// The access field is a date and no time, and the write field has no hundredths byte, so each
/// is judged with zero in place of what the format does not give it.
fn check_times(
    entry: &DirEntry,
    index: u32,
    at: Location,
    deviations: &mut OnDeviation<'_>,
) -> Result<(), ReadError> {
    let optional = [
        (
            "creation time",
            DosTimestamp {
                date: entry.create_date,
                time: entry.create_time,
                tenth: entry.create_time_tenth,
            },
        ),
        (
            "access time",
            DosTimestamp {
                date: entry.access_date,
                time: 0,
                tenth: 0,
            },
        ),
    ];
    for (field, stamp) in optional {
        if stamp != DosTimestamp::default() && !stamp.is_well_formed() {
            deviations.record(at, ReadError::MalformedTimestamp { index, field })?;
        }
    }
    let write = DosTimestamp {
        date: entry.write_date,
        time: entry.write_time,
        tenth: 0,
    };
    if !write.is_well_formed() {
        deviations.record(
            at,
            ReadError::MalformedTimestamp {
                index,
                field: "modification time",
            },
        )?;
    }
    Ok(())
}

/// Whether an entry with these attributes is a volume label: the volume-label attribute,
/// and neither the long-name combination nor the directory attribute.
///
/// The one definition both [`Reader::volume_label`] and a directory read hold an entry to.
/// The pinned `fsck.fat` and `mlabel` take an entry carrying the directory attribute as well
/// for no label (observed).
fn is_volume_label(attributes: DirAttributes) -> bool {
    attributes.contains(DirAttributes::VOLUME_ID)
        && !attributes.is_long_name()
        && !attributes.contains(DirAttributes::DIRECTORY)
}

/// The names a driver finds `entry` by, each folded as it compares them: its name, and its
/// short name where that is a second one.
///
/// The fold is the writer's, `fat/name.rs`'s `folded`, so a pair this reports is a pair the
/// writer refuses. A name that is not UTF-8 — a short name read under no code page — is
/// folded in its ASCII letters alone.
fn lookup_keys(entry: &Entry) -> Vec<Vec<u8>> {
    let fold = |name: &[u8]| {
        super::name::folded(name).map_or_else(|| name.to_ascii_lowercase(), String::into_bytes)
    };
    let name = fold(&entry.name);
    let short = fold(&entry.short_name);
    if short == name {
        vec![name]
    } else {
        vec![name, short]
    }
}

/// The first cluster a directory entry names.
fn first_cluster(entry: &DirEntry, fat_type: FatType) -> u32 {
    // The high half of the first cluster number is not part of it on FAT12 and FAT16, where
    // a driver of that era left whatever it liked in those two bytes. Joining them there
    // would read that as an address.
    match fat_type {
        FatType::Fat32 => {
            (u32::from(entry.first_cluster_hi) << 16) | u32::from(entry.first_cluster_lo)
        }
        FatType::Fat12 | FatType::Fat16 => u32::from(entry.first_cluster_lo),
    }
}

/// The node a directory entry describes.
fn node_of(entry: &DirEntry, fat_type: FatType) -> Node {
    let first = first_cluster(entry, fat_type);
    Node {
        storage: if first < 2 {
            Storage::None
        } else {
            Storage::Chain(first)
        },
        attributes: entry.attributes,
        size: entry.size,
        times: Some(Times {
            create: Some(DosTimestamp {
                date: entry.create_date,
                time: entry.create_time,
                tenth: entry.create_time_tenth,
            })
            .filter(|stamp| *stamp != DosTimestamp::default())
            .map(DosTimestamp::decode),
            access: (entry.access_date != 0).then(|| {
                DosTimestamp {
                    date: entry.access_date,
                    time: 0,
                    tenth: 0,
                }
                .decode()
            }),
            modify: DosTimestamp {
                date: entry.write_date,
                time: entry.write_time,
                tenth: 0,
            }
            .decode(),
        }),
    }
}

/// The FAT family's implementation of the crate's extraction surface.
///
/// The node handle is [`Node`], which the walk already read, so a sink that stats and then
/// reads a file costs no second lookup of it.
impl<R: Read + Seek> FsTree for Reader<R> {
    type Node = Node;

    fn family(&self) -> Family {
        Family::Fat
    }

    fn max_file_bytes(&self) -> u64 {
        self.limits.max_file_bytes
    }

    fn walk_tree<E, F>(&mut self, mut visit: F) -> Result<(), E>
    where
        E: From<TreeError>,
        F: FnMut(&mut Self, TreeEntry<Node>) -> Result<(), E>,
    {
        // The root has no name, so the walk does not reach it. Yielding it first under the
        // empty path is what lets a sink apply the root's own metadata without a second way
        // of asking for it — even though on this family there is none to apply, which the
        // stat says by naming everything it filled in.
        let root = self.root();
        visit(self, TreeEntry::new(Vec::new(), NodeKind::Directory, root))?;

        let outcome = self.walk_with::<WalkFail<E>>(|reader, entry| {
            let kind = node_kind(&entry.node);
            // No `shared`: the format has no second name for a node, so two paths are
            // always two nodes.
            visit(reader, TreeEntry::new(entry.path, kind, entry.node)).map_err(WalkFail::Visitor)
        });
        match outcome {
            Ok(()) => Ok(()),
            Err(WalkFail::Read(e)) => Err(E::from(TreeError::from(e))),
            // Nothing above produces one: a FAT node is a directory or a file, and both are
            // kinds the shared frame has. The arm is here because the failure is the shared
            // surface's rather than this family's, so a later kind that cannot be described
            // reports through it.
            Err(WalkFail::Tree(e)) => Err(E::from(e)),
            Err(WalkFail::Visitor(e)) => Err(e),
        }
    }

    fn stat(&mut self, node: &Node, synthesis: &Synthesis) -> Result<Attributes, TreeError> {
        // A FAT volume's whole record of a node is a read-only bit and two times, which is
        // exFAT's too — so what a read of one invents has a single home, beside the one that
        // says what a write of one loses.
        Ok(Attributes::from_read_only_bit(
            synthesis,
            node.is_dir(),
            node.attributes.contains(DirAttributes::READ_ONLY),
            node.times.map(|t| (t.access, t.modify, t.create)),
        ))
    }

    fn read_bytes(&mut self, node: &Node, offset: u64, buf: &mut [u8]) -> Result<usize, TreeError> {
        Ok(Reader::read_into(self, node, offset, buf)?)
    }

    fn link_target(&mut self, _node: &Node) -> Result<Vec<u8>, TreeError> {
        // The format has no symbolic links, so no node a walk yields is one and this is
        // reached only by a caller that did not look at the kind it was handed.
        Err(TreeError::Malformed {
            family: Family::Fat,
            detail: "a FAT volume holds no symbolic links".to_string(),
        })
    }

    fn find(&mut self, path: &[u8]) -> Result<Child<Node>, TreeError> {
        let node = self.lookup(path).map_err(|e| match e {
            ReadError::NotFound { .. } | ReadError::NotADirectory { .. } => TreeError::NotFound {
                family: Family::Fat,
                path: path.to_vec(),
            },
            other => TreeError::from(other),
        })?;
        Ok(Child::new(
            crate::tree::last_name(path),
            node_kind(&node),
            node,
        ))
    }

    fn list(&mut self, dir: &Node) -> Result<Vec<Child<Node>>, TreeError> {
        if !dir.is_dir() {
            return Err(crate::tree::not_a_directory(Family::Fat));
        }
        let entries = self.read_dir(dir)?.into_iter().map(|e| (e.name, e.node));
        Ok(crate::tree::listed(Family::Fat, entries)?
            .into_iter()
            .map(|(name, node)| Child::new(name, node_kind(&node), node))
            .collect())
    }

    /// In clusters: the volume's cluster count, and the clusters its table marks free. The
    /// information sector's free count is a hint a driver need not keep, so it is not read.
    fn usage(&mut self) -> Result<Usage, TreeError> {
        let census = self.census(None);
        if let Some(e) = census.failed {
            return Err(e.into());
        }
        Ok(Usage::new(
            u64::from(self.layout.bytes_per_cluster()),
            u64::from(self.layout.clusters),
            u64::from(census.free),
        ))
    }
}

/// What a node is, in the shared frame's words: the one projection a walk, a lookup and a
/// listing all go through. A FAT node is a directory or a file and nothing else.
fn node_kind(node: &Node) -> NodeKind {
    if node.is_dir() {
        NodeKind::Directory
    } else {
        NodeKind::File {
            size: u64::from(node.size),
        }
    }
}

/// The shared walk failure over this family's read error.
type WalkFail<E> = crate::tree::WalkFail<ReadError, E>;

/// What makes `?` on a [`ReadError`] work inside a walk through the shared surface. Written
/// per family because a blanket implementation would collide with the reflexive one.
impl<E> From<ReadError> for WalkFail<E> {
    fn from(err: ReadError) -> Self {
        WalkFail::Read(err)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fat::{
        BootCode, ClusterSize, DiskGeometry, FatTypeRequest, FormatOptions, Image, MEDIA_REMOVABLE,
        PlanRequest, ReservedSectors, VolumeLabel, format,
    };
    use crate::path::canonical_parts;
    use crate::source::{Metadata, TreeBuilder};
    use std::io::Cursor;

    /// The instant every fixture stamps with: 2015-03-14T09:26:52Z, on a two-second boundary
    /// so that nothing under test is also exercising the hundredths field.
    const TIME: Timestamp = Timestamp::from_secs(1_426_325_212);

    fn options() -> FormatOptions {
        FormatOptions::new(0x1234_abcd, TIME)
    }

    /// A tree holding every naming shape the writer distinguishes.
    fn tree() -> TreeBuilder {
        let m = |mode| Metadata::new(mode, TIME);
        TreeBuilder::new()
            .directory(b"/EFI".to_vec(), m(0o755))
            .directory(b"/EFI/BOOT".to_vec(), m(0o755))
            // Already its own short name: the writer gives it no long-name run.
            .file(
                b"/EFI/BOOT/BOOTX64.EFI".to_vec(),
                b"MZ\x90\x00".to_vec(),
                m(0o644),
            )
            // Lower case, so it needs one.
            .file(b"/readme.txt".to_vec(), b"hello\n".to_vec(), m(0o644))
            // Long enough to be shortened, and a second that shortens alike so the tail
            // numbering is exercised.
            .file(
                b"/a-long-file-name.text".to_vec(),
                vec![b'x'; 5000],
                m(0o644),
            )
            .file(
                b"/a-long-file-name-two.text".to_vec(),
                b"two".to_vec(),
                m(0o644),
            )
            // Owning no cluster at all.
            .file(b"/empty".to_vec(), Vec::new(), m(0o444))
    }

    /// A populated volume of `mib` mebibytes at the given type.
    fn image(mib: u64, request: FatTypeRequest) -> Image {
        let opts = options()
            .label(VolumeLabel::new("FERROSYS").expect("label"))
            .plan(PlanRequest::new(0).fat_type(request));
        format(tree(), mib << 20, opts).expect("format")
    }

    /// The three types, each on a volume large enough to reach it.
    fn each_type() -> [(FatType, Image); 3] {
        [
            (
                FatType::Fat12,
                image(2, FatTypeRequest::Exactly(FatType::Fat12)),
            ),
            (
                FatType::Fat16,
                image(64, FatTypeRequest::Exactly(FatType::Fat16)),
            ),
            (
                FatType::Fat32,
                image(512, FatTypeRequest::Exactly(FatType::Fat32)),
            ),
        ]
    }

    fn reader(image: &Image) -> Reader<Cursor<&[u8]>> {
        Reader::open(Cursor::new(image.as_bytes())).expect("open")
    }

    /// The byte offset of sector `n`.
    fn at(layout: &FatLayout, sector: u32) -> usize {
        sector as usize * layout.bytes_per_sector as usize
    }

    #[test]
    fn a_table_read_never_reaches_past_the_copy_it_is_in() {
        // The copies are laid end to end, so one sector past the live table is the *next*
        // copy's first entry. Reading it would splice that byte onto a FAT12 entry that
        // straddles the boundary, and the value would belong to neither copy. Both ways of
        // reading an entry — the chain walk's window and the mirror comparison — take the
        // rule from here, which is what makes them agree on every entry they both reach.
        for (_, image) in each_type() {
            let r = reader(&image);
            let last = r.layout.fat_sectors - 1;
            assert_eq!(
                r.table_window_sectors(last),
                1,
                "the copy's last sector has no next sector of its own"
            );
            assert_eq!(r.table_window_sectors(last.saturating_sub(1)), 2);
            // A sector index past the table entirely — which no bounded caller produces —
            // still asks for no second sector.
            assert_eq!(r.table_window_sectors(u32::MAX), 1);
        }
    }

    #[test]
    fn the_layout_read_back_is_the_layout_planned() {
        // The planner's output and the reader's recovery are two derivations of one thing
        // from disjoint inputs — a request on one side and the bytes on the other — so their
        // agreeing is what says the boot sector records the whole geometry.
        for (what, image) in each_type() {
            let r = reader(&image);
            assert_eq!(r.layout(), image.layout(), "{what}");
            assert_eq!(r.fat_type(), what);
        }
    }

    #[test]
    fn every_name_the_writer_placed_reads_back() {
        for (what, image) in each_type() {
            let mut r = reader(&image);
            let mut paths: Vec<Vec<u8>> = r
                .walk()
                .expect("walk")
                .into_iter()
                .map(|e| e.path)
                .collect();
            paths.sort();
            let expected: Vec<&[u8]> = vec![
                b"/EFI",
                b"/EFI/BOOT",
                b"/EFI/BOOT/BOOTX64.EFI",
                b"/a-long-file-name-two.text",
                b"/a-long-file-name.text",
                b"/empty",
                b"/readme.txt",
            ];
            let got: Vec<&[u8]> = paths.iter().map(Vec::as_slice).collect();
            assert_eq!(got, expected, "{what}");
        }
    }

    #[test]
    fn every_file_reads_back_byte_for_byte() {
        for (what, image) in each_type() {
            let mut r = reader(&image);
            for (path, expected) in [
                (&b"/EFI/BOOT/BOOTX64.EFI"[..], b"MZ\x90\x00".to_vec()),
                (b"/readme.txt", b"hello\n".to_vec()),
                (b"/a-long-file-name.text", vec![b'x'; 5000]),
                (b"/a-long-file-name-two.text", b"two".to_vec()),
                (b"/empty", Vec::new()),
            ] {
                let node = r.lookup(path).unwrap_or_else(|e| {
                    panic!("{what}: {} not found: {e}", String::from_utf8_lossy(path))
                });
                assert_eq!(u64::from(node.size), expected.len() as u64, "{what}");
                assert_eq!(
                    r.read_data(&node).expect("read"),
                    expected,
                    "{what}: {}",
                    String::from_utf8_lossy(path)
                );
            }
        }
    }

    #[test]
    fn a_multi_cluster_file_reads_the_same_whole_as_it_does_in_pieces() {
        // The chain cursor is what makes a sequential read one pass rather than one per
        // call, and a cursor that resumed at the wrong index would show up here and nowhere
        // else: the whole-file path and the piecewise path would disagree.
        for (what, image) in each_type() {
            let mut r = reader(&image);
            let node = r.lookup(b"/a-long-file-name.text").expect("lookup");
            let whole = r.read_data(&node).expect("whole");
            for chunk in [1usize, 7, 512, 4096] {
                let mut pieces = Vec::new();
                let mut buf = vec![0u8; chunk];
                let mut offset = 0u64;
                loop {
                    let got = r.read_into(&node, offset, &mut buf).expect("piece");
                    if got == 0 {
                        break;
                    }
                    pieces.extend_from_slice(&buf[..got]);
                    offset += got as u64;
                }
                assert_eq!(pieces, whole, "{what}: in {chunk}-byte pieces");
            }
            // And backwards, which the cursor cannot resume from and must restart for.
            let mut buf = [0u8; 16];
            for start in (0..whole.len()).step_by(997).rev() {
                let got = r
                    .read_into(&node, start as u64, &mut buf)
                    .expect("backwards");
                assert_eq!(&buf[..got], &whole[start..start + got], "{what}");
            }
        }
    }

    #[test]
    fn a_short_name_is_kept_beside_the_name_and_says_whether_a_long_one_was_used() {
        // The case-byte decision observed from the reading side: a name that is already its
        // own short name has no long-name run, and one that is not does. A writer that used
        // the reserved case byte instead would show `has_long_name` false for `readme.txt`.
        for (what, image) in each_type() {
            let mut r = reader(&image);
            let root = r.root();
            let entries = r.read_dir(&root).expect("read the root");
            let by_name = |n: &[u8]| {
                entries
                    .iter()
                    .find(|e| e.name == n)
                    .unwrap_or_else(|| panic!("{what}: {} absent", String::from_utf8_lossy(n)))
            };
            let readme = by_name(b"readme.txt");
            assert!(readme.has_long_name, "{what}");
            assert_eq!(readme.short_name, b"README.TXT", "{what}");

            // The two that shorten alike take different short names, and the reader sees
            // both of them.
            let one = by_name(b"a-long-file-name.text");
            let two = by_name(b"a-long-file-name-two.text");
            assert_ne!(one.short_name, two.short_name, "{what}");

            let efi = r.lookup(b"/EFI/BOOT").expect("lookup");
            let boot = r.read_dir(&efi).expect("read");
            let payload = boot
                .iter()
                .find(|e| e.name == b"BOOTX64.EFI")
                .expect("entry");
            assert!(
                !payload.has_long_name,
                "{what}: a name that is its own short name took a long-name run"
            );
            assert_eq!(payload.short_name, b"BOOTX64.EFI");
        }
    }

    #[test]
    fn a_name_is_found_by_its_short_alias_as_well_as_by_its_long_name() {
        // The 8.3 alias is a name the volume holds for an entry, and the one a short-name
        // consumer knows it by: a listing shows it, so a lookup must reach it, through a
        // directory reached by its own alias as well as through a file. Exactly and folded
        // alike, as a long name is.
        let m = |mode| Metadata::new(mode, TIME);
        let source = TreeBuilder::new()
            .directory(b"/Long directory name".to_vec(), m(0o755))
            .file(
                b"/Long directory name/Long filename.txt".to_vec(),
                b"alias contents".to_vec(),
                m(0o644),
            );
        for request in [FatType::Fat12, FatType::Fat16, FatType::Fat32] {
            let mib = match request {
                FatType::Fat12 => 2,
                FatType::Fat16 => 64,
                FatType::Fat32 => 512,
            };
            let opts =
                options().plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(request)));
            let image = format(source.clone(), mib << 20, opts).expect("format");
            let mut r = reader(&image);
            let root = r.root();
            let dir = r
                .read_dir(&root)
                .expect("read the root")
                .into_iter()
                .find(|e| e.name == b"Long directory name")
                .expect("the directory");
            let inner = r.read_dir(&dir.node).expect("read the directory");
            let file = inner
                .iter()
                .find(|e| e.name == b"Long filename.txt")
                .expect("the file");
            assert!(dir.has_long_name && file.has_long_name, "{request:?}");
            assert_ne!(file.short_name, file.name, "{request:?}");

            let by_long = r
                .lookup(b"/Long directory name/Long filename.txt")
                .expect("the long names resolve");
            let alias = |bytes: &[u8]| String::from_utf8(bytes.to_vec()).expect("ASCII");
            let (dir_alias, file_alias) = (alias(&dir.short_name), alias(&file.short_name));
            for path in [
                format!("/{dir_alias}/{file_alias}"),
                format!(
                    "/{}/{}",
                    dir_alias.to_lowercase(),
                    file_alias.to_lowercase()
                ),
                format!("/Long directory name/{file_alias}"),
                format!("/{dir_alias}/Long filename.txt"),
            ] {
                let found = r
                    .lookup(path.as_bytes())
                    .unwrap_or_else(|e| panic!("{request:?}: {path} does not resolve: {e}"));
                assert_eq!(found, by_long, "{request:?}: {path}");
                assert_eq!(
                    r.read_data(&found).expect("read"),
                    b"alias contents",
                    "{request:?}: {path}"
                );
            }
        }
    }

    #[test]
    fn the_case_flags_are_honoured_on_reading_and_never_written() {
        // The writer leaves byte 12 zero on every entry, so nothing in an image this crate
        // wrote depends on it.
        for (what, image) in each_type() {
            let mut r = reader(&image);
            let root = r.root();
            r.for_each_slot::<ReadError>(&root, |_, slot| {
                assert_eq!(
                    slot.entry.case_flags, 0,
                    "{what}: the writer set a reserved case flag"
                );
                Ok(ControlFlow::Continue(()))
            })
            .expect("raw");
        }
        // And read back, the flags mean what Windows means by them.
        assert_eq!(render_short(b"README  TXT", 0), b"README.TXT");
        assert_eq!(render_short(b"README  TXT", NT_LOWER_BASE), b"readme.TXT");
        assert_eq!(render_short(b"README  TXT", NT_LOWER_EXT), b"README.txt");
        assert_eq!(
            render_short(b"README  TXT", NT_LOWER_BASE | NT_LOWER_EXT),
            b"readme.txt"
        );
        // A byte above ASCII has no case without the code page the volume does not record,
        // so folding leaves it alone.
        assert_eq!(
            render_short(b"CAF\xE9    TXT", NT_LOWER_BASE),
            b"caf\xE9.TXT".to_vec(),
            "the flag names the base alone, and the byte above ASCII has no case"
        );
    }

    #[test]
    fn a_name_with_no_extension_keeps_no_dot() {
        assert_eq!(render_short(b"EMPTY      ", 0), b"EMPTY");
        assert_eq!(render_short(b"A       B  ", 0), b"A.B");
        // The substituted leading byte is put back: a name that genuinely begins 0xE5 is
        // stored as 0x05 so it is not read as a deleted slot.
        assert_eq!(render_short(b"\x05BC        ", 0), b"\xE5BC".to_vec());
    }

    #[test]
    fn the_volume_label_comes_from_the_root_entry() {
        for (what, image) in each_type() {
            let mut r = reader(&image);
            assert_eq!(
                r.volume_label().expect("label"),
                Some(b"FERROSYS".to_vec()),
                "{what}"
            );
            // And it is not among the names the tree yields: it is not a file.
            let root = r.root();
            let names: Vec<Vec<u8>> = r
                .read_dir(&root)
                .expect("read")
                .into_iter()
                .map(|e| e.name)
                .collect();
            assert!(!names.contains(&b"FERROSYS".to_vec()), "{what}");
        }
    }

    #[test]
    fn an_access_date_of_zero_is_a_date_not_kept() {
        // Zero is how the format records a date not kept, as it is for the creation field: it
        // is no date in the format's own range. So the node has no access time, and what the
        // shared surface reports for one is the modification time, marked invented.
        use crate::tree::FsTree;
        let (_, image) = each_type().into_iter().next().expect("a type");
        let mut bytes = image.as_bytes().to_vec();
        // `BOOTX64 EFI`, its own short name, and its access date the word at 18 of the entry.
        let at = bytes
            .windows(11)
            .position(|w| w == b"BOOTX64 EFI")
            .expect("the entry");
        bytes[at + 18..at + 20].fill(0);
        let mut r = Reader::open(Cursor::new(&bytes[..])).expect("open");
        let node = r.lookup(b"/EFI/BOOT/BOOTX64.EFI").expect("the file");
        let times = node.times.expect("an entry's times");
        assert_eq!(times.access, None);
        let stat = r.stat(&node, &Synthesis::new()).expect("its attributes");
        assert!(
            stat.synthesized
                .contains(&crate::fidelity::Property::AccessTime)
        );
        assert_eq!(stat.meta.atime, stat.meta.mtime);
    }

    #[test]
    fn a_label_entry_of_spaces_is_no_label_and_one_led_by_a_space_is_reported() {
        for (what, image) in each_type() {
            let bytes = image.as_bytes().to_vec();
            // The root's label entry: the name the writer gave it, then the label attribute.
            let at = bytes
                .windows(12)
                .position(|w| w == b"FERROSYS   \x08")
                .expect("the label entry");
            let mut led = bytes.clone();
            led[at..at + 11].copy_from_slice(b" FERROSYS  ");
            let mut r = Reader::open_with(
                Cursor::new(&led[..]),
                &OpenOptions::new().policy(ReadPolicy::Lenient),
            )
            .expect("open");
            assert!(
                r.scan()
                    .anomalies()
                    .iter()
                    .any(|a| a.detail.contains("beginning with a space")),
                "{what}"
            );
            let mut blank = bytes;
            blank[at..at + 11].fill(b' ');
            let mut r = Reader::open_with(
                Cursor::new(&blank[..]),
                &OpenOptions::new().policy(ReadPolicy::Lenient),
            )
            .expect("open");
            assert_eq!(r.volume_label().expect("a label read"), None, "{what}");
        }
    }

    #[test]
    fn a_strict_scan_of_a_volume_this_crate_wrote_is_clean() {
        // The line the severities are drawn against: a strict read accepts everything the
        // writer emits, so a scan of one finds nothing at all.
        for (what, image) in each_type() {
            let mut r = reader(&image);
            let report = r.scan();
            assert!(report.is_clean(), "{what}: {:#?}", report.anomalies());
            assert!(!report.has_fatal(ReadPolicy::Strict), "{what}");
            r.verify_tables()
                .unwrap_or_else(|e| panic!("{what}: the tables disagree: {e}"));
        }
    }

    #[test]
    fn a_strict_read_accepts_every_volume_the_writer_produces_at_every_option() {
        // The same line, over the half of the writer's input the geometry sweeps do not
        // reach. `PlanRequest` decides where the bytes go; `FormatOptions` decides what a
        // dozen of them say — and a field the writer accepts but the reader's parameter-block
        // gate refuses breaks the round trip exactly as surely as a misplaced cluster would.
        // So every field is varied here, one at a time, across all three types.
        /// One departure from the default options, and what to call it in a failure.
        type Variant = (&'static str, Box<dyn Fn(FormatOptions) -> FormatOptions>);

        let long_code = vec![0x90u8; BootCode::MAX_BYTES_FAT32];
        let mut variants: Vec<Variant> = vec![
            ("default", Box::new(|o: FormatOptions| o)),
            (
                "unlabelled",
                Box::new(|mut o: FormatOptions| {
                    o.label = None;
                    o
                }),
            ),
            (
                "oem name",
                Box::new(|mut o: FormatOptions| {
                    o.oem_name = *b"MSWIN4.1";
                    o
                }),
            ),
            (
                "hidden sectors",
                Box::new(|mut o: FormatOptions| {
                    o.hidden_sectors = 2048;
                    o
                }),
            ),
            (
                "disk geometry",
                Box::new(|o: FormatOptions| {
                    let most = std::num::NonZeroU16::MAX;
                    o.disk_geometry(DiskGeometry::Exactly {
                        sectors_per_track: most,
                        heads: most,
                    })
                }),
            ),
            (
                "volume id",
                Box::new(|mut o: FormatOptions| {
                    o.volume_id = 0;
                    o
                }),
            ),
            (
                "earliest time",
                Box::new(|mut o: FormatOptions| {
                    o.time = Timestamp::from_secs(DosTimestamp::SECS_MIN);
                    o
                }),
            ),
            (
                "latest time",
                Box::new(|mut o: FormatOptions| {
                    o.time = Timestamp::from_secs(DosTimestamp::SECS_MAX);
                    o
                }),
            ),
            (
                "boot code",
                Box::new(move |o: FormatOptions| {
                    o.boot_code(BootCode::new(&long_code).expect("boot code"))
                }),
            ),
        ];
        // The sweep's own completeness check, and the reason this test can claim "every
        // field" rather than "the fields someone listed". `FormatOptions` is destructured
        // field by field, so a field added to it stops this test compiling until someone
        // decides what varies it. Without that, a matrix is exhaustive only over the axes
        // it was written with — which is how a sweep over the sector size, the table count,
        // the type, the cluster size and the label certified a round trip it did not test,
        // because `media` was the one field nobody had thought to move.
        //
        // Bindings are discarded: it is the exhaustiveness the compiler checks, not the
        // values.
        let FormatOptions {
            // Each varied above, by the variant named for it.
            label: _,
            oem_name: _,
            hidden_sectors: _,
            disk_geometry: _,
            volume_id: _,
            time: _,
            media: _,
            boot_code: _,
            // Varied by the type loop below, and exhaustively by the geometry sweeps in
            // tests/fat_oracle.rs, which compare against the pinned oracle rather than
            // against this crate's own reader.
            plan: _,
            // Neither reaches a byte this reader gates on. `accepted_loss` decides whether
            // a format *fails* over a property FAT cannot hold, so a volume that exists at
            // all was written with a setting that permitted it; `synthesis` names what an
            // owner and a mode read back as, which the format does not record and no parse
            // consults. A tree carrying something lossy is the subject of the fidelity
            // tests, not of the parameter block's round trip.
            accepted_loss: _,
            synthesis: _,
        } = options();

        // Every media descriptor the format defines: the writer refuses the rest, and the
        // reader accepts exactly these.
        for media in (0xF8u8..=0xFF).chain([MEDIA_REMOVABLE]) {
            variants.push((
                "media",
                Box::new(move |mut o: FormatOptions| {
                    o.media = media;
                    o
                }),
            ));
        }

        for (what, mib) in [
            (FatType::Fat12, 2u64),
            (FatType::Fat16, 64),
            (FatType::Fat32, 512),
        ] {
            for (name, vary) in &variants {
                let base = options()
                    .label(VolumeLabel::new("FERROSYS").expect("label"))
                    .plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(what)));
                let image = format(tree(), mib << 20, vary(base))
                    .unwrap_or_else(|e| panic!("{what} / {name}: format: {e}"));
                let mut r = Reader::open(Cursor::new(image.as_bytes()))
                    .unwrap_or_else(|e| panic!("{what} / {name}: a strict open: {e}"));
                assert_eq!(r.layout(), image.layout(), "{what} / {name}");
                let report = r.scan();
                assert!(
                    report.is_clean(),
                    "{what} / {name}: {:#?}",
                    report.anomalies()
                );
            }
        }
    }

    #[test]
    fn an_undersized_fat32_is_remarked_on_and_not_refused() {
        // The opt-in small FAT32 volume: below the format's own cluster minimum, written on
        // request, and read as FAT32 by every mainstream driver. This crate emits it, so a
        // strict read must accept it.
        let opts = options().plan(
            PlanRequest::new(0)
                .cluster_size(ClusterSize::Sectors(1))
                .reserved_sectors(ReservedSectors::Count(32))
                .fat_type(FatTypeRequest::UndersizedFat32),
        );
        let image = format(TreeBuilder::new(), 8 << 20, opts).expect("format");
        let mut r = Reader::open(Cursor::new(image.as_bytes())).expect("a strict open");
        assert_eq!(r.fat_type(), FatType::Fat32);
        assert!(r.layout().clusters < crate::fat::MIN_CLUSTERS_FAT32);
        let report = r.scan();
        assert!(report.is_clean(), "{:#?}", report.anomalies());
    }

    #[test]
    fn the_reader_opens_exactly_what_detection_claims() {
        // Both go through one derivation, so there is no image detection names and the
        // reader refuses, and none it calls unrecognized that the reader opens.
        for (_, image) in each_type() {
            let bytes = image.as_bytes();
            assert!(matches!(
                crate::detect(Cursor::new(bytes)),
                Ok(crate::Filesystem::Fat(_))
            ));
            assert!(Reader::open(Cursor::new(bytes)).is_ok());
        }
        // And a master boot record, which ends in the same two bytes a FAT volume does.
        let mut mbr = vec![0u8; 1 << 20];
        mbr[510] = 0x55;
        mbr[511] = 0xAA;
        mbr[0..3].copy_from_slice(&[0xEB, 0x3C, 0x90]);
        assert!(crate::detect(Cursor::new(&mbr)).is_err());
        assert!(matches!(
            Reader::open(Cursor::new(&mbr)),
            Err(ReadError::BadBootSector { .. })
        ));
    }

    #[test]
    fn a_volume_inside_a_larger_image_reads_at_its_own_offset() {
        const BASE: u64 = 1 << 20;
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut disk = vec![0u8; BASE as usize];
        disk.extend_from_slice(image.as_bytes());
        // Nothing at the start of the disk, and the volume where it was put.
        assert!(Reader::open(Cursor::new(&disk)).is_err());
        let mut r = Reader::open_with(Cursor::new(&disk), &OpenOptions::new().base(BASE))
            .expect("open at the partition's start");
        assert_eq!(r.layout(), image.layout());
        assert_eq!(r.walk().expect("walk").len(), 7);
    }

    #[test]
    fn a_volume_longer_than_its_region_is_refused_and_one_inside_it_opens() {
        // The same volume, with a neighbour's bytes after it on the disk.
        const BASE: u64 = 1 << 20;
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let len = image.as_bytes().len() as u64;
        let mut disk = vec![0u8; BASE as usize];
        disk.extend_from_slice(image.as_bytes());
        disk.extend(vec![0xee; 1 << 20]);
        // A partition a byte short of the volume: the parameter block records more sectors
        // than the source holds, under either policy. Without the partition's end, the
        // neighbour's bytes would make up the difference.
        for policy in [ReadPolicy::Strict, ReadPolicy::Lenient] {
            assert!(matches!(
                Reader::open_with(
                    Cursor::new(&disk),
                    &OpenOptions::new().base(BASE).len(len - 1).policy(policy)
                ),
                Err(ReadError::BadBootSector {
                    field: "BPB_TotSec32",
                    ..
                })
            ));
        }
        // The partition that holds it whole, and the disk with no partition named.
        for options in [
            OpenOptions::new().base(BASE).len(len),
            OpenOptions::new().base(BASE),
        ] {
            let mut r = Reader::open_with(Cursor::new(&disk), &options).expect("open");
            assert_eq!(r.walk().expect("walk").len(), 7);
            assert!(r.scan().is_clean());
        }
    }

    #[test]
    fn a_lookup_finds_a_name_however_its_letters_are_cased() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut r = reader(&image);
        // Two rules meet in these spellings, and they are separate. The separators and `.`
        // elements carry no meaning to *any* path in this crate, so a volume drops them
        // because it splits through the one shared rule rather than because this reader
        // reimplemented it — asserted here against `canonical_key`, so a splitter that
        // drifted would make a model key an entry at a path this reader could no longer
        // reach. The case of the letters is FAT's own business, which is why the shared key
        // does not fold it and this assertion uppercases before comparing.
        for path in [
            &b"/EFI/BOOT/BOOTX64.EFI"[..],
            b"/efi/boot/bootx64.efi",
            b"/EFI/boot/BootX64.efi",
            b"//EFI//BOOT//BOOTX64.EFI",
            b"/./EFI/BOOT/BOOTX64.EFI",
            b"/EFI/BOOT/BOOTX64.EFI/",
            b"EFI/BOOT/BOOTX64.EFI",
        ] {
            let node = r
                .lookup(path)
                .unwrap_or_else(|e| panic!("{}: {e}", String::from_utf8_lossy(path)));
            assert_eq!(node.size, 4);
            assert_eq!(
                crate::path::canonical_key(path).to_ascii_uppercase(),
                b"EFI/BOOT/BOOTX64.EFI",
                "{}: one path to a model as well as to a lookup",
                String::from_utf8_lossy(path)
            );
        }
        assert!(matches!(
            r.lookup(b"/EFI/BOOT/NOPE"),
            Err(ReadError::NotFound { .. })
        ));
        assert!(matches!(
            r.lookup(b"/readme.txt/deeper"),
            Err(ReadError::NotADirectory { .. })
        ));
    }

    #[test]
    fn a_parent_component_ascends_though_no_entry_of_that_name_is_ever_handed_back() {
        // This family is where the two questions the one spelling asks came apart. A FAT
        // subdirectory genuinely stores `.` and `..` entries, and none of them reaches a
        // caller: the format's own are identified by their short-name field and filtered
        // there, and a long name spelling either is refused as a name. So there is no entry
        // an ascent could be a lookup of, and it has to be the descent walked back.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut r = reader(&image);
        let boot = r.lookup(b"/EFI/BOOT").expect("lookup");
        let listed = r.read_dir(&boot).expect("read the subdirectory");
        // Asked through the shared rule rather than by spelling the two names again, so a
        // clause added to what no path component may carry reaches this assertion too.
        assert!(
            !listed
                .iter()
                .any(|e| is_hostile_component(&e.name) || is_hostile_component(&e.short_name)),
            "a name no path component may carry reached a caller: {:?}",
            listed.iter().map(|e| &e.name).collect::<Vec<_>>()
        );
        // The volume stores them all the same, which is what makes the filtering the claim
        // rather than an accident of this fixture.
        assert_eq!(listed.len(), 1);

        // And the component resolves, through a directory whose listing has nothing of that
        // name in it.
        let want = r.lookup(b"/EFI/BOOT/BOOTX64.EFI").expect("lookup");
        assert_eq!(
            r.lookup(b"/EFI/BOOT/../BOOT/BOOTX64.EFI")
                .map(|node| node.storage),
            Ok(want.storage)
        );
        assert_eq!(
            r.lookup(b"/EFI/..").map(|n| n.storage),
            Ok(r.root().storage)
        );
    }

    #[test]
    fn a_directory_holds_no_bytes_and_yields_none() {
        // A directory's storage is its entries, and handing those back as file contents
        // would be a directory entry read as data.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut r = reader(&image);
        let dir = r.lookup(b"/EFI").expect("lookup");
        assert!(dir.is_dir());
        assert_eq!(r.read_data(&dir).expect("read"), Vec::<u8>::new());
        let mut buf = [0u8; 32];
        assert_eq!(r.read_into(&dir, 0, &mut buf).expect("read"), 0);
    }

    #[test]
    fn the_read_limit_refuses_rather_than_shortening() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut r = Reader::open_with(
            Cursor::new(image.as_bytes()),
            &OpenOptions::new().limits(Limits::new().max_file_bytes(1024)),
        )
        .expect("open");
        let node = r.lookup(b"/a-long-file-name.text").expect("lookup");
        assert!(matches!(
            r.read_data(&node),
            Err(ReadError::FileTooLarge {
                size: 5000,
                limit: 1024
            })
        ));
        // A stream into a caller's own writer answers to it too, and it has to: nothing
        // accumulates there, so the memory it costs says nothing about the bytes it
        // produces — and an extraction's `--cat` is exactly that stream.
        assert!(matches!(
            r.read_data_to(&node, std::io::sink()),
            Err(ReadError::FileTooLarge {
                size: 5000,
                limit: 1024
            })
        ));
        // A read into a caller's own buffer is bounded by the buffer and says how much of
        // it was filled, so a partial read stays representable.
        let mut buf = [0u8; 64];
        assert_eq!(r.read_into(&node, 0, &mut buf).expect("read"), 64);
    }

    #[test]
    fn a_time_the_encoding_does_not_define_is_named_where_the_entry_is_read() {
        // `DosTimestamp::decode` reports the instant the arithmetic reaches and says a scan
        // is what judges it. This is that scan, and it is the write time that is judged
        // unconditionally: the format requires it, where the creation and access times are
        // optional and a wholly zero field is how it records that they were not kept.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let entry = entry_of(&image, b"EMPTY      ");

        // Day 31 of February, which is a date the calendar does not have and the arithmetic
        // reads as the third of March.
        let mut bytes = image.as_bytes().to_vec();
        let odd = ((2035u16 - 1980) << 9) | (2 << 5) | 31;
        bytes[entry + 24..entry + 26].copy_from_slice(&odd.to_le_bytes());
        let err = Reader::open(Cursor::new(bytes.as_slice()))
            .expect("open")
            .walk()
            .expect_err("a strict read refuses it");
        assert!(
            matches!(
                err,
                ReadError::MalformedTimestamp {
                    field: "modification time",
                    ..
                }
            ),
            "{err}"
        );

        // The creation time zeroed whole, which is the format recording that nothing kept
        // it — so it is passed over rather than reported as the month-zero date it spells.
        let mut bytes = image.as_bytes().to_vec();
        bytes[entry + 13] = 0;
        bytes[entry + 14..entry + 18].copy_from_slice(&0u32.to_le_bytes());
        Reader::open(Cursor::new(bytes.as_slice()))
            .expect("open")
            .walk()
            .expect("a field the format calls optional and absent stops no read");

        // Nothing short of the whole field is that record: a zero date beside a time that is
        // not zero is a field that was written, and written wrongly.
        let mut bytes = image.as_bytes().to_vec();
        bytes[entry + 16..entry + 18].copy_from_slice(&0u16.to_le_bytes());
        let err = Reader::open(Cursor::new(bytes.as_slice()))
            .expect("open")
            .walk()
            .expect_err("a strict read refuses it");
        assert!(
            matches!(
                err,
                ReadError::MalformedTimestamp {
                    field: "creation time",
                    ..
                }
            ),
            "{err}"
        );
    }

    #[test]
    fn a_creation_field_left_zero_reads_as_no_birth_time() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let entry = entry_of(&image, b"EMPTY      ");
        let birth = |bytes: &[u8]| {
            let mut r = Reader::open(Cursor::new(bytes)).expect("open");
            let node = r.lookup(b"/empty").expect("the file");
            FsTree::stat(&mut r, &node, &Synthesis::default())
                .expect("stat")
                .meta
                .btime
        };
        // A field the writer filled is the birth time.
        assert!(birth(image.as_bytes()).is_some());
        // Zeroed whole, it is the format's record that nothing kept one.
        let mut bytes = image.as_bytes().to_vec();
        bytes[entry + 13] = 0;
        bytes[entry + 14..entry + 18].copy_from_slice(&0u32.to_le_bytes());
        assert_eq!(birth(&bytes), None);
        // The root has no entry, and so no birth time.
        let mut r = Reader::open(Cursor::new(image.as_bytes())).expect("open");
        let root = r.root();
        let stat = FsTree::stat(&mut r, &root, &Synthesis::default()).expect("stat");
        assert_eq!(stat.meta.btime, None);
    }

    /// Where the directory entry whose short name is `name` begins, as a byte offset into
    /// `image`.
    ///
    /// Found by scanning the root region for the eleven-byte field rather than computed, so a
    /// case that patches an entry stays correct when the order a directory is written in
    /// changes.
    #[test]
    fn a_directory_two_entries_lead_to_is_refused_strictly_and_passed_over_leniently() {
        // /EFI/BOOT's entry repointed at /EFI's own first cluster: a directory that is its own
        // child. A FAT directory has one name, so a strict read refuses the volume; a lenient
        // one lists the name and does not descend into the cluster a second time.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let efi = match reader(&image).lookup(b"/EFI").expect("lookup").storage {
            Storage::Chain(start) => start,
            _ => panic!("the fixture's directory owns no chain"),
        };
        let entry = entry_of(&image, b"BOOT       ");
        let mut bytes = image.as_bytes().to_vec();
        bytes[entry + 26..entry + 28].copy_from_slice(&((efi & 0xffff) as u16).to_le_bytes());
        bytes[entry + 20..entry + 22].copy_from_slice(&((efi >> 16) as u16).to_le_bytes());

        let err = Reader::open(Cursor::new(bytes.as_slice()))
            .expect("open")
            .walk()
            .expect_err("a strict read refuses it");
        assert!(
            matches!(err, ReadError::RepeatedDirectory { cluster } if cluster == efi),
            "{err:?}"
        );

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let paths: Vec<Vec<u8>> = r
            .walk()
            .expect("a lenient read passes it over")
            .into_iter()
            .map(|e| e.path)
            .collect();
        assert!(paths.contains(&b"/EFI/BOOT".to_vec()));
        assert!(
            !paths.iter().any(|p| p.starts_with(b"/EFI/BOOT/")),
            "the repeat is not descended into: {paths:?}"
        );
    }

    /// The first cluster `path` names on `image`.
    fn cluster_of(image: &Image, path: &[u8]) -> u32 {
        match reader(image).lookup(path).expect("lookup").storage {
            Storage::Chain(start) => start,
            _ => panic!("{} owns no chain", String::from_utf8_lossy(path)),
        }
    }

    /// Write `cluster` into the 32-byte entry at `off`, both halves.
    fn point_at(bytes: &mut [u8], off: usize, cluster: u32) {
        bytes[off + 20..off + 22].copy_from_slice(&((cluster >> 16) as u16).to_le_bytes());
        bytes[off + 26..off + 28].copy_from_slice(&((cluster & 0xffff) as u16).to_le_bytes());
    }

    /// What a strict walk and a scan make of `bytes`.
    fn walked_and_scanned(bytes: &[u8]) -> (Result<Vec<WalkEntry>, ReadError>, ScanReport) {
        let strict = Reader::open(Cursor::new(bytes))
            .expect("a strict open")
            .walk();
        let report = Reader::open_with(
            Cursor::new(bytes),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open")
        .scan();
        (strict, report)
    }

    #[test]
    fn a_dot_entry_naming_another_cluster_is_found_and_refused_strictly() {
        // `/EFI/BOOT`'s `.` names its own first cluster and its `..` names `/EFI`'s: each is
        // pointed one cluster on, on every type. Documented, and what the pinned `fsck.fat`
        // repairs.
        for (fat_type, image) in each_type() {
            let efi = cluster_of(&image, b"/EFI");
            let boot = cluster_of(&image, b"/EFI/BOOT");
            let layout = *image.layout();
            let at_boot = at(
                &layout,
                layout.cluster_start_sector(boot).expect("a cluster"),
            );
            for (slot, name, expected) in [(0usize, ".", boot), (1, "..", efi)] {
                let mut bytes = image.as_bytes().to_vec();
                point_at(&mut bytes, at_boot + slot * DIR_ENTRY_SIZE, expected + 1);
                let (strict, report) = walked_and_scanned(&bytes);
                let wrong = ReadError::DotEntryTarget {
                    path: b"/EFI/BOOT".to_vec(),
                    name,
                    found: expected + 1,
                    expected,
                };
                assert_eq!(strict.expect_err("a strict walk refuses it"), wrong);
                assert!(
                    report
                        .anomalies()
                        .iter()
                        .any(|a| a.detail == wrong.to_string()
                            && a.severity == Severity::Integrity),
                    "{fat_type:?} {name}: {:?}",
                    report.anomalies()
                );
            }
        }
    }

    #[test]
    fn the_high_half_of_a_dot_entrys_cluster_counts_on_fat32_alone() {
        // On FAT32 the two halves are one number, and a `..` whose high half is wrong names a
        // cluster 65536 away. On FAT12 and FAT16 the high half is not part of the number, and
        // a driver of that era left what it liked there, so the same bytes are no finding.
        for (fat_type, image) in each_type() {
            let boot = cluster_of(&image, b"/EFI/BOOT");
            let layout = *image.layout();
            let off = at(
                &layout,
                layout.cluster_start_sector(boot).expect("a cluster"),
            ) + DIR_ENTRY_SIZE
                + 20;
            let mut bytes = image.as_bytes().to_vec();
            bytes[off..off + 2].copy_from_slice(&1u16.to_le_bytes());
            let (strict, report) = walked_and_scanned(&bytes);
            if fat_type == FatType::Fat32 {
                assert!(
                    matches!(
                        strict,
                        Err(ReadError::DotEntryTarget { name: "..", found, .. }) if found >> 16 == 1
                    ),
                    "{strict:?}"
                );
            } else {
                assert!(strict.is_ok(), "{fat_type:?}: {strict:?}");
                assert!(report.is_clean(), "{fat_type:?}: {:?}", report.anomalies());
            }
        }
    }

    #[test]
    fn a_dot_entry_missing_or_out_of_place_is_found_and_never_an_entry() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let efi = cluster_of(&image, b"/EFI");
        let boot = cluster_of(&image, b"/EFI/BOOT");
        let at_efi = at(
            &layout,
            layout.cluster_start_sector(efi).expect("a cluster"),
        );
        let at_boot = at(
            &layout,
            layout.cluster_start_sector(boot).expect("a cluster"),
        );
        let at_root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        let sound: Vec<Vec<u8>> = reader(&image)
            .walk()
            .expect("walk")
            .into_iter()
            .map(|e| e.path)
            .collect();
        // The first free slot of a directory, which ends it: a slot written there, with the
        // one after it still free, is the directory's last entry.
        let free = |bytes: &[u8], dir: usize| {
            (0..)
                .map(|n| dir + n * DIR_ENTRY_SIZE)
                .find(|&off| bytes[off] == 0)
                .expect("a free slot")
        };

        // What is wrong, how the bytes are damaged to say so, and the finding's last words.
        type Case<'a> = (&'a str, Box<dyn Fn(&mut Vec<u8>) + 'a>, &'a str);
        let cases: [Case<'_>; 5] = [
            (
                "a `..` in slot 3 of /EFI",
                Box::new(|b: &mut Vec<u8>| {
                    let to = free(b, at_efi);
                    let dotdot = b[at_efi + DIR_ENTRY_SIZE..at_efi + 2 * DIR_ENTRY_SIZE].to_vec();
                    b[to..to + DIR_ENTRY_SIZE].copy_from_slice(&dotdot);
                }),
                "/EFI: entry 3 is a `..` entry, where the format puts none",
            ),
            (
                "a `..` in the root",
                Box::new(|b: &mut Vec<u8>| {
                    let to = free(b, at_root);
                    let dotdot = b[at_efi + DIR_ENTRY_SIZE..at_efi + 2 * DIR_ENTRY_SIZE].to_vec();
                    b[to..to + DIR_ENTRY_SIZE].copy_from_slice(&dotdot);
                }),
                "a `..` entry, where the format puts none",
            ),
            (
                "a `..` without the directory attribute",
                Box::new(|b: &mut Vec<u8>| b[at_boot + DIR_ENTRY_SIZE + 11] = 0x20),
                "/EFI/BOOT: the `..` entry does not carry the directory attribute",
            ),
            (
                "a `.` deleted",
                Box::new(|b: &mut Vec<u8>| b[at_boot] = 0xE5),
                "/EFI/BOOT: entry 0 is not the `.` entry the format puts there",
            ),
            (
                "a `..` named otherwise",
                Box::new(|b: &mut Vec<u8>| b[at_boot + DIR_ENTRY_SIZE + 1] = b'X'),
                "/EFI/BOOT: entry 1 is not the `..` entry the format puts there",
            ),
        ];
        for (what, damage, detail) in cases {
            let mut bytes = image.as_bytes().to_vec();
            damage(&mut bytes);
            let (strict, report) = walked_and_scanned(&bytes);
            assert!(
                matches!(strict, Err(ReadError::BadDotEntry { .. })),
                "{what}: {strict:?}"
            );
            let found: Vec<&Anomaly> = report
                .anomalies()
                .iter()
                .filter(|a| a.detail.ends_with(detail))
                .collect();
            assert_eq!(found.len(), 1, "{what}: {:?}", report.anomalies());
            assert_eq!(found[0].severity, Severity::Conformance, "{what}");
            // Whatever is wrong with it, a dot entry is never an entry of the directory.
            let mut lenient = Reader::open_with(
                Cursor::new(bytes.as_slice()),
                &OpenOptions::new().policy(ReadPolicy::Lenient),
            )
            .expect("open");
            let paths: Vec<Vec<u8>> = lenient
                .walk()
                .expect("a lenient walk")
                .into_iter()
                .map(|e| e.path)
                // A `..` renamed is an ordinary entry by the format's rules, and is listed.
                .filter(|p| !p.ends_with(b"/.X"))
                .collect();
            assert_eq!(paths, sound, "{what}");
        }
    }

    /// What a strict walk, a lenient walk, and a scan make of `bytes`: whether the strict walk
    /// was refused, the lenient walk's paths, and the findings.
    fn read_three_ways(bytes: &[u8]) -> (bool, Vec<Vec<u8>>, ScanReport) {
        let refused = Reader::open(Cursor::new(bytes))
            .expect("a strict open")
            .walk()
            .is_err();
        let mut lenient = Reader::open_with(
            Cursor::new(bytes),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        let paths = lenient
            .walk()
            .expect("a lenient walk")
            .into_iter()
            .map(|e| e.path)
            .collect();
        (refused, paths, lenient.scan())
    }

    #[test]
    fn a_character_the_format_reserves_in_a_name_is_named_and_the_name_handed_back() {
        // Documented: a short name's field reserves `+` and a leading space, and a long name
        // reserves `:`. Each is a conformance finding and the name is still read as stored.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let bootx64 = entry_of(&image, b"BOOTX64 EFI");
        let readme = entry_of(&image, b"README  TXT");
        // The fifth unit of the run in front of `readme.txt`, which is where its `m` is.
        let unit = readme - DIR_ENTRY_SIZE + 9;
        assert_eq!(
            &image.as_bytes()[unit..unit + 2],
            b"m\0",
            "the fixture's long name"
        );
        // What is wrong, the byte written and where, the path a lenient walk lists, and the
        // name and code the finding carries.
        type Case<'a> = (&'a str, usize, u8, &'a [u8], &'a str, u32);
        let cases: [Case<'_>; 3] = [
            (
                "a short `+`",
                bootx64 + 1,
                b'+',
                b"/EFI/BOOT/B+OTX64.EFI",
                "short",
                0x2b,
            ),
            ("a long `:`", unit, b':', b"/read:e.txt", "long", 0x3a),
            (
                "a leading space",
                bootx64,
                b' ',
                b"/EFI/BOOT/ OOTX64.EFI",
                "short",
                0x20,
            ),
        ];
        for (what, at, byte, listed, field, code) in cases {
            let mut bytes = image.as_bytes().to_vec();
            bytes[at] = byte;
            let (refused, paths, report) = read_three_ways(&bytes);
            assert!(refused, "{what}: a strict walk refuses it");
            assert!(paths.contains(&listed.to_vec()), "{what}: {paths:?}");
            let named: Vec<&Anomaly> = report
                .anomalies()
                .iter()
                .filter(|a| a.detail.contains(&format!("the {field} name at entry")))
                .collect();
            assert_eq!(named.len(), 1, "{what}: {:?}", report.anomalies());
            assert_eq!(named[0].severity, Severity::Conformance, "{what}");
            assert!(
                named[0].detail.contains(&format!("{code:#06x}")),
                "{what}: {}",
                named[0].detail
            );
        }
        // 0x05 in the first byte stands for 0xE5, which is not reserved: what it draws is the
        // remark every byte above ASCII read under no code page draws.
        let mut bytes = image.as_bytes().to_vec();
        bytes[bootx64] = 0x05;
        let (_, _, report) = read_three_ways(&bytes);
        assert!(
            !report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("the format reserves")),
            "{:?}",
            report.anomalies()
        );
        // And a volume this crate wrote carries none of these.
        let (_, _, report) = read_three_ways(image.as_bytes());
        assert!(report.is_clean(), "{:?}", report.anomalies());
    }

    #[test]
    fn two_names_one_directory_cannot_tell_apart_are_integrity_damage() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let at_root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        let boot = cluster_of(&image, b"/EFI/BOOT");
        let at_boot = at(
            &layout,
            layout.cluster_start_sector(boot).expect("a cluster"),
        );
        let bootx64 = entry_of(&image, b"BOOTX64 EFI");
        let readme = entry_of(&image, b"README  TXT");
        let free = |bytes: &[u8], dir: usize| {
            (0..)
                .map(|n| dir + n * DIR_ENTRY_SIZE)
                .find(|&off| bytes[off] == 0)
                .expect("a free slot")
        };
        let copy = |bytes: &mut Vec<u8>, from: std::ops::Range<usize>, to: usize| {
            let slots = bytes[from].to_vec();
            bytes[to..to + slots.len()].copy_from_slice(&slots);
        };

        // The same short name twice.
        let mut twice = image.as_bytes().to_vec();
        let to = free(&twice, at_boot);
        copy(&mut twice, bootx64..bootx64 + DIR_ENTRY_SIZE, to);
        // `readme.txt`'s short entry alone, without its run: a short name `README.TXT` beside
        // the long name `readme.txt`, which a lookup folds to the same name.
        let mut alias = image.as_bytes().to_vec();
        let to = free(&alias, at_root);
        copy(&mut alias, readme..readme + DIR_ENTRY_SIZE, to);
        // The run and its entry again, under another short name and a long one that differs
        // only in case: two long names one lookup cannot choose between.
        let mut cased = image.as_bytes().to_vec();
        let to = free(&cased, at_root);
        let run = readme - DIR_ENTRY_SIZE;
        copy(&mut cased, run..readme + DIR_ENTRY_SIZE, to);
        let short = to + DIR_ENTRY_SIZE;
        cased[short..short + 11].copy_from_slice(b"README~2TXT");
        let checksum = DirEntry::read_from(&cased[short..short + DIR_ENTRY_SIZE])
            .expect("an entry")
            .lfn_checksum();
        cased[to + 13] = checksum;
        cased[to + 1] = b'R';

        for (what, bytes, path, entries) in [
            (
                "one short name twice",
                twice,
                &b"/EFI/BOOT/BOOTX64.EFI"[..],
                2,
            ),
            ("a long name and a short one", alias, b"/readme.txt", 2),
            ("two long names", cased, b"/readme.txt", 2),
        ] {
            let (refused, paths, report) = read_three_ways(&bytes);
            assert!(refused, "{what}: a strict walk refuses it");
            let leaf = *crate::path::canonical_parts(path).last().expect("a name");
            assert_eq!(
                paths
                    .iter()
                    .filter(|p| {
                        crate::path::canonical_parts(p)
                            .last()
                            .is_some_and(|n| n.eq_ignore_ascii_case(leaf))
                    })
                    .count(),
                entries,
                "{what}: a lenient walk lists both: {paths:?}"
            );
            let found: Vec<&Anomaly> = report
                .anomalies()
                .iter()
                .filter(|a| a.detail.contains("once case is folded"))
                .collect();
            assert_eq!(found.len(), 1, "{what}: {:?}", report.anomalies());
            assert_eq!(found[0].severity, Severity::Integrity, "{what}");
        }
    }

    /// The findings of a lenient scan of `bytes` that name `detail`.
    fn findings_naming(bytes: &[u8], detail: &str) -> Vec<Anomaly> {
        Reader::open_with(
            Cursor::new(bytes),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open")
        .scan()
        .anomalies()
        .iter()
        .filter(|a| a.detail.contains(detail))
        .cloned()
        .collect()
    }

    #[test]
    fn a_directory_entry_recording_a_length_is_remarked_on() {
        // Documented: a directory's entry records no length, its chain being its length. No
        // driver reads the field, so it is a remark; the pinned checker clears it.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let efi = entry_of(&image, b"EFI        ");
        let mut bytes = image.as_bytes().to_vec();
        bytes[efi + 28..efi + 32].copy_from_slice(&512u32.to_le_bytes());
        let found = findings_naming(&bytes, "where a directory records none");
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].severity, Severity::Cosmetic);
        // A remark, so a strict walk reads the directory whole.
        assert_eq!(
            Reader::open(Cursor::new(bytes.as_slice()))
                .expect("open")
                .walk()
                .expect("a strict walk")
                .len(),
            7
        );
    }

    #[test]
    fn a_label_is_one_entry_in_the_root_and_nothing_else_is_one() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let at_root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        let efi = cluster_of(&image, b"/EFI");
        let at_efi = at(
            &layout,
            layout.cluster_start_sector(efi).expect("a cluster"),
        );
        let label = entry_of(&image, b"FERROSYS   ");
        let free = |bytes: &[u8], dir: usize| {
            (0..)
                .map(|n| dir + n * DIR_ENTRY_SIZE)
                .find(|&off| bytes[off] == 0)
                .expect("a free slot")
        };
        let label_of = |bytes: &[u8]| {
            Reader::open_with(
                Cursor::new(bytes),
                &OpenOptions::new().policy(ReadPolicy::Lenient),
            )
            .expect("open")
            .volume_label()
            .expect("the label")
        };

        // A second label in the root: the first is the volume's.
        let mut second = image.as_bytes().to_vec();
        let to = free(&second, at_root);
        let mut entry = second[label..label + DIR_ENTRY_SIZE].to_vec();
        entry[..11].copy_from_slice(b"SECOND     ");
        second[to..to + DIR_ENTRY_SIZE].copy_from_slice(&entry);
        let found = findings_naming(&second, "is a second volume label");
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].severity, Severity::Conformance);
        assert_eq!(label_of(&second), Some(b"FERROSYS".to_vec()));

        // A label in a subdirectory, where the format defines none.
        let mut misplaced = image.as_bytes().to_vec();
        let to = free(&misplaced, at_efi);
        let entry = misplaced[label..label + DIR_ENTRY_SIZE].to_vec();
        misplaced[to..to + DIR_ENTRY_SIZE].copy_from_slice(&entry);
        let found = findings_naming(&misplaced, "a volume label entry sits at entry");
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].severity, Severity::Conformance);

        // The label's entry carrying the directory attribute too: neither a label nor a
        // directory, so the label is the boot sector's copy, as it is for a volume whose root
        // holds none.
        let mut both = image.as_bytes().to_vec();
        both[label + 11] |= 0x10;
        let found = findings_naming(&both, "neither a label nor a directory");
        assert_eq!(found.len(), 1, "{found:?}");
        assert_eq!(found[0].severity, Severity::Conformance);
        let walked: Vec<Vec<u8>> = Reader::open_with(
            Cursor::new(both.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open")
        .walk()
        .expect("walk")
        .into_iter()
        .map(|e| e.path)
        .collect();
        assert!(
            !walked.iter().any(|p| p.starts_with(b"/FERROSYS")),
            "{walked:?}"
        );
    }

    #[test]
    fn the_free_count_the_information_sector_keeps_is_held_to_the_table() {
        // A hint that is out of date is remarked on; one past the volume's clusters is one no
        // driver kept. exFAT's fullness is graded the same two ways.
        let image = image(512, FatTypeRequest::Exactly(FatType::Fat32));
        let layout = *image.layout();
        let info = at(
            &layout,
            u32::from(layout.fat32.expect("FAT32").fs_info_sector),
        ) + 488;
        let stated = u32::from_le_bytes(image.as_bytes()[info..info + 4].try_into().expect("four"));
        for (value, detail, severity) in [
            (stated - 1, "clusters free", Some(Severity::Cosmetic)),
            (
                layout.clusters + 1,
                "more clusters than",
                Some(Severity::Conformance),
            ),
            (u32::MAX, "free-cluster hint", None),
        ] {
            let mut bytes = image.as_bytes().to_vec();
            bytes[info..info + 4].copy_from_slice(&value.to_le_bytes());
            let found = findings_naming(&bytes, detail);
            match severity {
                Some(severity) => {
                    assert_eq!(found.len(), 1, "{value}: {found:?}");
                    assert_eq!(found[0].severity, severity, "{value}");
                }
                // The sentinel says the count is not known, which is not a stale count.
                None => assert!(found.is_empty(), "{value}: {found:?}"),
            }
        }
        // The count this crate writes is the table's.
        assert!(findings_naming(image.as_bytes(), "free-cluster hint").is_empty());
    }

    #[test]
    fn a_long_name_ends_at_its_terminator_or_its_padding_and_ill_padding_is_remarked_on() {
        // `readme.txt` is ten units in a thirteen-unit entry: a zero, then two of padding.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let run = entry_of(&image, b"README  TXT") - DIR_ENTRY_SIZE;
        // Units 10, 11 and 12 of the entry, by their byte offsets in it.
        let (nul, pad, last) = (run + 24, run + 28, run + 30);
        assert_eq!(&image.as_bytes()[nul..nul + 2], &[0, 0]);
        assert_eq!(&image.as_bytes()[last..last + 2], &[0xff, 0xff]);
        for (what, at, unit) in [
            ("padding where the zero is", nul, 0xFFFFu16),
            ("a character after the zero", pad, u16::from(b'A')),
        ] {
            let mut bytes = image.as_bytes().to_vec();
            bytes[at..at + 2].copy_from_slice(&unit.to_le_bytes());
            let found = findings_naming(&bytes, "not padded the way the format pads one");
            assert_eq!(found.len(), 1, "{what}: {found:?}");
            assert_eq!(found[0].severity, Severity::Cosmetic, "{what}");
            let names: Vec<Vec<u8>> = Reader::open(Cursor::new(bytes.as_slice()))
                .expect("open")
                .walk()
                .expect("a strict walk")
                .into_iter()
                .map(|e| e.path)
                .collect();
            assert!(
                names.contains(&b"/readme.txt".to_vec()),
                "{what}: {names:?}"
            );
        }
    }

    #[test]
    fn a_long_name_past_the_format_s_cap_is_named_and_read() {
        // Twenty entries carry 260 units and the format caps a name at 255. A run of twenty
        // full entries in front of one short entry, in a directory with room for it.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let boot = cluster_of(&image, b"/EFI/BOOT");
        let dir = at(
            &layout,
            layout.cluster_start_sector(boot).expect("a cluster"),
        );
        let mut bytes = image.as_bytes().to_vec();
        let first_free = (0..)
            .map(|n| dir + n * DIR_ENTRY_SIZE)
            .find(|&off| bytes[off] == 0)
            .expect("a free slot");
        let mut short = bytes[entry_of(&image, b"BOOTX64 EFI")..][..DIR_ENTRY_SIZE].to_vec();
        short[..11].copy_from_slice(b"LONGNAMETXT");
        let checksum = DirEntry::read_from(&short)
            .expect("an entry")
            .lfn_checksum();
        for (n, ordinal) in (1..=LFN_MAX_ENTRIES as u8).rev().enumerate() {
            let lfn = LfnEntry {
                order: ordinal | if n == 0 { LFN_LAST_ENTRY } else { 0 },
                name: [u16::from(b'a'); LFN_CHARS_PER_ENTRY],
                checksum,
            };
            let at = first_free + n * DIR_ENTRY_SIZE;
            lfn.write_to(&mut bytes[at..at + DIR_ENTRY_SIZE])
                .expect("write");
        }
        let at = first_free + LFN_MAX_ENTRIES * DIR_ENTRY_SIZE;
        bytes[at..at + DIR_ENTRY_SIZE].copy_from_slice(&short);

        let found = findings_naming(&bytes, "units");
        assert!(found.iter().any(|a| a.detail.contains("260")), "{found:?}");
        let mut lenient = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let long = format!("/EFI/BOOT/{}", "a".repeat(260));
        assert!(lenient.lookup(long.as_bytes()).is_ok(), "the name is read");
        assert!(matches!(
            Reader::open(Cursor::new(bytes.as_slice()))
                .expect("open")
                .walk(),
            Err(ReadError::LongNameTooLong { units: 260, .. })
        ));
    }

    #[test]
    fn a_bad_cluster_mark_inside_a_chain_ends_the_read_and_is_named() {
        // The mark says a cluster is unusable, so no chain may run through it.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let start = cluster_of(&image, b"/a-long-file-name.text");
        let mut bytes = image.as_bytes().to_vec();
        let bad = table::bad_cluster(FatType::Fat16);
        for copy in 0..layout.fats {
            let entry =
                at(&layout, layout.fat_start_sector(copy).expect("a copy")) + start as usize * 2;
            bytes[entry..entry + 2].copy_from_slice(&(bad as u16).to_le_bytes());
        }
        let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
        let node = r.lookup(b"/a-long-file-name.text").expect("the name");
        assert_eq!(
            r.read_data(&node)
                .expect_err("the chain runs through a bad cluster"),
            ReadError::BadChainEntry {
                cluster: start,
                entry: bad,
            }
        );
        assert_eq!(findings_naming(&bytes, &format!("{bad:#x}")).len(), 1);
    }

    #[test]
    fn every_read_error_answers_with_an_anomaly_that_says_where_it_was() {
        // Exhaustive by construction is not available for an enum this crate may grow, so the
        // list is kept by hand: each variant answers, in this family's frame.
        let all = [
            ReadError::Io {
                kind: std::io::ErrorKind::UnexpectedEof,
                message: "x".to_string(),
            },
            ReadError::Io {
                kind: std::io::ErrorKind::Other,
                message: "x".to_string(),
            },
            ReadError::Parse(ParseError::TooShort {
                structure: "x",
                need: 1,
                got: 0,
            }),
            ReadError::BadBootSector {
                field: "x",
                value: 1,
            },
            ReadError::AmbiguousClusterCount { clusters: 4086 },
            ReadError::LargeCluster { bytes: 65536 },
            ReadError::ClusterOutOfRange { cluster: 9 },
            ReadError::BadChainEntry {
                cluster: 9,
                entry: 0,
            },
            ReadError::ChainTooLong {
                start: 2,
                clusters: 4,
            },
            ReadError::OrphanedLongName { index: 0 },
            ReadError::LongNameChecksum {
                index: 0,
                found: 1,
                expected: 2,
            },
            ReadError::LongNameTooLong {
                index: 0,
                units: 260,
            },
            ReadError::LongNamePadding { index: 0 },
            ReadError::IllFormedLongName { index: 0 },
            ReadError::UninterpretedShortName {
                index: 0,
                byte: 0x80,
            },
            ReadError::HostileName { index: 0 },
            ReadError::ReservedCharacter {
                index: 0,
                field: "short",
                code: 0x2b,
            },
            ReadError::IndistinguishableNames { index: 3, first: 2 },
            ReadError::RepeatedDirectory { cluster: 3 },
            ReadError::SizeWithoutAllocation { index: 0, size: 1 },
            ReadError::DirectoryWithSize { index: 0, size: 1 },
            ReadError::BadDotEntry {
                detail: "x".to_string(),
            },
            ReadError::DotEntryTarget {
                path: b"/x".to_vec(),
                name: "..",
                found: 3,
                expected: 0,
            },
            ReadError::EntriesAfterEnd { index: 0 },
            ReadError::DirectoryTooLong { index: 0, limit: 0 },
            ReadError::MisplacedVolumeLabel { index: 0 },
            ReadError::LabelWithDirectoryAttribute { index: 0 },
            ReadError::SecondVolumeLabel { index: 0 },
            ReadError::LabelBeginsWithSpace { index: 0 },
            ReadError::LostClusters { count: 1, first: 2 },
            ReadError::FreeCountOutOfRange {
                stated: 9,
                clusters: 8,
            },
            ReadError::FreeCountStale {
                stated: 7,
                counted: 8,
            },
            ReadError::NotFound {
                path: b"/x".to_vec(),
            },
            ReadError::NotADirectory {
                path: b"/x".to_vec(),
            },
            ReadError::FileTooLarge { size: 2, limit: 1 },
            ReadError::PathTooLong { limit: MAX_PATH },
            ReadError::WalkTooLarge { limit: 1 },
            ReadError::BackupBootSectorDiffers { sector: 6 },
            ReadError::BadInfoSector { sector: 1 },
            ReadError::BadReservedEntry {
                index: 1,
                found: 0,
                expected: 1,
            },
            ReadError::ChainTooShort {
                start: 2,
                size: 4096,
                read: 512,
            },
            ReadError::MalformedTimestamp {
                index: 0,
                field: "modification time",
            },
            ReadError::SectorOutOfRange {
                sector: 9,
                total_sectors: 8,
            },
            ReadError::TableMismatch {
                copy: 1,
                cluster: 2,
                first: 3,
                other: 4,
            },
            ReadError::TablePaddingMismatch { copy: 1 },
            ReadError::VolumeDirty,
            ReadError::MediaFailure,
        ];
        for err in all {
            let anomaly = err.anomaly();
            assert!(!anomaly.detail.is_empty(), "{err:?}");
            let finding = crate::Deviation::to_finding(&anomaly, 512);
            assert_eq!(finding.family, Family::Fat);
            assert_eq!(finding.category, anomaly.category.as_str());
        }
    }

    fn entry_of(image: &Image, name: &[u8; 11]) -> usize {
        let bytes = image.as_bytes();
        bytes
            .as_chunks::<DIR_ENTRY_SIZE>()
            .0
            .iter()
            .position(|slot| &slot[..11] == name)
            .map(|n| n * DIR_ENTRY_SIZE)
            .unwrap_or_else(|| panic!("no entry is named {}", String::from_utf8_lossy(name)))
    }

    /// A directory of ten short-named files, `N0.TXT` to `N9.TXT`, which the writer lays down
    /// in that order.
    fn ten_names() -> Image {
        let m = |mode| Metadata::new(mode, TIME);
        let mut tree = TreeBuilder::new().directory(b"/D".to_vec(), m(0o755));
        for i in 0..10 {
            tree = tree.file(format!("/D/N{i}.TXT").into_bytes(), b"x".to_vec(), m(0o644));
        }
        format(
            tree,
            64 << 20,
            options().plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat16))),
        )
        .expect("format")
    }

    #[test]
    fn a_lookup_reads_a_directory_only_as_far_as_its_name() {
        // A lookup streams the directory as ext's does: it gathers nothing, so the cap on
        // what a walk gathers is not its business, and a directory longer than the cap still
        // resolves every name in it.
        let image = ten_names();
        let mut r = Reader::open_with(
            Cursor::new(image.as_bytes()),
            &OpenOptions::new().limits(Limits::new().max_walk_entries(3)),
        )
        .expect("open");
        let dir = r.lookup(b"/D").expect("the directory");
        assert!(matches!(
            r.read_dir(&dir),
            Err(ReadError::WalkTooLarge { limit: 3 })
        ));
        for name in [&b"/D/N0.TXT"[..], b"/D/N9.TXT", b"/d/n9.txt"] {
            assert!(
                r.lookup(name).is_ok(),
                "{} is past the cap and found",
                String::from_utf8_lossy(name)
            );
        }
    }

    #[test]
    fn an_entry_past_the_match_does_not_refuse_a_strict_lookup() {
        // The lookup stops at its name, so an entry it never reads cannot refuse it. One it
        // does read on the way still does, as a listing of the directory does.
        let image = ten_names();
        let mut bytes = image.as_bytes().to_vec();
        let at = entry_of(&image, b"N5      TXT");
        bytes[at] = b'/';
        let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("a strict open");
        let dir = r.lookup(b"/D").expect("the directory");
        assert!(matches!(
            r.read_dir(&dir),
            Err(ReadError::HostileName { .. })
        ));
        assert!(r.lookup(b"/D/N2.TXT").is_ok(), "before the bad entry");
        assert!(
            matches!(r.lookup(b"/D/N8.TXT"), Err(ReadError::HostileName { .. })),
            "past it, the lookup reads it on the way"
        );
        // A case-folded name reads on to the end in case an exact one follows, so it meets
        // the bad entry too.
        assert!(r.lookup(b"/D/n2.txt").is_err());
    }

    #[test]
    fn a_walk_bound_is_reported_rather_than_silently_shortening_the_tree() {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut r = Reader::open_with(
            Cursor::new(image.as_bytes()),
            &OpenOptions::new().limits(Limits::new().max_walk_entries(3)),
        )
        .expect("open");
        assert!(matches!(
            r.walk(),
            Err(ReadError::WalkTooLarge { limit: 3 })
        ));
    }

    /// A volume whose root directory is chained through every cluster it has, with every
    /// 32-byte slot of the data region a well-formed short-name entry.
    ///
    /// This is the shape a caller's cap has to survive: nothing here is larger than the
    /// image, so no structural bound refuses it, and a read that materialized the directory
    /// before consulting a limit would allocate the volume's size whatever the caller asked
    /// for.
    /// An empty undersized FAT32 of one-sector clusters whose root chains through `clusters`
    /// clusters from its first, every slot of them the entry `slot` makes of its index.
    fn root_chained_through(
        clusters: Option<u32>,
        slot: impl Fn(usize) -> [u8; DIR_ENTRY_SIZE],
    ) -> (Vec<u8>, FatLayout) {
        let opts = options().plan(
            PlanRequest::new(0)
                .cluster_size(ClusterSize::Sectors(1))
                .reserved_sectors(ReservedSectors::Count(32))
                .fat_type(FatTypeRequest::UndersizedFat32),
        );
        let image = format(TreeBuilder::new(), 8 << 20, opts).expect("format");
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let root = layout.fat32.expect("a FAT32 volume").root_cluster;
        assert_eq!(root, 2, "the root is the first cluster");
        // Every cluster the chain takes points at the next, so the chain that begins at the
        // root runs through all of them.
        let last = root + clusters.unwrap_or(layout.clusters) - 1;
        assert!(last < layout.clusters + 2, "the volume holds the chain");
        let table_bytes = layout.fat_sectors as usize * layout.bytes_per_sector as usize;
        for copy in 0..layout.fats {
            let start = at(&layout, layout.fat_start_sector(copy).expect("a table"));
            let table = &mut bytes[start..start + table_bytes];
            for cluster in root..=last {
                let value = if cluster == last {
                    table::end_of_chain(layout.fat_type)
                } else {
                    cluster + 1
                };
                assert!(table::write_entry(layout.fat_type, table, cluster, value));
            }
        }
        let data = at(&layout, layout.first_data_sector);
        let end = data + (last - root + 1) as usize * layout.bytes_per_cluster() as usize;
        for (n, chunk) in bytes[data..end]
            .as_chunks_mut::<DIR_ENTRY_SIZE>()
            .0
            .iter_mut()
            .enumerate()
        {
            *chunk = slot(n);
        }
        (bytes, layout)
    }

    /// A file entry named `name` (the eleven bytes of a short name), stamped `TIME`.
    fn file_slot(name: &[u8]) -> [u8; DIR_ENTRY_SIZE] {
        let mut slot = [0u8; DIR_ENTRY_SIZE];
        slot[..11].copy_from_slice(name);
        slot[11] = 0x20; // archive, which is what an ordinary file carries
        let stamp = DosTimestamp::encode(TIME).expect("in range");
        slot[22..24].copy_from_slice(&stamp.time.to_le_bytes());
        slot[24..26].copy_from_slice(&stamp.date.to_le_bytes());
        slot
    }

    fn root_chained_through_the_whole_volume() -> (Vec<u8>, FatLayout) {
        // Every slot in the data region is an entry, so nothing stops the parse early. Each
        // carries a real write time, because the bound under test is the entry cap and an
        // entry whose date the calendar does not have is a deviation that would stop the
        // parse first — on a fixture where the times were never the point.
        root_chained_through(None, |_| file_slot(b"FILLER  TXT"))
    }

    #[test]
    fn a_directory_larger_than_the_cap_is_refused_before_it_is_gathered() {
        // A directory is read a region at a time and its entries are counted against the
        // caller's bound as they are produced, so a crafted one costs a cluster rather than
        // the volume. Reading it whole first and consulting the bound afterwards would make
        // `Limits` unable to do the one thing it exists for.
        let (bytes, layout) = root_chained_through_the_whole_volume();
        assert!(
            layout.clusters > 4096,
            "the fixture is too small to be evidence: {} clusters",
            layout.clusters
        );

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().limits(Limits::new().max_walk_entries(16)),
        )
        .expect("open");
        let root = r.root();
        assert!(matches!(
            r.read_dir(&root),
            Err(ReadError::WalkTooLarge { limit: 16 })
        ));
        assert!(matches!(
            r.walk(),
            Err(ReadError::WalkTooLarge { limit: 16 })
        ));

        // A chain collected whole answers to the same bound, for the same reason.
        assert!(matches!(
            r.chain(2),
            Err(ReadError::WalkTooLarge { limit: 16 })
        ));
    }

    /// A volume whose root chains through `clusters` one-sector clusters, every slot of them
    /// a file with a short name of its own, the `n`th slot naming `F{n:07}.TXT`.
    fn root_of_clusters(clusters: u32) -> Vec<u8> {
        root_chained_through(Some(clusters), |n| {
            file_slot(format!("F{n:07}TXT").as_bytes())
        })
        .0
    }

    #[test]
    fn a_directory_past_the_format_s_size_is_read_whole_and_named() {
        let per_cluster = 512 / DIR_ENTRY_SIZE as u64;
        let at_bound = u32::try_from(MAX_DIRECTORY_BYTES / 512).expect("a cluster count");
        let lenient = OpenOptions::new().policy(ReadPolicy::Lenient);
        let finding = ReadError::DirectoryTooLong {
            index: u32::try_from(MAX_DIRECTORY_ENTRIES).expect("an index"),
            limit: MAX_DIRECTORY_BYTES,
        }
        .to_string();

        // At the bound, a strict read takes the whole directory and a scan has nothing to say
        // about its size.
        let bytes = root_of_clusters(at_bound);
        let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
        let root = r.root();
        let entries = r.read_dir(&root).expect("a directory of the format's size");
        assert_eq!(entries.len() as u64, MAX_DIRECTORY_ENTRIES);
        let mut r = Reader::open_with(Cursor::new(bytes.as_slice()), &lenient).expect("open");
        assert!(
            !r.scan().anomalies().iter().any(|a| a.detail == finding),
            "a directory of exactly the bound"
        );

        // One cluster past it.
        let bytes = root_of_clusters(at_bound + 1);
        let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
        let root = r.root();
        let err = r.read_dir(&root).expect_err("a strict read refuses it");
        assert_eq!(err.to_string(), finding);
        assert_eq!(err.anomaly().severity, Severity::Conformance);
        // A lookup reads only as far as its name, so a name before the bound resolves.
        assert!(r.lookup(b"/F0000009.TXT").is_ok());

        // A lenient read takes every entry, the ones past the bound included, as a driver
        // reads them; a scan names the directory once.
        let mut r = Reader::open_with(Cursor::new(bytes.as_slice()), &lenient).expect("open");
        let root = r.root();
        let entries = r.read_dir(&root).expect("a lenient read");
        assert_eq!(entries.len() as u64, MAX_DIRECTORY_ENTRIES + per_cluster);
        let last = format!("F{:07}.TXT", MAX_DIRECTORY_ENTRIES + per_cluster - 1);
        assert_eq!(
            entries.last().map(|e| e.name.as_slice()),
            Some(last.as_bytes())
        );
        let report = r.scan();
        let named: Vec<_> = report
            .anomalies()
            .iter()
            .filter(|a| a.detail == finding)
            .collect();
        assert_eq!(named.len(), 1, "{:#?}", report.anomalies());
        assert_eq!(named[0].severity, Severity::Conformance);
    }

    #[test]
    fn a_scan_that_hit_the_cap_inside_one_directory_reports_nothing_lost() {
        // The same rule the running name count follows: a traversal that stopped reached
        // fewer clusters than the volume owns, so what it did not reach is not evidence.
        let (bytes, _) = root_chained_through_the_whole_volume();
        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new()
                .policy(ReadPolicy::Lenient)
                .limits(Limits::new().max_walk_entries(16)),
        )
        .expect("open");
        let report = r.scan();
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("more than 16 names")),
            "{:#?}",
            report.anomalies()
        );
        assert!(
            !report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("reached by no chain")),
            "{:#?}",
            report.anomalies()
        );
    }

    /// Format a volume, hand its bytes to `damage`, and report what a lenient scan finds.
    fn damaged(what: FatTypeRequest, damage: impl FnOnce(&mut [u8], &FatLayout)) -> ScanReport {
        let image = image(64, what);
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        damage(&mut bytes, &layout);
        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        r.scan()
    }

    /// Switch a FAT32 volume's mirroring off and name `live` as the one maintained copy, in
    /// the boot sector and in its backup.
    fn set_ext_flags(bytes: &mut [u8], layout: &FatLayout, flags: u16) {
        let mut sectors = vec![0u32];
        if let Some(backup) = layout.fat32.and_then(|f| f.backup_boot_sector) {
            sectors.push(u32::from(backup));
        }
        for sector in sectors {
            let off = at(layout, sector) + 40;
            bytes[off..off + 2].copy_from_slice(&flags.to_le_bytes());
        }
    }

    #[test]
    fn a_chain_is_followed_through_the_table_the_volume_says_is_live() {
        // `BPB_ExtFlags` bit 7 says only one copy of the table is maintained and bits 0-3 say
        // which. A reader that takes the bit and drops the number follows the copy the volume
        // abandoned, and returns the tree and the file bytes *that* table describes — while a
        // conformant driver returns different ones.
        //
        // What makes it silent rather than merely wrong is that this is exactly the shape
        // where the mirror check is suppressed: with mirroring off the copies are not obliged
        // to agree, so the disagreement that would otherwise be an integrity finding is not
        // reported. A strict open followed by an extraction succeeds and is wrong.
        let pristine = image(512, FatTypeRequest::Exactly(FatType::Fat32));
        let layout = *pristine.layout();
        let want = {
            let mut r = reader(&pristine);
            let node = r.lookup(b"/a-long-file-name.text").expect("lookup");
            r.read_data(&node).expect("read")
        };
        assert_eq!(want.len(), 5000, "the fixture file spans several clusters");
        let names = reader(&pristine).walk().expect("walk").len();
        let mut bytes = pristine.into_bytes();

        // Copy 0 is emptied outright, so nothing can be resolved through it: every chain
        // ends at a free cluster on the first step. Copy 1 is left as the writer laid it
        // down, and the volume is told that copy 1 is the live one.
        let start = at(&layout, layout.fat_start_sector(0).expect("a first table"));
        let len = at(&layout, layout.fat_sectors);
        bytes[start..start + len].fill(0);
        set_ext_flags(&mut bytes, &layout, 0x0081);

        let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("a strict open");
        let node = r.lookup(b"/a-long-file-name.text").expect("lookup");
        assert_eq!(
            r.read_data(&node).expect("read through the live table"),
            want,
            "the bytes are the live table's, not the abandoned copy's"
        );
        assert_eq!(
            r.walk().expect("walk").len(),
            names,
            "the tree is the live table's too"
        );

        // And the same volume with mirroring on is a volume whose table 0 is destroyed: the
        // control that shows the damage was real rather than unreached.
        let mut mirrored = bytes;
        set_ext_flags(&mut mirrored, &layout, 0x0000);
        // The lookup itself can succeed — the name sits in the root's first cluster, and a
        // lookup stops at it without following the chain past — but the file's bytes run
        // through the destroyed table.
        let mut r = Reader::open(Cursor::new(mirrored.as_slice())).expect("open");
        let read = r
            .lookup(b"/a-long-file-name.text")
            .and_then(|node| r.read_data(&node));
        assert!(
            matches!(read, Err(ReadError::BadChainEntry { entry: 0, .. })),
            "with mirroring on the read goes through the emptied copy 0, whose entries are \
             free and so continue no chain: {read:?}"
        );
        assert!(r.walk().is_err(), "nor does the tree walk through it");
    }

    #[test]
    fn the_label_is_the_live_one_and_survives_the_leading_byte_substitution() {
        // `volume_label` walks `for_each_slot`, which hands back *every* slot because that is
        // what the scan needs. All the free, deleted, and end-of-directory handling lives in
        // `parse_dir`, which this bypasses — so a deleted label entry, or one sitting past
        // the end marker, was returned where `fatlabel` and every driver read the live one.
        // And because `parse_dir` was bypassed, neither the entries-after-end nor the
        // misplaced-label finding fired: a strict read reported nothing.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let live = reader(&image)
            .volume_label()
            .expect("read")
            .expect("a label");
        assert_eq!(live, b"FERROSYS");
        let mut bytes = image.into_bytes();

        // The volume records the label twice: in the root directory, which is what a rename
        // updates and what every driver reads, and in the boot sector, which nothing keeps in
        // step. Made to differ, so which one answered is visible.
        let boot = bytes
            .windows(11)
            .position(|w| w == b"FERROSYS   ")
            .expect("the boot sector's copy");
        let root = bytes
            .windows(11)
            .rposition(|w| w == b"FERROSYS   ")
            .expect("the root entry");
        assert_ne!(boot, root, "the two copies are two places");
        bytes[boot..boot + 11].copy_from_slice(b"STALECOPY  ");

        // The root's entry, struck out. The live label is then the boot sector's, which is
        // what the reader falls back to — and *not* the deleted entry, which is a name the
        // volume no longer answers to.
        bytes[root] = NAME_DELETED;
        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        assert_eq!(
            r.volume_label().expect("read").as_deref(),
            Some(&b"STALECOPY"[..]),
            "a deleted entry is not the volume's label"
        );

        // And a label whose first byte really is `0xE5` is stored as `0x05`, the deleted
        // marker's substitution — so reading it back without undoing that gives a label one
        // byte different from the one that was set.
        let mut restored = bytes.clone();
        restored[root] = NAME_LEADING_E5;
        restored[root + 1..root + 11].copy_from_slice(b"ABEL      ");
        let mut r = Reader::open_with(
            Cursor::new(restored.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        assert_eq!(
            r.volume_label().expect("read").expect("a label")[0],
            0xE5,
            "the substituted leading byte is put back"
        );
    }

    #[test]
    fn an_unknown_filesystem_version_is_reported_rather_than_scanned_clean() {
        // `BPB_FSVer` is the field a driver reads to decide whether it understands the
        // volume at all. Zero is the only version ever defined, and neither Windows nor
        // Linux mounts anything else — so a volume carrying another value is one nothing
        // will touch, and a read that opened and scanned it clean would be describing an
        // image that in practice does not exist.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, layout| {
            // `BPB_FSVer` sits at offset 42 of the boot sector, and of its backup.
            let mut sectors = vec![0u32];
            if let Some(backup) = layout.fat32.and_then(|f| f.backup_boot_sector) {
                sectors.push(u32::from(backup));
            }
            for sector in sectors {
                let off = at(layout, sector) + 42;
                bytes[off..off + 2].copy_from_slice(&1u16.to_le_bytes());
            }
        });
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("BPB_FSVer is 0x0001")),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn a_live_table_the_volume_does_not_have_is_reported_rather_than_followed_blindly() {
        // `BPB_ExtFlags` naming copy 5 of two is incoherent. Nothing can be resolved through
        // a table that is not there, so reads fall back to copy 0 — and because that is a
        // different table from the one the volume names, the scan says so at the weight of a
        // wrong read rather than as a cosmetic field.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, layout| {
            set_ext_flags(bytes, layout, 0x0085);
        });
        assert!(
            report.anomalies().iter().any(|a| {
                a.severity == Severity::Integrity && a.detail.contains("names table 5")
            }),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn a_name_carrying_terminal_control_bytes_is_escaped_where_it_enters_a_finding() {
        // A name may carry ESC, CR, or a right-to-left override and still be read: the format
        // reserves the first two, which a scan reports and a lenient read hands back, and the
        // third is legal in a long name. A finding that interpolated such a name raw would
        // hand those bytes to whatever printed it —
        // and a name of `\x1b[2J\x1b[1;1Hno findings\x1b[0m` puts a forged clean report on
        // the screen of whoever inspects the image, from a command that exited zero.
        //
        // So the name is escaped where it enters the text. Nothing downstream can do it:
        // by then the detail is one string and no part of it is marked as the image's.
        let hostile = b"\x1b[2Jred\r";
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat16), |bytes, _| {
            let at = bytes
                .windows(11)
                .position(|w| w == b"BOOTX64 EFI")
                .expect("the fixture's short name is on disk");
            // The name, and a length its chain cannot hold — which is what makes a finding
            // that names the entry fire at all.
            bytes[at..at + 8].copy_from_slice(hostile);
            bytes[at + 28..at + 32].copy_from_slice(&999_999u32.to_le_bytes());
        });

        let named: Vec<&str> = report
            .anomalies()
            .iter()
            .map(|a| a.detail.as_str())
            .filter(|d| d.contains("\\x1b"))
            .collect();
        assert!(
            !named.is_empty(),
            "a finding names the entry: {:#?}",
            report.anomalies()
        );
        for detail in report.anomalies().iter().map(|a| &a.detail) {
            assert!(
                !detail.chars().any(char::is_control),
                "a finding carries a raw control byte: {detail:?}"
            );
        }
        // And the projections a caller renders carry the same guarantee, because the detail
        // they interpolate already does.
        let findings = report.to_report();
        for rendered in [findings.to_table(), findings.to_json()] {
            assert!(
                !rendered.chars().any(|c| c.is_control() && c != '\n'),
                "a rendered report carries a raw control byte: {rendered:?}"
            );
        }
    }

    #[test]
    fn a_table_that_disagrees_with_its_mirror_is_an_integrity_finding() {
        // FAT carries no checksums, and the mirror is what stands in for one.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat16), |bytes, layout| {
            let second = layout.fat_start_sector(1).expect("two tables");
            bytes[at(layout, second) + 8] ^= 0xFF;
        });
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.severity == Severity::Integrity
                    && a.category == Category::AllocationTable),
            "{:#?}",
            report.anomalies()
        );
        assert!(report.has_fatal(ReadPolicy::Strict));
    }

    /// A FAT12 volume whose highest cluster number is even, with a reader over it and the
    /// byte offset of the second table's first byte.
    ///
    /// Both packing-boundary cases live at that parity: an even highest cluster is the one
    /// whose entry ends in a shared nibble rather than on a byte boundary.
    fn fat12_with_an_even_highest_cluster() -> (Vec<u8>, FatLayout) {
        for mib in 1u64..8 {
            let image = image(mib, FatTypeRequest::Exactly(FatType::Fat12));
            let layout = *image.layout();
            if (layout.clusters + 1).is_multiple_of(2) && layout.fats >= 2 {
                return (image.into_bytes(), layout);
            }
        }
        panic!("no FAT12 fixture in range has an even highest cluster");
    }

    #[test]
    fn a_divergence_in_the_last_fat12_entry_is_a_mismatch_and_not_padding() {
        // On FAT12 the highest cluster's entry can end in the *low* nibble of a byte, so a
        // difference at that byte is a difference in a live allocation entry. Classifying it
        // as padding would make it cosmetic, and a strict read would accept a volume whose
        // two tables disagree about where a chain goes.
        let (mut bytes, layout) = fat12_with_an_even_highest_cluster();
        let highest = layout.clusters + 1;
        let shared = table::entry_offset(FatType::Fat12, highest) + 1;
        let second = at(&layout, layout.fat_start_sector(1).expect("two tables"));

        // The low nibble of that byte is the highest entry's top four bits; the high nibble
        // belongs to no cluster the volume has.
        bytes[second + shared as usize] ^= 0x01;

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        match r.verify_tables() {
            Err(ReadError::TableMismatch { copy, cluster, .. }) => {
                assert_eq!(copy, 1);
                assert_eq!(cluster, highest);
            }
            other => panic!("expected a mismatch at the last entry, got {other:?}"),
        }
        // And it is fatal under a strict policy, which is what a padding classification —
        // `Severity::Cosmetic` — would not have been.
        let report = r.scan();
        assert!(
            report.has_fatal(ReadPolicy::Strict),
            "a table that disagrees about a live entry is not a remark: {:#?}",
            report.anomalies()
        );

        // The control: the byte one past the entry's last belongs to nothing, and a
        // difference there is padding and stays cosmetic.
        let (mut bytes, layout) = fat12_with_an_even_highest_cluster();
        let past = table::entry_offset(FatType::Fat12, layout.clusters + 1) + 2;
        bytes[second + past as usize] ^= 0xFF;
        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        assert!(matches!(
            r.verify_tables(),
            Err(ReadError::TablePaddingMismatch { copy: 1 })
        ));
    }

    #[test]
    fn a_divergence_in_a_shared_fat12_byte_names_the_entry_that_differs() {
        // The middle byte of a FAT12 pair belongs to two entries. A difference in its high
        // nibble is the *odd* entry's, and naming the even one would print a mismatch whose
        // two values are equal and send a repair at the wrong cluster.
        let (mut bytes, layout) = fat12_with_an_even_highest_cluster();
        let second = at(&layout, layout.fat_start_sector(1).expect("two tables"));
        // The pair (100, 101) shares the byte at offset 150 + 1.
        let odd = 101u32;
        let shared = table::entry_offset(FatType::Fat12, odd) as usize;
        assert!(odd < layout.clusters + 1, "the fixture is too small");

        let before = {
            let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
            (
                r.table_entry_in(0, odd - 1).expect("even entry"),
                r.table_entry_in(0, odd).expect("odd entry"),
            )
        };
        // The high nibble, which is the odd entry's low four bits.
        bytes[second + shared] ^= 0x10;

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        match r.verify_tables() {
            Err(ReadError::TableMismatch {
                copy,
                cluster,
                first,
                other,
            }) => {
                assert_eq!(copy, 1);
                assert_eq!(
                    cluster, odd,
                    "the shared byte was attributed to its neighbour"
                );
                assert_ne!(first, other, "a mismatch printed two identical values");
                assert_eq!(first, before.1);
            }
            other => panic!("expected a mismatch at the odd entry, got {other:?}"),
        }

        // And the other nibble of the same byte is the even entry's, reported as that one.
        let (mut bytes, _) = fat12_with_an_even_highest_cluster();
        bytes[second + shared] ^= 0x01;
        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        match r.verify_tables() {
            Err(ReadError::TableMismatch {
                cluster,
                first,
                other,
                ..
            }) => {
                assert_eq!(cluster, odd - 1);
                assert_ne!(first, other);
                assert_eq!(first, before.0);
            }
            other => panic!("expected a mismatch at the even entry, got {other:?}"),
        }
    }

    #[test]
    fn a_long_name_whose_checksum_does_not_match_is_an_integrity_finding() {
        // The checksum is what stops a driver without long-name support from orphaning a
        // name onto the wrong file, so a mismatch means the long name describes a file that
        // is not there.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat16), |bytes, layout| {
            let root = at(
                layout,
                layout.root_dir_start_sector().expect("a root region"),
            );
            // Rename the short entry a run belongs to, which is exactly what breaks the tie
            // in practice: a driver without long-name support renames the file and the
            // stale run stops matching. Corrupting one entry *of* the run would make it
            // incomplete instead, which is the neighbouring finding.
            for slot in 1..layout.root_entries as usize {
                let off = root + slot * DIR_ENTRY_SIZE;
                let previous = root + (slot - 1) * DIR_ENTRY_SIZE;
                if bytes[off + 11] != DirAttributes::LFN.bits()
                    && bytes[previous + 11] == DirAttributes::LFN.bits()
                {
                    bytes[off] = b'Z';
                    return;
                }
            }
            panic!("the fixture holds no long-name run");
        });
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("checksums to")),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn a_first_cluster_outside_the_volume_is_a_structural_finding() {
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat16), |bytes, layout| {
            let root = at(
                layout,
                layout.root_dir_start_sector().expect("a root region"),
            );
            for slot in 0..layout.root_entries as usize {
                let off = root + slot * DIR_ENTRY_SIZE;
                let attrs = bytes[off + 11];
                let size = u32::from_le_bytes(bytes[off + 28..off + 32].try_into().unwrap());
                if attrs != DirAttributes::LFN.bits() && size > 0 {
                    bytes[off + 26..off + 28].copy_from_slice(&0xFFFEu16.to_le_bytes());
                    return;
                }
            }
            panic!("the fixture holds no file entry in the root");
        });
        assert!(
            report.worst_severity() >= Some(Severity::Structural),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn clusters_allocated_and_reached_by_nothing_are_reported() {
        // What `fsck.fat` calls lost clusters: space spent holding something no reader can
        // find. It is the one finding that needs the whole allocation rather than any single
        // structure, which is why the scan carries a set over the clusters.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat16), |bytes, layout| {
            // The last cluster number a volume of `clusters` clusters has is `clusters + 1`;
            // this one is inside the volume and no entry points at it.
            let orphan = layout.clusters;
            for copy in 0..layout.fats {
                let start = at(layout, layout.fat_start_sector(copy).expect("a table"));
                let off = start + table::entry_offset(FatType::Fat16, orphan) as usize;
                bytes[off..off + 2].copy_from_slice(&0xFFFFu16.to_le_bytes());
            }
        });
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("reached by no chain")),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn an_entry_recording_a_length_and_no_first_cluster_is_named_where_it_is_read() {
        // FAT has no holes, so a length is a claim about clusters and a first cluster of zero
        // says there are none. Nothing downstream can see the two disagree: the storage such
        // an entry yields is the same `None` a legitimately empty file has, so the scan's
        // size-against-chain comparison has no chain to make it against — a volume `fsck.fat`
        // truncates the file on scanned clean, and the read refused halfway through an
        // extraction.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let entry = entry_of(&image, b"EMPTY      ");
        let mut bytes = image.into_bytes();
        bytes[entry + 28..entry + 32].copy_from_slice(&10u32.to_le_bytes());

        let err = Reader::open(Cursor::new(bytes.as_slice()))
            .expect("open")
            .walk()
            .expect_err("a strict read refuses it");
        assert!(
            matches!(err, ReadError::SizeWithoutAllocation { size: 10, .. }),
            "{err}"
        );

        // And the scan says it, at the severity that stops an `inspect`: this is the one
        // finding the volume carries, so nothing else could be standing in for it.
        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("a lenient open");
        let report = r.scan();
        let found: Vec<_> = report
            .anomalies()
            .iter()
            .filter(|a| a.detail.contains("no first cluster"))
            .collect();
        assert_eq!(found.len(), 1, "{:#?}", report.anomalies());
        assert_eq!(found[0].severity, Severity::Structural);
        assert!(!report.is_clean());

        // And the read objects too: the scan says so first and the read says so again, so a
        // caller reaching this entry either way is told.
        let node = r.lookup(b"/empty").expect("lookup");
        assert!(matches!(
            r.read_data(&node),
            Err(ReadError::ChainTooShort {
                start: 0,
                size: 10,
                read: 0
            })
        ));
    }

    #[test]
    fn a_backup_boot_sector_that_has_drifted_is_reported() {
        // It exists to be used when sector 0 cannot be read, so a copy that no longer
        // matches would restore a geometry the volume does not have.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, layout| {
            let backup = layout
                .fat32
                .and_then(|f| f.backup_boot_sector)
                .expect("a backup");
            bytes[at(layout, u32::from(backup)) + 20] ^= 0xFF;
        });
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.category == Category::BootSector),
            "{:#?}",
            report.anomalies()
        );
    }

    /// Clear `bits` of table entry 1 in every copy of the table, as a driver recording a
    /// state does.
    fn clear_entry_one(bytes: &mut [u8], layout: &FatLayout, bits: u32) {
        let offset = table::entry_offset(layout.fat_type, 1) as usize;
        for copy in 0..layout.fats {
            let start = at(layout, layout.reserved_sectors + copy * layout.fat_sectors) + offset;
            let width = if layout.fat_type == FatType::Fat32 {
                4
            } else {
                2
            };
            let mut word = [0u8; 4];
            word[..width].copy_from_slice(&bytes[start..start + width]);
            let cleared = (u32::from_le_bytes(word) & !bits).to_le_bytes();
            bytes[start..start + width].copy_from_slice(&cleared[..width]);
        }
    }

    #[test]
    fn the_status_bits_of_entry_one_are_a_state_and_not_a_bad_entry() {
        // The FAT specification defines a clean-shutdown bit and a hard-error bit at the top
        // of entry 1 on FAT16 and FAT32, each set for the good state. A driver clears one to
        // record the other, which is the volume working rather than a value no driver writes.
        for fat_type in [FatType::Fat16, FatType::Fat32] {
            let (clean, no_error) = table::status_bits(fat_type);
            for (bits, expected) in [
                (clean, vec![ReadError::VolumeDirty]),
                (no_error, vec![ReadError::MediaFailure]),
                (
                    clean | no_error,
                    vec![ReadError::VolumeDirty, ReadError::MediaFailure],
                ),
            ] {
                let report = damaged(FatTypeRequest::Exactly(fat_type), |bytes, layout| {
                    clear_entry_one(bytes, layout, bits);
                });
                let expected: Vec<Anomaly> = expected.iter().map(ReadError::anomaly).collect();
                assert_eq!(report.anomalies(), expected, "{fat_type:?}, bits {bits:#x}");
                assert!(!report.has_fatal(ReadPolicy::Strict), "{fat_type:?}");
            }
            // Any other bit is a value no driver writes, and is still reported as one.
            let report = damaged(FatTypeRequest::Exactly(fat_type), |bytes, layout| {
                clear_entry_one(bytes, layout, 1);
            });
            assert!(
                matches!(
                    report.anomalies(),
                    [a] if a.category == Category::AllocationTable
                        && a.severity == Severity::Conformance
                ),
                "{fat_type:?}: {:#?}",
                report.anomalies()
            );
        }
        // FAT12 defines no status bits, so its entry 1 is a value and nothing else.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat12), |bytes, layout| {
            clear_entry_one(bytes, layout, 0x800);
        });
        assert!(
            matches!(report.anomalies(), [a] if a.severity == Severity::Conformance),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn a_backup_boot_sector_is_compared_past_the_dirty_mark_and_no_further() {
        // A Linux driver marks a mounted volume in the primary boot sector's reserved byte and
        // leaves the backup alone, so the copies differing in that bit is the volume's state.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, _| {
            bytes[64 + 1] |= VOLUME_DIRTY;
        });
        assert_eq!(
            report.anomalies(),
            [ReadError::VolumeDirty.anomaly()],
            "the state, once, and no stale backup"
        );
        // Another bit of the same byte is not the state, and the copies differing in it is a
        // backup that no longer matches.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, _| {
            bytes[64 + 1] |= 0x02;
        });
        assert!(
            matches!(
                report.anomalies(),
                [a] if a.category == Category::BootSector && a.severity == Severity::Conformance
            ),
            "{:#?}",
            report.anomalies()
        );
    }

    #[test]
    fn the_half_of_the_information_sector_signature_nothing_explains_is_checked() {
        // The trailing signature's top half is the `55 AA` a stray boot signature accounts
        // for, so the parser does not require it. Its bottom half is two zero bytes that
        // nothing accounts for, and a value there is a false clean if the scan is silent
        // about it — which is the one thing a conformance surface must not be.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, layout| {
            let info = at(
                layout,
                u32::from(layout.fat32.expect("a FAT32 layout").fs_info_sector),
            );
            bytes[info + FsInfo::TRAIL_OFFSET] ^= 0x01;
        });
        let found: Vec<_> = report
            .anomalies()
            .iter()
            .filter(|a| a.category == Category::InfoSector)
            .collect();
        assert_eq!(found.len(), 1, "{:#?}", report.anomalies());
        assert_eq!(found[0].severity, Severity::Cosmetic);
        assert!(found[0].detail.contains("trailing signature"));
        // Inert, so it is a remark: a strict read still opens the volume.
        assert!(!report.has_fatal(ReadPolicy::Strict));

        // And the half the parser's reasoning does cover stays unchecked, which is the
        // leniency that reasoning argues for rather than an oversight.
        let report = damaged(FatTypeRequest::Exactly(FatType::Fat32), |bytes, layout| {
            let info = at(
                layout,
                u32::from(layout.fat32.expect("a FAT32 layout").fs_info_sector),
            );
            bytes[info + FsInfo::TRAIL_OFFSET + 3] ^= 0xFF;
        });
        assert!(report.is_clean(), "{:#?}", report.anomalies());
    }

    #[test]
    fn a_short_name_above_ascii_is_a_conformance_deviation_until_a_page_is_named() {
        // The severity tracks whether the reader recognized what it saw, which is the whole
        // of what naming a code page changes: the bytes are the same either way.
        //
        // The deviation is about the name the entry is *found under*. An entry with a long
        // name is found under that, which is UTF-16 and unambiguous, so its short name is a
        // legacy second record and not something the reader has to interpret. This fixture
        // therefore holds one name that is already its own short name, which is the case
        // where the eleven bytes are the whole of what the volume says.
        let opts =
            options().plan(PlanRequest::new(0).fat_type(FatTypeRequest::Exactly(FatType::Fat16)));
        let m = Metadata::new(0o644, TIME);
        let src = TreeBuilder::new().file(b"/README.TXT".to_vec(), b"hi\n".to_vec(), m);
        let built = format(src, 64 << 20, opts).expect("format");
        let layout = *built.layout();
        let mut bytes = built.into_bytes();
        let root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        let mut placed = false;
        for slot in 0..layout.root_entries as usize {
            let off = root + slot * DIR_ENTRY_SIZE;
            if &bytes[off..off + 11] == b"README  TXT" {
                bytes[off + 5] = 0x82;
                placed = true;
                break;
            }
        }
        assert!(placed, "the fixture holds no README entry");

        // Verbatim: a conformance deviation, so a strict read stops at it.
        let mut strict = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
        let root_node = strict.root();
        assert!(matches!(
            strict.read_dir(&root_node),
            Err(ReadError::UninterpretedShortName { byte: 0x82, .. })
        ));

        let mut lenient = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let root_node = lenient.root();
        let names: Vec<Vec<u8>> = lenient
            .read_dir(&root_node)
            .expect("read")
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(names.contains(&b"READM\x82.TXT".to_vec()), "{names:?}");
        let report = lenient.scan();
        assert_eq!(
            report.worst_severity(),
            Some(Severity::Conformance),
            "{:#?}",
            report.anomalies()
        );

        // Naming the page: the byte is interpreted, the read succeeds under a strict policy,
        // and the remark drops to cosmetic.
        let mut named = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().charset(ShortNameCharset::Cp437),
        )
        .expect("open");
        let root_node = named.root();
        let names: Vec<Vec<u8>> = named
            .read_dir(&root_node)
            .expect("a strict read, with the page named")
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(
            names.contains(&"READMé.TXT".as_bytes().to_vec()),
            "{names:?}"
        );
        let report = named.scan();
        assert_eq!(report.worst_severity(), Some(Severity::Cosmetic));
        assert!(!report.has_fatal(ReadPolicy::Strict));
    }

    #[test]
    fn a_long_name_that_is_not_well_formed_utf16_is_read_with_a_replacement() {
        // An unpaired surrogate stands for no character. The name is still handed back, so a
        // tree carrying one stays enumerable, and the deviation is what says so.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        let mut placed = false;
        for slot in 0..layout.root_entries as usize {
            let off = root + slot * DIR_ENTRY_SIZE;
            // The entry holding a name's *first* characters is the one with ordinal 1, which
            // is the last of the run on disk and so the one immediately before its short
            // entry.
            if bytes[off + 11] == DirAttributes::LFN.bits() && bytes[off] & !LFN_LAST_ENTRY == 1 {
                bytes[off + 1..off + 3].copy_from_slice(&0xD800u16.to_le_bytes());
                placed = true;
                break;
            }
        }
        assert!(placed, "the fixture holds no long-name entry");

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let root_node = r.root();
        let names: Vec<Vec<u8>> = r
            .read_dir(&root_node)
            .expect("read")
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(
            names.iter().any(|n| n.starts_with("\u{FFFD}".as_bytes())),
            "{names:?}"
        );
        assert!(
            r.scan()
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("well-formed UTF-16"))
        );
    }

    #[test]
    fn an_orphaned_long_name_run_is_reported_however_the_run_ends() {
        // A long-name run belongs to the ordinary short entry that follows it, and that
        // entry is only one of the ways a run can end. The others leave the run belonging
        // to nothing — an end marker, a deleted entry, a volume label, a fresh sequence
        // start — and each must be a finding: the classic corruption here is a short
        // entry deleted with its long-name slots left behind, and a scan that reported
        // the orphan at one terminal state and not the others would go quiet on exactly
        // that shape.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let bytes = image.into_bytes();
        let root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );

        // The slot of the short entry a single-entry run belongs to.
        let short_off = (0..layout.root_entries as usize)
            .map(|slot| root + slot * DIR_ENTRY_SIZE)
            .find(|&off| {
                bytes[off + 11] == DirAttributes::LFN.bits() && bytes[off] == LFN_LAST_ENTRY | 1
            })
            .map(|off| off + DIR_ENTRY_SIZE)
            .expect("the fixture holds a single-entry long-name run");

        let orphans_of = |edit: &dyn Fn(&mut [u8])| -> usize {
            let mut edited = bytes.clone();
            edit(&mut edited[short_off..short_off + DIR_ENTRY_SIZE]);
            let mut r = Reader::open_with(
                Cursor::new(edited.as_slice()),
                &OpenOptions::new().policy(ReadPolicy::Lenient),
            )
            .expect("open");
            r.scan()
                .anomalies()
                .iter()
                .filter(|a| a.detail.contains("do not form a complete run"))
                .count()
        };

        // The untouched fixture holds no orphan, so each count below is the edit's.
        assert_eq!(orphans_of(&|_| {}), 0, "the fixture is clean");
        // The run ends at the directory's end marker.
        assert_eq!(
            orphans_of(&|slot| slot[0] = NAME_END),
            1,
            "at the end marker"
        );
        // The short entry was deleted and the run's slots were not.
        assert_eq!(
            orphans_of(&|slot| slot[0] = NAME_DELETED),
            1,
            "at a deleted entry"
        );
        // The run ends at the volume label, which is not a name in the tree.
        assert_eq!(
            orphans_of(&|slot| slot[11] = DirAttributes::VOLUME_ID.bits()),
            1,
            "at the volume label"
        );
        // A fresh last-in-sequence entry starts over, wiping the run in flight; whatever
        // ends the second run may be an orphan of its own, so the bound here is at least.
        assert!(
            orphans_of(&|slot| {
                slot[0] = LFN_LAST_ENTRY | 1;
                slot[11] = DirAttributes::LFN.bits();
            }) >= 1,
            "at a second sequence start"
        );
        // The run ends at a dot entry, whose two slots hold a directory's link to itself
        // and to its parent and never carry a long name. The name is dropped there like
        // the label's is, and the debris is a finding there like the label's is.
        assert_eq!(
            orphans_of(&|slot| {
                slot[..11].copy_from_slice(b".          ");
                slot[11] = DirAttributes::DIRECTORY.bits();
            }),
            1,
            "at a dot entry"
        );
    }

    /// Format a volume and rewrite the first single-entry long-name run in its root region to
    /// spell `name`.
    ///
    /// The ordinal, the last-in-sequence flag, and the checksum are left where they are, so
    /// the run is still well-formed and still belongs to the short entry that follows it.
    /// What changes is the name and nothing else about how the run is formed — which is what
    /// makes the resolved name the only thing under test.
    fn root_long_name_spelling(name: &str) -> Vec<u8> {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        let units: Vec<u16> = name.encode_utf16().collect();
        assert!(
            units.len() < LFN_CHARS_PER_ENTRY,
            "the name and its terminator must fit one entry"
        );
        for slot in 0..layout.root_entries as usize {
            let off = root + slot * DIR_ENTRY_SIZE;
            // A run of exactly one entry: the last-in-sequence flag over ordinal 1.
            if bytes[off + 11] != DirAttributes::LFN.bits() || bytes[off] != LFN_LAST_ENTRY | 1 {
                continue;
            }
            for i in 0..LFN_CHARS_PER_ENTRY {
                // The thirteen units of one entry sit in three ranges the attribute byte and
                // the cluster field divide: five, then six, then two.
                let within = match i {
                    0..=4 => 1 + i * 2,
                    5..=10 => 14 + (i - 5) * 2,
                    _ => 28 + (i - 11) * 2,
                };
                // A name shorter than the entry holding it is terminated by one zero and
                // padded with `FFFF` after it, which is what the writer emits.
                let unit = match i.cmp(&units.len()) {
                    std::cmp::Ordering::Less => units[i],
                    std::cmp::Ordering::Equal => 0,
                    std::cmp::Ordering::Greater => 0xFFFF,
                };
                bytes[off + within..off + within + 2].copy_from_slice(&unit.to_le_bytes());
            }
            return bytes;
        }
        panic!("the fixture holds no single-entry long-name run");
    }

    /// Format a volume and put `name` into the eleven-byte name field of its `EFI` directory
    /// entry — the one name in the fixture the writer stores without a long-name run, so the
    /// eleven bytes are the whole of what the reader has to go on.
    fn root_short_name_of_efi(name: &[u8; 11]) -> Vec<u8> {
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );
        for slot in 0..layout.root_entries as usize {
            let off = root + slot * DIR_ENTRY_SIZE;
            if &bytes[off..off + 11] == b"EFI        " {
                bytes[off..off + 11].copy_from_slice(name);
                return bytes;
            }
        }
        panic!("the fixture holds no EFI entry");
    }

    /// What a name no directory can hold must produce, whichever field it arrived in: a
    /// strict read that stops at it, a lenient read that hands it to nobody, and a scan that
    /// says the volume is not clean.
    fn assert_hostile_name_is_refused(bytes: &[u8], what: &str) {
        let mut strict = Reader::open(Cursor::new(bytes)).expect("open");
        let root_node = strict.root();
        assert!(
            matches!(
                strict.read_dir(&root_node),
                Err(ReadError::HostileName { .. })
            ),
            "{what}: a strict read did not stop at it"
        );

        let mut lenient = Reader::open_with(
            Cursor::new(bytes),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let root_node = lenient.root();
        for entry in lenient.read_dir(&root_node).expect("a lenient read") {
            assert!(
                !is_hostile_component(&entry.name),
                "{what}: read_dir handed back {:?}",
                String::from_utf8_lossy(&entry.name)
            );
        }
        for entry in lenient.walk().expect("a lenient walk") {
            for component in canonical_parts(&entry.path) {
                assert!(
                    !is_hostile_component(component),
                    "{what}: the walk built {:?}",
                    String::from_utf8_lossy(&entry.path)
                );
            }
        }

        // And the volume is not called clean, which is what a consumer gating on
        // `is_clean()` before it extracts is relying on.
        let report = lenient.scan();
        assert!(!report.is_clean(), "{what}: the scan found nothing");
        assert!(
            report
                .anomalies()
                .iter()
                .any(|a| a.severity == Severity::Structural
                    && a.category == Category::Directory
                    && a.detail.contains("no directory can hold")),
            "{what}: {:#?}",
            report.anomalies()
        );
        assert!(report.has_fatal(ReadPolicy::Strict), "{what}");
    }

    #[test]
    fn a_long_name_a_directory_could_not_hold_is_refused_where_it_is_resolved() {
        // A run of long-name entries is reassembled after the dot entries are recognized by
        // their name field, so a run spelling `..` belongs to an ordinary short entry and
        // reaches the name a caller receives. The four names below are the ones a directory
        // cannot hold, and a crafted volume controls every byte of the run — the ordinal, the
        // checksum, and the units — so being well-formed says nothing about what it spells.
        for name in ["..", ".", "a/b", "../etc"] {
            assert_hostile_name_is_refused(&root_long_name_spelling(name), name);
        }
    }

    #[test]
    fn a_short_name_a_directory_could_not_hold_is_refused_where_it_is_resolved() {
        // The other field a name arrives in. An entry with no long-name run is found under
        // its eleven bytes, and nothing in the format stops those bytes being a separator or
        // a NUL — the character set a short name is restricted to is a formatter's rule, not
        // something a reader can assume of an image it did not write.
        for (name, what) in [(b"E/I        ", "a separator"), (b"E\0I        ", "a NUL")] {
            assert_hostile_name_is_refused(&root_short_name_of_efi(name), what);
        }
        // Eleven spaces render to nothing at all. An empty name is not a name: the path
        // built from one is the *directory's own* path with a trailing separator, which is
        // not an entry in that directory — and an archive writer renders it as a member
        // ending in `/`, which every tar reader takes for a directory and merges with the
        // real entry of that name.
        assert_hostile_name_is_refused(&root_short_name_of_efi(b"           "), "an empty name");
    }

    #[cfg(feature = "tar")]
    #[test]
    fn an_archive_of_a_volume_holding_a_traversal_name_carries_no_traversal_member() {
        // The consequence the refusal is there to prevent: this crate turning an untrusted
        // image into an archive whose members climb out of the directory they are unpacked
        // into. A great many tar readers unpack a `..` member where it points.
        let bytes = root_long_name_spelling("..");
        let mut reader = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let mut archive = Vec::new();
        crate::ArchiveSink::new(&mut archive)
            .write_tree(&mut reader)
            .expect("write the archive");

        let mut members = 0usize;
        for entry in tar::Archive::new(archive.as_slice())
            .entries()
            .expect("the archive lists its members")
        {
            let path = entry.expect("a member").path_bytes().to_vec();
            for component in canonical_parts(&path) {
                assert_ne!(
                    component,
                    b"..",
                    "the archive holds {:?}",
                    String::from_utf8_lossy(&path)
                );
            }
            assert!(!path.contains(&0), "a member name carries a NUL");
            members += 1;
        }
        // The rest of the tree is still there, so what the refusal cost is the one entry.
        assert!(members > 1, "the archive holds only {members} members");
    }

    #[test]
    fn a_used_slot_past_the_end_marker_is_reported_and_never_handed_back() {
        // Every driver stops at the marker, so an entry past it is storage nothing else on
        // the volume can see. Handing it back would show a caller a file no other tool
        // agrees exists, which is worse than not showing it — so it is reported and skipped.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let root = at(
            &layout,
            layout.root_dir_start_sector().expect("a root region"),
        );

        // The first free slot, which is where the writer put the end marker, gets an entry.
        let mut placed = None;
        for slot in 0..layout.root_entries as usize {
            let off = root + slot * DIR_ENTRY_SIZE;
            if bytes[off] == NAME_END {
                let mut ghost = [0u8; DIR_ENTRY_SIZE];
                ghost[..11].copy_from_slice(b"GHOST   TXT");
                ghost[11] = DirAttributes::ARCHIVE.bits();
                // A slot after the marker rather than at it, so the marker still terminates
                // the directory and this is genuinely past it.
                let past = off + DIR_ENTRY_SIZE;
                bytes[past..past + DIR_ENTRY_SIZE].copy_from_slice(&ghost);
                placed = Some(slot + 1);
                break;
            }
        }
        assert!(placed.is_some(), "the fixture's root has no free slot");

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let root_node = r.root();
        let names: Vec<Vec<u8>> = r
            .read_dir(&root_node)
            .expect("read")
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(
            !names.contains(&b"GHOST.TXT".to_vec()),
            "an entry past the end marker was handed back: {names:?}"
        );
        assert!(
            r.scan()
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("follows the end marker")),
            "{:#?}",
            r.scan().anomalies()
        );
        // And a strict read stops at it rather than quietly returning the shorter listing.
        let mut strict = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
        let root_node = strict.root();
        assert!(matches!(
            strict.read_dir(&root_node),
            Err(ReadError::EntriesAfterEnd { .. })
        ));
    }

    #[test]
    fn a_scan_that_stopped_short_does_not_report_lost_clusters() {
        // The lost-cluster finding is the one that needs the *whole* allocation: a cluster
        // is lost when nothing reached it, and "nothing reached it" is only true once the
        // walk has been everywhere. A scan that stopped at a bound reached fewer clusters
        // than the tree owns, so reporting the rest as unreferenced would turn a partial
        // traversal into a fact about the volume.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        for limits in [
            Limits::new().max_walk_entries(2),
            Limits::new().max_findings(1),
        ] {
            let mut r = Reader::open_with(
                Cursor::new(image.as_bytes()),
                &OpenOptions::new()
                    .policy(ReadPolicy::Lenient)
                    .limits(limits),
            )
            .expect("open");
            let report = r.scan();
            assert!(
                !report
                    .anomalies()
                    .iter()
                    .any(|a| a.detail.contains("reached by no chain")),
                "a scan that stopped short reported lost clusters: {:#?}",
                report.anomalies()
            );
        }
        // And with no bound in the way, the same volume scans clean — so the case above is
        // the bound doing something rather than the fixture having nothing to find.
        let mut r = Reader::open(Cursor::new(image.as_bytes())).expect("open");
        assert!(r.scan().is_clean());
    }

    #[test]
    fn a_scan_that_never_looked_is_not_a_clean_verdict() {
        // A cap of zero stops the scan before it reads a sector. The report is empty, and it
        // is *not* clean: an absence of findings from a scan that never looked is an absence
        // of looking, and a caller acting on `is_clean` must not read it as a verdict. This
        // is the ext reader's rule too, and it is one rule — both scans collect through the
        // same bounded accumulator, which is what records that reaching the cap stopped it.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let mut r = Reader::open_with(
            Cursor::new(image.as_bytes()),
            &OpenOptions::new()
                .policy(ReadPolicy::Lenient)
                .limits(Limits::new().max_findings(0)),
        )
        .expect("open");
        let report = r.scan();
        assert!(report.anomalies().is_empty());
        assert!(report.is_truncated());
        assert!(!report.is_clean(), "a truncated report claimed a verdict");
        assert!(report.to_report().to_json().contains("\"clean\":false"));
    }

    #[test]
    fn a_chain_that_loops_is_bounded_rather_than_followed() {
        // Nothing in a table says a chain ends, so a chain that points back at itself would
        // be followed forever. The bound is the volume's own cluster count, which a chain
        // cannot exceed without repeating one.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let start = {
            let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
            let node = r.lookup(b"/a-long-file-name.text").expect("lookup");
            match node.storage {
                Storage::Chain(start) => start,
                _ => panic!("the fixture's multi-cluster file owns no chain"),
            }
        };

        // Point the chain's second cluster back at its first.
        for copy in 0..layout.fats {
            let off = at(&layout, layout.fat_start_sector(copy).expect("a table"))
                + table::entry_offset(FatType::Fat16, start + 1) as usize;
            bytes[off..off + 2].copy_from_slice(&(start as u16).to_le_bytes());
        }

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        assert!(matches!(
            r.chain(start),
            Err(ReadError::ChainTooLong { .. })
        ));
        // A *directory* whose chain cycles is the other half, and the expensive one. The
        // chain walks above stop at a repeat in two steps; the slot walk a directory read
        // goes through had no such check and re-read the cycling cluster once per cluster
        // the volume owns before refusing — and a scan absorbs that error and carries on, so
        // the cost was paid afresh for every directory in the volume. A 32 MiB volume of
        // such directories runs to hundreds of gigabytes of reads.
        //
        // Both shapes refuse; only the work says which was done, so the reads are counted.
        let mut cycled = bytes.clone();
        let dir_start = {
            let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
            let node = r.lookup(b"/EFI").expect("lookup");
            match node.storage {
                Storage::Chain(start) => start,
                _ => panic!("a FAT16 subdirectory owns a chain"),
            }
        };
        for copy in 0..layout.fats {
            let off = at(&layout, layout.fat_start_sector(copy).expect("a table"))
                + table::entry_offset(FatType::Fat16, dir_start) as usize;
            cycled[off..off + 2].copy_from_slice(&(dir_start as u16).to_le_bytes());
        }

        let (source, reads) = crate::io::Counting::new(cycled);
        let mut counted =
            Reader::open_with(source, &OpenOptions::new().policy(ReadPolicy::Lenient))
                .expect("open");
        let dir = counted.lookup(b"/EFI").expect("lookup");
        let before = reads.borrow().len();
        assert!(
            matches!(counted.read_dir(&dir), Err(ReadError::ChainTooLong { .. })),
            "a directory whose chain cycles is refused"
        );
        let cost = reads.borrow().len() - before;
        assert!(
            cost < 64,
            "a directory cycling on one cluster cost {cost} reads"
        );

        // And the scan says what it is rather than running forever.
        assert!(!r.scan().is_clean());
    }

    #[test]
    fn a_chain_looping_onto_itself_is_told_apart_from_a_cluster_two_chains_share() {
        // Whose claim is repeated decides what the scan says: a cluster this walk already
        // stepped through is the chain looping onto itself, and blaming "another chain"
        // for it would send a reader hunting for a second file that does not exist. The
        // chain's second cluster is pointed back at its first, so the walk returns to
        // where it began.
        let image = image(64, FatTypeRequest::Exactly(FatType::Fat16));
        let layout = *image.layout();
        let mut bytes = image.into_bytes();
        let start = {
            let mut r = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
            let node = r.lookup(b"/a-long-file-name.text").expect("lookup");
            match node.storage {
                Storage::Chain(start) => start,
                _ => panic!("the fixture's multi-cluster file owns no chain"),
            }
        };
        for copy in 0..layout.fats {
            let off = at(&layout, layout.fat_start_sector(copy).expect("a table"))
                + table::entry_offset(FatType::Fat16, start + 1) as usize;
            bytes[off..off + 2].copy_from_slice(&(start as u16).to_le_bytes());
        }

        let mut r = Reader::open_with(
            Cursor::new(bytes.as_slice()),
            &OpenOptions::new().policy(ReadPolicy::Lenient),
        )
        .expect("open");
        let report = r.scan();
        let said = report
            .anomalies()
            .iter()
            .find(|a| a.detail.contains("loops"))
            .unwrap_or_else(|| panic!("no loop finding: {}", report.to_report().to_table()))
            .detail
            .clone();
        assert!(
            said.contains(&format!(
                "the chain from cluster {start} returns to cluster {start}"
            )),
            "{said}"
        );
        assert!(
            said.contains("a-long-file-name.text"),
            "the owning path rides along: {said}"
        );
        assert!(
            !report
                .anomalies()
                .iter()
                .any(|a| a.detail.contains("another chain")),
            "a loop is not a cross-link: {}",
            report.to_report().to_table()
        );
    }

    #[test]
    fn the_reader_never_panics_on_mangled_images() {
        // The never-panic contract: opening and every read path return errors on malformed
        // bytes, never crash. A deterministic sweep over degenerate geometry, truncations,
        // and bit-flips of a valid volume; the cargo-fuzz target in fuzz/ is the exhaustive
        // version.
        let image = image(2, FatTypeRequest::Exactly(FatType::Fat12)).into_bytes();

        fn drive(bytes: &[u8]) {
            for options in [
                OpenOptions::new(),
                OpenOptions::new().policy(ReadPolicy::Lenient),
                OpenOptions::new()
                    .policy(ReadPolicy::Lenient)
                    .charset(ShortNameCharset::Cp437),
                OpenOptions::new().base(512).policy(ReadPolicy::Lenient),
            ] {
                let Ok(mut r) = Reader::open_with(Cursor::new(bytes), &options) else {
                    continue;
                };
                let _ = r.verify_tables();
                let _ = r.info_sector();
                let _ = r.volume_label();
                let _ = r.scan();
                if let Ok(entries) = r.walk() {
                    for e in &entries {
                        let _ = r.read_data(&e.node);
                        if let Storage::Chain(start) = e.node.storage {
                            let _ = r.chain(start);
                        }
                    }
                    for e in &entries {
                        let _ = r.lookup(&e.path);
                    }
                }
                for path in [&b"/"[..], b"/../..", b"/a/b/c", b"//./"] {
                    let _ = r.lookup(path);
                }
            }
        }

        drive(&image);

        // Degenerate geometry that would divide by zero or underflow if unguarded. Offsets
        // are into the parameter block at the start of sector 0.
        for (off, len, fill) in [
            (11usize, 2usize, 0xffu8), // BPB_BytsPerSec
            (13, 1, 0x00),             // BPB_SecPerClus
            (14, 2, 0xff),             // BPB_RsvdSecCnt
            (16, 1, 0xff),             // BPB_NumFATs
            (17, 2, 0xff),             // BPB_RootEntCnt
            (19, 2, 0xff),             // BPB_TotSec16
            (22, 2, 0xff),             // BPB_FATSz16
            (32, 4, 0xff),             // BPB_TotSec32
        ] {
            let mut mangled = image.clone();
            mangled[off..off + len].fill(fill);
            drive(&mangled);
        }

        // Truncations at assorted lengths.
        for len in [0usize, 1, 511, 512, 513, 1024, 4096, 65_536] {
            drive(&image[..len.min(image.len())]);
        }

        // Deterministic single-byte flips across the metadata region, one image reused
        // (flip, drive, restore) so the sweep stays cheap.
        let mut flip = image.clone();
        let span = flip.len().min(96 * 1024);
        let mut i = 0usize;
        while i < span {
            let orig = flip[i];
            flip[i] ^= 0xff;
            drive(&flip);
            flip[i] = orig;
            i += 251; // a prime stride, so flips land on varied field offsets
        }

        // A few fixed non-image patterns.
        drive(&vec![0x00u8; 8192]);
        drive(&vec![0xffu8; 8192]);
        let ramp: Vec<u8> = (0..8192u32).map(|k| (k % 256) as u8).collect();
        drive(&ramp);
    }
}