fs-mac 0.1.1

Read, edit, create, check and clone classic Mac filesystems: MFS, HFS (incl. HFV images), HFS+/HFSX and Lisa, plus resource forks and BinHex
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
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
use byteorder::{BigEndian, ByteOrder};
#[cfg(feature = "rust173-polyfill")]
use disk_core::rust173::IntIsMultipleOf as _;
use std::cmp::Ordering;
use std::io::{Read, Seek, SeekFrom, Write};

use crate::hfs_common::{
    self, bitmap_clear_bit_be, bitmap_collect_clear_runs_be, bitmap_find_clear_run_be,
    bitmap_set_bit_be, bitmap_test_bit_be, btree_free_node, btree_grow_blocks,
    btree_map_chain_tail, btree_refresh_index_keys, btree_remove_record, BTreeHeader,
    BTreeKeyFormat,
};
use disk_core::entry::{EntryType, FileEntry};
use disk_core::filesystem::CompactResult;
use disk_core::filesystem::{
    CreateDirectoryOptions, CreateFileOptions, EditableFilesystem, Filesystem, FilesystemError,
};

const HFS_SIGNATURE: u16 = 0x4244;
const HFS_PLUS_EMBEDDED_SIGNATURE: u16 = 0x482B;

/// Mac Roman to Unicode lookup table for bytes 0x80-0xFF.
static MAC_ROMAN_TABLE: [char; 128] = [
    '\u{00C4}', '\u{00C5}', '\u{00C7}', '\u{00C9}', '\u{00D1}', '\u{00D6}', '\u{00DC}', '\u{00E1}',
    '\u{00E0}', '\u{00E2}', '\u{00E4}', '\u{00E3}', '\u{00E5}', '\u{00E7}', '\u{00E9}', '\u{00E8}',
    '\u{00EA}', '\u{00EB}', '\u{00ED}', '\u{00EC}', '\u{00EE}', '\u{00EF}', '\u{00F1}', '\u{00F3}',
    '\u{00F2}', '\u{00F4}', '\u{00F6}', '\u{00F5}', '\u{00FA}', '\u{00F9}', '\u{00FB}', '\u{00FC}',
    '\u{2020}', '\u{00B0}', '\u{00A2}', '\u{00A3}', '\u{00A7}', '\u{2022}', '\u{00B6}', '\u{00DF}',
    '\u{00AE}', '\u{00A9}', '\u{2122}', '\u{00B4}', '\u{00A8}', '\u{2260}', '\u{00C6}', '\u{00D8}',
    '\u{221E}', '\u{00B1}', '\u{2264}', '\u{2265}', '\u{00A5}', '\u{00B5}', '\u{2202}', '\u{2211}',
    '\u{220F}', '\u{03C0}', '\u{222B}', '\u{00AA}', '\u{00BA}', '\u{03A9}', '\u{00E6}', '\u{00F8}',
    '\u{00BF}', '\u{00A1}', '\u{00AC}', '\u{221A}', '\u{0192}', '\u{2248}', '\u{2206}', '\u{00AB}',
    '\u{00BB}', '\u{2026}', '\u{00A0}', '\u{00C0}', '\u{00C3}', '\u{00D5}', '\u{0152}', '\u{0153}',
    '\u{2013}', '\u{2014}', '\u{201C}', '\u{201D}', '\u{2018}', '\u{2019}', '\u{00F7}', '\u{25CA}',
    '\u{00FF}', '\u{0178}', '\u{2044}', '\u{20AC}', '\u{2039}', '\u{203A}', '\u{FB01}', '\u{FB02}',
    '\u{2021}', '\u{00B7}', '\u{201A}', '\u{201E}', '\u{2030}', '\u{00C2}', '\u{00CA}', '\u{00C1}',
    '\u{00CB}', '\u{00C8}', '\u{00CD}', '\u{00CE}', '\u{00CF}', '\u{00CC}', '\u{00D3}', '\u{00D4}',
    '\u{F8FF}', '\u{00D2}', '\u{00DA}', '\u{00DB}', '\u{00D9}', '\u{0131}', '\u{02C6}', '\u{02DC}',
    '\u{00AF}', '\u{02D8}', '\u{02D9}', '\u{02DA}', '\u{00B8}', '\u{02DD}', '\u{02DB}', '\u{02C7}',
];

/// Convert a UTF-8 string to Mac Roman bytes.
/// Returns Err if any character cannot be represented in Mac Roman.
pub fn utf8_to_mac_roman(s: &str) -> Result<Vec<u8>, FilesystemError> {
    let mut result = Vec::with_capacity(s.len());
    for ch in s.chars() {
        if (ch as u32) < 0x80 {
            result.push(ch as u8);
        } else {
            // Search the Mac Roman table for this character
            let mut found = false;
            for (i, &table_char) in MAC_ROMAN_TABLE.iter().enumerate() {
                if table_char == ch {
                    result.push((i as u8) + 0x80);
                    found = true;
                    break;
                }
            }
            if !found {
                return Err(FilesystemError::InvalidData(format!(
                    "character '{}' (U+{:04X}) cannot be encoded in Mac Roman",
                    ch, ch as u32
                )));
            }
        }
    }
    Ok(result)
}

/// Decode a Mac Roman byte string to UTF-8.
pub fn mac_roman_to_utf8(data: &[u8]) -> String {
    data.iter()
        .map(|&b| {
            if b < 0x80 {
                b as char
            } else {
                MAC_ROMAN_TABLE[(b - 0x80) as usize]
            }
        })
        .collect()
}

/// Decode an archive/container entry name whose encoding is ambiguous.
///
/// Vintage Mac archives (StuffIt, Compact Pro, MacBinary, MAR) store names in
/// Mac Roman, but some have been re-packed by modern tools that emit UTF-8 — so
/// a `™` arrives as the three UTF-8 bytes `E2 84 A2` instead of Mac Roman `0xAA`.
/// Decoding those blindly as Mac Roman yields mojibake (`‚Ñ¢`).
///
/// Heuristic: if the bytes are valid UTF-8 *and* carry at least one multi-byte
/// (non-ASCII) sequence, treat them as UTF-8; otherwise fall back to Mac Roman.
/// This is safe because a genuine Mac Roman high byte (e.g. `é` = `0x8E`) is a
/// lone byte ≥ 0x80, which is never a valid standalone UTF-8 sequence — so real
/// Mac Roman names always take the Mac Roman path. Pure-ASCII names decode
/// identically either way.
pub fn decode_mac_filename(data: &[u8]) -> String {
    if data.iter().any(|&b| b >= 0x80) {
        if let Ok(s) = std::str::from_utf8(data) {
            return s.to_string();
        }
    }
    mac_roman_to_utf8(data)
}

/// Render a 4-byte Mac OSType (a type or creator code) for display.
///
/// OSType codes are raw Mac Roman bytes, so high bytes like `•` (`0xA5`) must go
/// through the Mac Roman table rather than `from_utf8_lossy` (which renders them
/// as `�`). Control bytes (`< 0x20`) and `0x00` padding render as spaces so the
/// fixed 4-glyph shape is preserved. Trailing spaces are trimmed.
pub fn format_ostype(code: &[u8; 4]) -> String {
    code.iter()
        .map(|&b| match b {
            0x00..=0x1f => ' ',
            b if b < 0x80 => b as char,
            b => MAC_ROMAN_TABLE[(b - 0x80) as usize],
        })
        .collect::<String>()
        .trim_end()
        .to_string()
}

/// Returns `true` if the catalog B-tree header is all zeros (uninitialized).
/// Validate a name for a new file or directory on a classic HFS volume.
/// Returns the encoded Mac Roman bytes on success.
fn validate_hfs_create_name(name: &str) -> Result<Vec<u8>, FilesystemError> {
    if name.is_empty() {
        return Err(FilesystemError::InvalidData(
            "filename is empty — pick a non-blank name".into(),
        ));
    }
    if name.contains(':') {
        return Err(FilesystemError::InvalidData(
            "filename contains ':', which classic Mac OS uses as a path separator — \
             rename the file (try '-' or '_' instead)"
                .into(),
        ));
    }
    let name_bytes = utf8_to_mac_roman(name).map_err(|_| {
        FilesystemError::InvalidData(
            "filename contains characters that can't be encoded in Mac Roman \
             (HFS predates Unicode) — rename using plain ASCII or common accented letters"
                .into(),
        )
    })?;
    if name_bytes.is_empty() {
        return Err(FilesystemError::InvalidData(
            "filename is empty — pick a non-blank name".into(),
        ));
    }
    if name_bytes.len() > 31 {
        return Err(FilesystemError::InvalidData(format!(
            "filename is too long ({} chars); classic HFS allows up to 31 — shorten the name",
            name_bytes.len()
        )));
    }
    Ok(name_bytes)
}

/// Some formatters (notably Disk Jockey's "Empty HFS" image) allocate the
/// catalog extents but leave the bytes zeroed, which would otherwise cause a
/// panic on the first insert because `node_size` parses as 0.
/// Count data-fork extents per file by walking classic HFS catalog leaves.
/// Mirror of `hfsplus_fragmentation_stats` but for the smaller HFS file
/// record layout: 3 inline extents at offset 74, physical-size at offset
/// 30. Forks whose `physical_size_blocks > sum(inline blockCounts)` are
/// flagged as fragmented (overflow into the extents B-tree).
fn hfs_fragmentation_stats(catalog_data: &[u8]) -> disk_core::filesystem::FragmentationStats {
    use crate::hfs_common::walk_leaf_records;

    let mut stats = disk_core::filesystem::FragmentationStats::default();
    if catalog_data.len() < 34 {
        return stats;
    }
    let node_size = BigEndian::read_u16(&catalog_data[32..34]) as usize;
    let first_leaf = BigEndian::read_u32(&catalog_data[24..28]);
    if node_size == 0 || first_leaf == 0 {
        return stats;
    }
    walk_leaf_records::<(), _>(
        catalog_data,
        first_leaf,
        node_size,
        |_node_idx, _rec_idx, _abs_off, rec| {
            if rec.is_empty() {
                return None;
            }
            let key_len = rec[0] as usize;
            let mut data_off = 1 + key_len;
            if !data_off.is_multiple_of(2) {
                data_off += 1;
            }
            if data_off + 102 > rec.len() {
                return None;
            }
            if rec[data_off] as i8 != CATALOG_FILE {
                return None;
            }
            let body = &rec[data_off..];
            let phys_bytes = BigEndian::read_u32(&body[30..34]);
            if phys_bytes == 0 {
                return None;
            }
            let mut inline_extents: u32 = 0;
            let mut inline_blocks: u32 = 0;
            for j in 0..3 {
                let count = BigEndian::read_u16(&body[74 + j * 4 + 2..74 + j * 4 + 4]);
                if count > 0 {
                    inline_extents += 1;
                    inline_blocks = inline_blocks.saturating_add(count as u32);
                }
            }
            stats.files_with_data += 1;
            // Compare physical-size in blocks against inline block coverage.
            // We don't have block_size here (it's in MDB, not catalog), so use
            // ratio approximately: any data fork where inline blocks < physical
            // bytes / 512 (the smallest possible block size) must overflow.
            // Since physical-size is already block-rounded, `inline_blocks
            // == 0 && phys_bytes > 0` is the unambiguous overflow signal.
            let overflows = inline_blocks == 0 && phys_bytes > 0;
            if inline_extents > 1 || overflows {
                stats.fragmented_files += 1;
            }
            None
        },
    );
    stats
}

fn is_catalog_uninitialized(catalog_data: &[u8]) -> bool {
    if catalog_data.len() < 34 {
        return true;
    }
    // node_size field in the BTHeaderRec sits at catalog byte 32..34.
    BigEndian::read_u16(&catalog_data[32..34]) == 0
}

/// The two B-tree files a classic HFS volume keeps in its MDB.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HfsTree {
    Catalog,
    Extents,
}

impl HfsTree {
    fn label(self) -> &'static str {
        match self {
            HfsTree::Catalog => "catalog",
            HfsTree::Extents => "extents-overflow",
        }
    }
}

/// HFS extent descriptor: start_block (u16) + block_count (u16).
#[derive(Debug, Clone, Copy)]
pub struct HfsExtDescriptor {
    pub start_block: u16,
    pub block_count: u16,
}

/// Result of [`HfsFilesystem::locate_file_by_cnid`]. `offset_in_image` is
/// absolute within the underlying image file, so scripts patching
/// disk-byte offsets into boot blocks or supervisor payloads can use it
/// directly without re-adding any partition base.
#[derive(Debug, Clone, Copy)]
pub struct HfsFileLocation {
    pub offset_in_image: u64,
    pub length: u64,
    pub fragmented: bool,
}

/// Lightweight, public snapshot of an HFS volume's headline numbers.
/// Returned by [`HfsFilesystem::volume_summary`] so GUI code outside the
/// library crate can populate display fields without touching pub(crate)
/// internals.
#[derive(Debug, Clone)]
pub struct HfsVolumeSummary {
    pub volume_name: String,
    pub block_size: u32,
    pub total_blocks: u16,
    pub free_blocks: u16,
    pub used_bytes: u64,
    pub file_count: u32,
    pub folder_count: u32,
    pub catalog_file_size: u32,
    pub extents_file_size: u32,
}

impl HfsExtDescriptor {
    pub fn parse(data: &[u8]) -> Self {
        HfsExtDescriptor {
            start_block: BigEndian::read_u16(&data[0..2]),
            block_count: BigEndian::read_u16(&data[2..4]),
        }
    }

    fn serialize(&self, out: &mut [u8]) {
        BigEndian::write_u16(&mut out[0..2], self.start_block);
        BigEndian::write_u16(&mut out[2..4], self.block_count);
    }
}

/// HFS Master Directory Block (MDB) — at partition_offset + 1024.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct HfsMasterDirectoryBlock {
    pub(crate) signature: u16,
    pub(crate) create_date: u32,
    pub(crate) modify_date: u32,
    pub(crate) total_blocks: u16,
    pub(crate) block_size: u32,
    pub(crate) free_blocks: u16,
    pub(crate) volume_name: String,
    pub(crate) volume_name_raw: Vec<u8>,
    pub(crate) volume_bitmap_block: u16,
    /// First allocation block's offset in 512-byte sectors from partition start.
    pub(crate) first_alloc_block: u16,
    pub(crate) next_catalog_id: u32,
    pub(crate) file_count: u32,
    pub(crate) folder_count: u32,
    pub(crate) finder_info: [u32; 8],
    pub(crate) catalog_file_size: u32,
    pub(crate) catalog_file_extents: [HfsExtDescriptor; 3],
    pub(crate) extents_file_size: u32,
    pub(crate) extents_file_extents: [HfsExtDescriptor; 3],
    pub(crate) embedded_signature: u16,
    pub(crate) embedded_start_block: u16,
    pub(crate) embedded_block_count: u16,
    /// Raw 512-byte sector for serialization (preserve fields we don't explicitly parse).
    pub(crate) raw_sector: [u8; 512],
}

impl HfsMasterDirectoryBlock {
    fn parse(data: &[u8]) -> Result<Self, FilesystemError> {
        if data.len() < 162 {
            return Err(FilesystemError::Parse("MDB too short".into()));
        }
        let sig = BigEndian::read_u16(&data[0..2]);
        if sig != HFS_SIGNATURE {
            return Err(FilesystemError::Parse(format!(
                "bad MDB signature: 0x{sig:04X}"
            )));
        }

        // Volume name: Pascal string at offset 36 (length byte + up to 27 chars)
        let name_len = data[36] as usize;
        let name_bytes = &data[37..37 + name_len.min(27)];
        let volume_name = mac_roman_to_utf8(name_bytes);
        let volume_name_raw = name_bytes.to_vec();

        let mut extents_extents = [HfsExtDescriptor {
            start_block: 0,
            block_count: 0,
        }; 3];
        for i in 0..3 {
            extents_extents[i] = HfsExtDescriptor::parse(&data[134 + i * 4..138 + i * 4]);
        }

        let mut catalog_extents = [HfsExtDescriptor {
            start_block: 0,
            block_count: 0,
        }; 3];
        for i in 0..3 {
            catalog_extents[i] = HfsExtDescriptor::parse(&data[150 + i * 4..154 + i * 4]);
        }

        // Embedded HFS+ info at offsets 124-130
        let embedded_sig = BigEndian::read_u16(&data[124..126]);
        let embedded_start = BigEndian::read_u16(&data[126..128]);
        let embedded_count = BigEndian::read_u16(&data[128..130]);

        // Finder info at offset 92 (32 bytes = 8 × u32)
        let mut finder_info = [0u32; 8];
        for i in 0..8 {
            finder_info[i] = BigEndian::read_u32(&data[92 + i * 4..96 + i * 4]);
        }

        // Preserve raw sector for faithful serialization
        let mut raw_sector = [0u8; 512];
        let copy_len = data.len().min(512);
        raw_sector[..copy_len].copy_from_slice(&data[..copy_len]);

        Ok(HfsMasterDirectoryBlock {
            signature: sig,
            create_date: BigEndian::read_u32(&data[2..6]),
            modify_date: BigEndian::read_u32(&data[6..10]),
            total_blocks: BigEndian::read_u16(&data[18..20]),
            block_size: BigEndian::read_u32(&data[20..24]),
            free_blocks: BigEndian::read_u16(&data[34..36]),
            volume_name,
            volume_name_raw,
            volume_bitmap_block: BigEndian::read_u16(&data[14..16]),
            first_alloc_block: BigEndian::read_u16(&data[28..30]),
            next_catalog_id: BigEndian::read_u32(&data[30..34]),
            file_count: BigEndian::read_u32(&data[84..88]),
            folder_count: BigEndian::read_u32(&data[88..92]),
            finder_info,
            extents_file_size: BigEndian::read_u32(&data[130..134]),
            extents_file_extents: extents_extents,
            catalog_file_size: BigEndian::read_u32(&data[146..150]),
            catalog_file_extents: catalog_extents,
            embedded_signature: embedded_sig,
            embedded_start_block: embedded_start,
            embedded_block_count: embedded_count,
            raw_sector,
        })
    }

    /// Serialize MDB back to a 512-byte sector.
    /// Uses the raw sector as a base and overwrites fields we may have modified.
    fn serialize_to_sector(&self) -> [u8; 512] {
        let mut out = self.raw_sector;
        BigEndian::write_u32(&mut out[6..10], self.modify_date);
        BigEndian::write_u16(&mut out[18..20], self.total_blocks);
        BigEndian::write_u16(&mut out[34..36], self.free_blocks);
        BigEndian::write_u32(&mut out[30..34], self.next_catalog_id);
        BigEndian::write_u32(&mut out[84..88], self.file_count);
        BigEndian::write_u32(&mut out[88..92], self.folder_count);
        for i in 0..8 {
            BigEndian::write_u32(&mut out[92 + i * 4..96 + i * 4], self.finder_info[i]);
        }
        BigEndian::write_u32(&mut out[130..134], self.extents_file_size);
        for i in 0..3 {
            self.extents_file_extents[i].serialize(&mut out[134 + i * 4..138 + i * 4]);
        }
        BigEndian::write_u32(&mut out[146..150], self.catalog_file_size);
        for i in 0..3 {
            self.catalog_file_extents[i].serialize(&mut out[150 + i * 4..154 + i * 4]);
        }
        out
    }

    /// True if this MDB wraps an embedded HFS+ volume.
    fn has_embedded_hfs_plus(&self) -> bool {
        self.embedded_signature == HFS_PLUS_EMBEDDED_SIGNATURE
    }
}

/// Catalog record types.
pub(crate) const CATALOG_DIR: i8 = 1;
/// The catalog file's own CNID; extents past the MDB's three sit in the overflow tree.
const CNID_CATALOG: u32 = 4;
pub(crate) const CATALOG_FILE: i8 = 2;

/// Decode a 4-byte Mac OS type/creator code to a string.
/// Non-printable bytes are replaced with '.'.
/// A parsed HFS catalog record.
#[derive(Debug, Clone)]
#[allow(dead_code)]
enum CatalogRecord {
    Directory {
        dir_id: u32,
        name: String,
        parent_id: u32,
        /// Catalog dates `(create, modify, backup)` in Mac-epoch seconds.
        dates: (u32, u32, u32),
    },
    File {
        file_id: u32,
        name: String,
        parent_id: u32,
        data_size: u32,
        data_extents: [HfsExtDescriptor; 3],
        rsrc_size: u32,
        rsrc_extents: [HfsExtDescriptor; 3],
        /// Raw 4-byte Mac OSType type/creator, straight off disk (no lossy
        /// display decode) so high-bit codes survive round-trips.
        type_code: [u8; 4],
        creator_code: [u8; 4],
        /// Finder flags (FInfo.fdFlags) — bit 0x8000 is `kIsAlias`.
        finder_flags: u16,
        /// Catalog dates `(create, modify, backup)` in Mac-epoch seconds.
        dates: (u32, u32, u32),
    },
}

/// Classic HFS filesystem implementation.
pub struct HfsFilesystem<R: Read + Seek> {
    reader: R,
    partition_offset: u64,
    /// Partition length when the caller knows it; the alternate MDB lives in
    /// the partition's last kilobyte, which need not follow the last block.
    partition_size: Option<u64>,
    mdb: HfsMasterDirectoryBlock,
    /// Cached catalog file data.
    catalog_data: Vec<u8>,
    /// Cached extents-overflow B-tree file data, lazily loaded on first
    /// read of a file that needs more than its 3 inline extents.
    extents_overflow_data: Option<Vec<u8>>,
    /// Cached volume bitmap (lazy-loaded on first edit operation).
    bitmap: Option<Vec<u8>>,
    /// Boot block payload staged by `set_boot_blocks`; flushed on `sync_metadata`.
    pending_boot_blocks: Option<Box<[u8; 1024]>>,
    /// Volume (create, modify, backup) dates staged by `set_volume_dates`.
    /// When Some, overrides the automatic `hfs_now()` stamp in `sync_metadata`.
    pending_volume_dates: Option<(u32, u32, u32)>,
    /// When set (via `begin_bulk` / `end_bulk`), per-operation rollback
    /// snapshots are skipped: `snapshot()` returns `None`. The caller takes
    /// responsibility for batch-level atomicity (discarding all changes if any
    /// operation fails). Used by `tar_import` so a large import doesn't clone
    /// the whole multi-megabyte catalog on every single `create_file`.
    bulk_mode: bool,
    /// Cache for `ensure_catalog_initialized`: once both B-trees are confirmed
    /// live, this short-circuits the check. Without it every edit re-reads the
    /// (multi-megabyte) extents-overflow fork from disk just to test whether
    /// it's blank — death by a thousand reads on a large import.
    btrees_initialized: bool,
}

impl<R: Read + Seek> HfsFilesystem<R> {
    /// Where the alternate MDB lives: the partition's next-to-last sector when
    /// the length is known, else the sector after the last allocation block.
    fn alt_mdb_offset(&self) -> Option<u64> {
        if let Some(size) = self.partition_size.filter(|&s| s >= 2048) {
            return Some(self.partition_offset + size - 1024);
        }
        if self.mdb.block_size == 0 || self.mdb.total_blocks == 0 {
            return None;
        }
        let sectors_per_block = self.mdb.block_size as u64 / 512;
        let alt_sector =
            self.mdb.first_alloc_block as u64 + self.mdb.total_blocks as u64 * sectors_per_block;
        Some(self.partition_offset + alt_sector * 512)
    }

    pub fn open(reader: R, partition_offset: u64) -> Result<Self, FilesystemError> {
        Self::open_sized(reader, partition_offset, None)
    }

    /// [`open_sized`](Self::open_sized) for an edit: a volume smaller than its
    /// partition is warned about once, since Mac OS will refuse it (R-058).
    pub fn open_for_edit(
        reader: R,
        partition_offset: u64,
        partition_size: Option<u64>,
    ) -> Result<Self, FilesystemError> {
        let fs = Self::open_sized(reader, partition_offset, partition_size)?;
        if let Some(short) = fs.partition_shortfall() {
            log::warn!(
                "the HFS volume is {short} bytes smaller than its partition; Mac OS and Disk \
                 First Aid expect a classic HFS volume to fill its partition. Grow it with \
                 `rb-cli resize IMG@N --size <partition size>` (R-058)"
            );
        }
        Ok(fs)
    }

    /// Bytes by which the volume falls short of its partition, when the
    /// partition length is known and the volume does not fill it.
    pub fn partition_shortfall(&self) -> Option<u64> {
        let size = self.partition_size.filter(|&s| s >= 2048)?;
        if self.mdb.block_size == 0 {
            return None;
        }
        let volume_len = self.mdb.first_alloc_block as u64 * 512
            + self.mdb.total_blocks as u64 * self.mdb.block_size as u64
            + 1024;
        if volume_len < size {
            Some(size - volume_len)
        } else {
            None
        }
    }

    /// [`open`](Self::open) with the partition length, so the alternate MDB is
    /// read and written at the partition end as Mac OS and Disk First Aid expect.
    pub fn open_sized(
        mut reader: R,
        partition_offset: u64,
        partition_size: Option<u64>,
    ) -> Result<Self, FilesystemError> {
        // Read MDB at offset + 1024 (sector 2) — full 512-byte sector
        reader.seek(SeekFrom::Start(partition_offset + 1024))?;
        let mut mdb_buf = [0u8; 512];
        reader.read_exact(&mut mdb_buf)?;
        let mdb = HfsMasterDirectoryBlock::parse(&mdb_buf)?;

        if mdb.has_embedded_hfs_plus() {
            return Err(FilesystemError::Unsupported(
                "this HFS volume contains an embedded HFS+ volume; use HFS+ reader instead".into(),
            ));
        }

        // Read the catalog file
        let catalog_data = read_fork_data(
            &mut reader,
            partition_offset,
            &mdb,
            &mdb.catalog_file_extents,
            mdb.catalog_file_size as u64,
        )?;

        let mut fs = HfsFilesystem {
            reader,
            partition_offset,
            partition_size,
            mdb,
            catalog_data,
            extents_overflow_data: None,
            bitmap: None,
            pending_boot_blocks: None,
            pending_volume_dates: None,
            bulk_mode: false,
            btrees_initialized: false,
        };
        // A catalog grown past its three inline extents continues in the
        // extents-overflow tree under CNID 4, the way Mac OS extends it.
        if (fs.catalog_data.len() as u64) < fs.mdb.catalog_file_size as u64 {
            let inline = fs.mdb.catalog_file_extents;
            let size = fs.mdb.catalog_file_size as u64;
            fs.catalog_data = fs.read_fork_with_overflow(CNID_CATALOG, 0x00, &inline, size)?;
        }
        Ok(fs)
    }

    /// List all catalog records with a given parent_id.
    fn list_children(&self, parent_id: u32) -> Result<Vec<CatalogRecord>, FilesystemError> {
        if self.catalog_data.len() < 512 {
            return Ok(vec![]);
        }

        // Read B-tree header from node 0
        // Node descriptor: 14 bytes, then BTHeaderRec starts
        // BTHeaderRec: treeDepth(2) + rootNode(4) + leafRecords(4) + firstLeafNode(4) + ...
        let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as u32;
        if node_size == 0 || self.catalog_data.len() < node_size as usize {
            return Ok(vec![]);
        }
        let header_node = &self.catalog_data[0..node_size as usize];
        let first_leaf = BigEndian::read_u32(&header_node[24..28]);

        let mut results = Vec::new();
        let mut node_idx = first_leaf;

        while node_idx != 0 {
            let offset = node_idx as usize * node_size as usize;
            if offset + node_size as usize > self.catalog_data.len() {
                break;
            }
            let node = &self.catalog_data[offset..offset + node_size as usize];

            // Node descriptor
            let next_node = BigEndian::read_u32(&node[0..4]);
            let _kind = node[8] as i8; // should be -1 for leaf
            let num_records = BigEndian::read_u16(&node[10..12]);

            for i in 0..num_records as usize {
                // Record offset is stored at end of node, growing backward
                let offset_pos = node_size as usize - 2 * (i + 1);
                if offset_pos + 2 > node.len() {
                    break;
                }
                let rec_offset = BigEndian::read_u16(&node[offset_pos..offset_pos + 2]) as usize;
                if rec_offset + 6 > node.len() {
                    continue;
                }

                // Parse catalog key
                let key_len = node[rec_offset] as usize;
                if key_len < 6 || rec_offset + 1 + key_len > node.len() {
                    continue;
                }
                let key_data = &node[rec_offset + 1..rec_offset + 1 + key_len];
                // key_data: reserved(1) + parent_id(4) + name_len(1) + name(N)
                let rec_parent_id = BigEndian::read_u32(&key_data[1..5]);
                let name_len = key_data[5] as usize;
                let name = if name_len > 0 && 6 + name_len <= key_data.len() {
                    mac_roman_to_utf8(&key_data[6..6 + name_len])
                } else {
                    String::new()
                };

                // Record data follows key (aligned to even boundary)
                let mut rec_data_offset = rec_offset + 1 + key_len;
                if !rec_data_offset.is_multiple_of(2) {
                    rec_data_offset += 1;
                }
                if rec_data_offset + 2 > node.len() {
                    continue;
                }

                let record_type = node[rec_data_offset] as i8;

                if rec_parent_id != parent_id {
                    continue;
                }

                match record_type {
                    CATALOG_DIR => {
                        if rec_data_offset + 70 > node.len() {
                            continue;
                        }
                        let dir_id =
                            BigEndian::read_u32(&node[rec_data_offset + 6..rec_data_offset + 10]);
                        // Dir record dates: crDate@10, mdDate@14, bkDate@18.
                        let dir = &node[rec_data_offset..];
                        let dates = (
                            BigEndian::read_u32(&dir[10..14]),
                            BigEndian::read_u32(&dir[14..18]),
                            BigEndian::read_u32(&dir[18..22]),
                        );
                        results.push(CatalogRecord::Directory {
                            dir_id,
                            name,
                            parent_id: rec_parent_id,
                            dates,
                        });
                    }
                    CATALOG_FILE => {
                        if rec_data_offset + 102 > node.len() {
                            continue;
                        }
                        let rec = &node[rec_data_offset..];
                        // Finder Info (FInfo) at offset 4: fdType(4) + fdCreator(4) + fdFlags(2)
                        let type_code: [u8; 4] = rec[4..8].try_into().unwrap();
                        let creator_code: [u8; 4] = rec[8..12].try_into().unwrap();
                        let finder_flags = BigEndian::read_u16(&rec[12..14]);
                        // File ID (filFlNum) at offset 20
                        let file_id = BigEndian::read_u32(&rec[20..24]);
                        // Data fork: logical size at offset 26, first 3 extents at 74
                        let data_size = BigEndian::read_u32(&rec[26..30]);
                        let mut data_extents = [HfsExtDescriptor {
                            start_block: 0,
                            block_count: 0,
                        }; 3];
                        for j in 0..3 {
                            data_extents[j] = HfsExtDescriptor::parse(&rec[74 + j * 4..78 + j * 4]);
                        }
                        // Resource fork: logical size at offset 36, extents at 86
                        let rsrc_size = BigEndian::read_u32(&rec[36..40]);
                        let mut rsrc_extents = [HfsExtDescriptor {
                            start_block: 0,
                            block_count: 0,
                        }; 3];
                        for j in 0..3 {
                            rsrc_extents[j] = HfsExtDescriptor::parse(&rec[86 + j * 4..90 + j * 4]);
                        }
                        // File record dates: crDate@44, mdDate@48, bkDate@52.
                        let dates = (
                            BigEndian::read_u32(&rec[44..48]),
                            BigEndian::read_u32(&rec[48..52]),
                            BigEndian::read_u32(&rec[52..56]),
                        );
                        results.push(CatalogRecord::File {
                            file_id,
                            name,
                            parent_id: rec_parent_id,
                            data_size,
                            data_extents,
                            rsrc_size,
                            rsrc_extents,
                            type_code,
                            creator_code,
                            finder_flags,
                            dates,
                        });
                    }
                    _ => {}
                }
            }

            node_idx = next_node;
        }

        Ok(results)
    }

    /// Find a file record by its file_id (CNID) in the catalog B-tree.
    /// Returns (data_size, data_extents, rsrc_size, rsrc_extents).
    fn find_file_by_id(
        &self,
        file_id: u32,
    ) -> Option<(u32, [HfsExtDescriptor; 3], u32, [HfsExtDescriptor; 3])> {
        if self.catalog_data.len() < 512 {
            return None;
        }
        let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as u32;
        if node_size == 0 || self.catalog_data.len() < node_size as usize {
            return None;
        }
        let header_node = &self.catalog_data[0..node_size as usize];
        let first_leaf = BigEndian::read_u32(&header_node[24..28]);

        let mut node_idx = first_leaf;
        while node_idx != 0 {
            let offset = node_idx as usize * node_size as usize;
            if offset + node_size as usize > self.catalog_data.len() {
                break;
            }
            let node = &self.catalog_data[offset..offset + node_size as usize];
            let next_node = BigEndian::read_u32(&node[0..4]);
            let num_records = BigEndian::read_u16(&node[10..12]);

            for i in 0..num_records as usize {
                let offset_pos = node_size as usize - 2 * (i + 1);
                if offset_pos + 2 > node.len() {
                    break;
                }
                let rec_offset = BigEndian::read_u16(&node[offset_pos..offset_pos + 2]) as usize;
                if rec_offset + 6 > node.len() {
                    continue;
                }
                let key_len = node[rec_offset] as usize;
                if key_len < 6 || rec_offset + 1 + key_len > node.len() {
                    continue;
                }
                let mut rec_data_offset = rec_offset + 1 + key_len;
                if !rec_data_offset.is_multiple_of(2) {
                    rec_data_offset += 1;
                }
                if rec_data_offset + 2 > node.len() {
                    continue;
                }
                let record_type = node[rec_data_offset] as i8;
                if record_type != CATALOG_FILE {
                    continue;
                }
                if rec_data_offset + 102 > node.len() {
                    continue;
                }
                let rec = &node[rec_data_offset..];
                // File ID (filFlNum) at offset 20
                let rec_file_id = BigEndian::read_u32(&rec[20..24]);
                if rec_file_id != file_id {
                    continue;
                }
                // Data fork: logical size at offset 26, extents at 74
                let data_size = BigEndian::read_u32(&rec[26..30]);
                let mut data_extents = [HfsExtDescriptor {
                    start_block: 0,
                    block_count: 0,
                }; 3];
                for j in 0..3 {
                    data_extents[j] = HfsExtDescriptor::parse(&rec[74 + j * 4..78 + j * 4]);
                }
                // Resource fork: logical size at offset 36, extents at 86
                let rsrc_size = BigEndian::read_u32(&rec[36..40]);
                let mut rsrc_extents = [HfsExtDescriptor {
                    start_block: 0,
                    block_count: 0,
                }; 3];
                for j in 0..3 {
                    rsrc_extents[j] = HfsExtDescriptor::parse(&rec[86 + j * 4..90 + j * 4]);
                }
                return Some((data_size, data_extents, rsrc_size, rsrc_extents));
            }
            node_idx = next_node;
        }
        None
    }

    /// Read the volume bitmap and return it.
    fn read_volume_bitmap(&mut self) -> Result<Vec<u8>, FilesystemError> {
        let bitmap_offset = self.partition_offset + self.mdb.volume_bitmap_block as u64 * 512;
        let bitmap_size = (self.mdb.total_blocks as u32).div_ceil(8) as usize;
        self.reader.seek(SeekFrom::Start(bitmap_offset))?;
        let mut bitmap = vec![0u8; bitmap_size];
        self.reader.read_exact(&mut bitmap)?;
        Ok(bitmap)
    }

    /// Return the byte offset of allocation block `n` from partition start.
    fn alloc_block_offset(&self, block: u32) -> u64 {
        self.mdb.first_alloc_block as u64 * 512 + block as u64 * self.mdb.block_size as u64
    }

    /// Ensure bitmap is loaded.
    fn ensure_bitmap(&mut self) -> Result<(), FilesystemError> {
        if self.bitmap.is_none() {
            let bm = self.read_volume_bitmap()?;
            self.bitmap = Some(bm);
        }
        Ok(())
    }

    /// Run filesystem integrity check. Loads bitmap if not already cached.
    pub fn fsck(&mut self) -> Result<disk_core::fsck::FsckResult, FilesystemError> {
        self.ensure_bitmap()?;
        // Load extents overflow B-tree if it exists (for files with >3 extents)
        let extents_data = if self.mdb.extents_file_size > 0 {
            read_fork_data(
                &mut self.reader,
                self.partition_offset,
                &self.mdb,
                &self.mdb.extents_file_extents,
                self.mdb.extents_file_size as u64,
            )
            .ok()
        } else {
            None
        };
        // Read the alternate MDB — located at the sector immediately after
        // the last allocation block on the volume.
        let alt_mdb_sector = if let Some(alt_offset) = self.alt_mdb_offset() {
            let mut alt_buf = [0u8; 512];
            if self
                .reader
                .seek(SeekFrom::Start(alt_offset))
                .and_then(|_| self.reader.read_exact(&mut alt_buf))
                .is_ok()
            {
                Some(alt_buf)
            } else {
                None
            }
        } else {
            None
        };
        Ok(crate::hfs_fsck::check_hfs_integrity(
            &self.mdb,
            &self.catalog_data,
            self.bitmap.as_ref().unwrap(),
            extents_data.as_deref(),
            alt_mdb_sector.as_ref(),
            self.partition_size,
        ))
    }

    /// Build classic HFS catalog key: key_len(1) + reserved(1) + parent_id(4) + name_len(1) + name(Mac Roman).
    pub(crate) fn build_catalog_key(parent_id: u32, name: &[u8]) -> Vec<u8> {
        let key_len = 1 + 4 + 1 + name.len(); // reserved + parent_id + name_len + name
        let mut key = Vec::with_capacity(1 + key_len);
        key.push(key_len as u8); // key_len
        key.push(0); // reserved
        let mut buf4 = [0u8; 4];
        BigEndian::write_u32(&mut buf4, parent_id);
        key.extend_from_slice(&buf4);
        key.push(name.len() as u8);
        key.extend_from_slice(name);
        // Pad to even length if needed (HFS B-tree records are even-aligned)
        if key.len() % 2 != 0 {
            key.push(0);
        }
        key
    }

    /// Compare function for HFS catalog keys (key portion only).
    pub(crate) fn catalog_compare(a: &[u8], b: &[u8]) -> Ordering {
        // Format: key_len(1) + reserved(1) + parent_id(4) + name_len(1) + name(Mac Roman)
        if a.len() < 7 || b.len() < 7 {
            return a.len().cmp(&b.len());
        }
        let parent_a = BigEndian::read_u32(&a[2..6]);
        let parent_b = BigEndian::read_u32(&b[2..6]);
        let name_len_a = a[6] as usize;
        let name_len_b = b[6] as usize;
        let name_a = &a[7..7 + name_len_a.min(a.len() - 7)];
        let name_b = &b[7..7 + name_len_b.min(b.len() - 7)];
        hfs_common::compare_hfs_keys(parent_a, name_a, parent_b, name_b)
    }

    /// Find a catalog record by (parent_id, name).
    /// Returns Some((node_idx, rec_idx, absolute_offset_in_catalog_data)) if found.
    ///
    /// Descends the B-tree index to the single leaf that would hold the key and
    /// scans only that leaf — O(log n), not a walk of the whole leaf chain. In
    /// a consistent catalog a key lives in exactly one leaf (the one the search
    /// path reaches), so this is exact. It matters at scale: `create_file` /
    /// `create_directory` / `rename` call this for duplicate detection on every
    /// entry, so a linear walk here made bulk imports (`untar`) O(n^2). The
    /// index is kept consistent by the incremental inserter
    /// ([`hfs_common::btree_insert_full`]); on a structurally broken catalog
    /// (pre-fsck) prefer repairing first — editing assumes a healthy tree.
    fn find_catalog_record_by_name(
        &self,
        parent_id: u32,
        name: &[u8],
    ) -> Option<(u32, usize, usize)> {
        let search_key = Self::build_catalog_key(parent_id, name);
        let header = BTreeHeader::read(&self.catalog_data);
        let node_size = header.node_size as usize;
        if node_size == 0 || self.catalog_data.len() < node_size {
            return None;
        }

        let (leaf_idx, _) = hfs_common::btree_find_insert_leaf(
            &self.catalog_data,
            &header,
            &search_key,
            &Self::catalog_compare,
        );

        let off = leaf_idx as usize * node_size;
        if off + node_size > self.catalog_data.len() {
            return None;
        }
        let node = &self.catalog_data[off..off + node_size];
        let num_records = BigEndian::read_u16(&node[10..12]) as usize;
        for rec_idx in 0..num_records {
            let (start, end) = hfs_common::btree_record_range(node, node_size, rec_idx);
            if start >= end || end > node_size {
                continue;
            }
            let rec = &node[start..end];
            if rec.len() < 7 {
                continue;
            }
            let key_len = rec[0] as usize;
            let key_end = 1 + key_len;
            if key_end > rec.len() {
                continue;
            }
            if Self::catalog_compare(&rec[..key_end], &search_key) == Ordering::Equal {
                return Some((leaf_idx, rec_idx, off + start));
            }
        }
        None
    }

    /// Find a thread record by CNID (thread key: parent_id=cnid, name="").
    fn find_catalog_record_by_cnid(&self, cnid: u32) -> Option<(u32, usize, usize)> {
        self.find_catalog_record_by_name(cnid, &[])
    }

    /// Update parent folder valence (child count) by delta.
    fn update_parent_valence(&mut self, parent_id: u32, delta: i32) -> Result<(), FilesystemError> {
        let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as usize;
        let first_leaf = BigEndian::read_u32(&self.catalog_data[24..28]);

        // Walk leaves to locate the dir record's valence offset; mutate after
        // the borrow ends so we satisfy the &mut self mutation rule.
        let val_off = hfs_common::walk_leaf_records(
            &self.catalog_data,
            first_leaf,
            node_size,
            |_node_idx, _rec_idx, abs_off, rec| {
                if rec.len() < 7 {
                    return None;
                }
                let key_len = rec[0] as usize;
                let mut data_off = abs_off + 1 + key_len;
                if !data_off.is_multiple_of(2) {
                    data_off += 1;
                }
                let abs_end = abs_off + rec.len();
                if data_off + 10 > abs_end {
                    return None;
                }
                if self.catalog_data[data_off] as i8 != CATALOG_DIR {
                    return None;
                }
                // Dir record: type(1) + reserved(1) + flags(2) + valence(2) + dirID(4)
                let dir_id = BigEndian::read_u32(&self.catalog_data[data_off + 6..data_off + 10]);
                if dir_id == parent_id {
                    Some(data_off + 4)
                } else {
                    None
                }
            },
        );
        let val_off = val_off.ok_or_else(|| {
            FilesystemError::NotFound(format!(
                "parent directory CNID {} not found in catalog",
                parent_id
            ))
        })?;
        let old_val = BigEndian::read_u16(&self.catalog_data[val_off..val_off + 2]);
        let new_val = (old_val as i32 + delta).max(0) as u16;
        BigEndian::write_u16(&mut self.catalog_data[val_off..val_off + 2], new_val);
        Ok(())
    }

    /// Insert a catalog record into the B-tree, handling splits and growth.
    ///
    /// Delegates to the shared incremental inserter
    /// ([`hfs_common::btree_insert_full`]) — the same find-leaf /
    /// split-with-insert / grow-root-or-insert-into-parent machinery that HFS+
    /// and the streamed defrag builder use. It maintains the index nodes
    /// incrementally (O(log n) per insert) rather than rebuilding the entire
    /// index after every leaf split.
    ///
    /// The previous per-split `rebuild_index_nodes` approach was O(n) per split
    /// (O(n^2) over a bulk import like `untar`) and, worse, corrupted the tree
    /// once it grew past the header node's 2048-bit allocation bitmap: the
    /// rebuild's free-all-index-nodes pass was capped at that bitmap, so index
    /// nodes living in map-node-covered segments leaked. That drained the free
    /// nodes until a rebuild ran out mid-flight and left the index with broken
    /// sibling links — surfacing as the spurious "disk full: no free B-tree
    /// nodes" / `IndexSiblingLinkBroken` failure at ~7.4k catalog records.
    fn insert_catalog_record(&mut self, key_record: &[u8]) -> Result<(), FilesystemError>
    where
        R: Write,
    {
        // Out of nodes: grow the catalog file by a clump and retry once, as
        // Mac OS does (F-016). The failed insert left the tree untouched.
        let mut grown = false;
        loop {
            match hfs_common::btree_insert_full(
                &mut self.catalog_data,
                key_record,
                &hfs_common::BTreeKeyFormat::CLASSIC_CATALOG,
                &Self::catalog_compare,
            ) {
                Ok(()) => return Ok(()),
                Err(FilesystemError::DiskFull(_)) if !grown => {
                    self.grow_btree(HfsTree::Catalog)?;
                    grown = true;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Grow the catalog or extents-overflow file by a clump of nodes: extend
    /// its last extent when the blocks after it are free, else take a fresh
    /// inline extent slot; publish the nodes (and a map node when the bitmap
    /// runs out) and the new file size in the MDB (F-016).
    fn grow_btree(&mut self, tree: HfsTree) -> Result<(), FilesystemError>
    where
        R: Write,
    {
        let block_size = self.mdb.block_size;
        if tree == HfsTree::Extents {
            self.ensure_extents_overflow()?;
        }
        let (node_size, total_nodes, existing_map) = {
            let buf = self.tree_buf(tree)?;
            let h = BTreeHeader::read(buf);
            let segs = hfs_common::btree_bitmap_segments(buf, h.node_size as usize);
            (
                h.node_size as usize,
                h.total_nodes,
                (segs.len() as u32).saturating_sub(1),
            )
        };
        if node_size < 256 || block_size == 0 {
            return Err(FilesystemError::InvalidData(format!(
                "{} B-tree has node size {node_size}",
                tree.label()
            )));
        }
        // drXTClpSiz / drCTClpSiz: the clump Mac OS itself extends the file by.
        let clump_off = if tree == HfsTree::Catalog { 78 } else { 74 };
        let clump = BigEndian::read_u32(&self.mdb.raw_sector[clump_off..clump_off + 4]) as usize;
        let grow_nodes = (clump.div_ceil(node_size).max(1) as u32).max(8);
        let header_cap = ((node_size - 256) * 8) as u32;
        let per_map = (hfs_common::map_node_bitmap_bytes(node_size) * 8) as u32;
        let need_map = total_nodes + grow_nodes > header_cap + existing_map * per_map;
        let add_slots = grow_nodes + u32::from(need_map);
        let grow_blocks = btree_grow_blocks(total_nodes, add_slots, node_size, block_size);
        let mut add_slots = add_slots;
        if grow_blocks > 0 {
            let mut inline = match tree {
                HfsTree::Catalog => self.mdb.catalog_file_extents,
                HfsTree::Extents => self.mdb.extents_file_extents,
            };
            // Every extent of the file, inline first, then the overflow records.
            let mut all: Vec<HfsExtDescriptor> = inline
                .iter()
                .copied()
                .filter(|e| e.block_count > 0)
                .collect();
            let inline_blocks: u32 = all.iter().map(|e| e.block_count as u32).sum();
            if tree == HfsTree::Catalog && all.len() == 3 {
                self.ensure_extents_overflow()?;
                if let Some(x) = self.extents_overflow_data.as_ref() {
                    all.extend(collect_fork_overflow_extents(
                        x,
                        CNID_CATALOG,
                        0x00,
                        inline_blocks,
                    ));
                }
            }
            let tail = all
                .last()
                .map(|e| e.start_block as u32 + e.block_count as u32);
            match tail {
                Some(t) if self.allocate_blocks_at(t, grow_blocks)? => {
                    all.last_mut().unwrap().block_count += grow_blocks as u16;
                }
                _ => {
                    // A fresh extent doubles the file, so the inline slots and
                    // the overflow records are not spent one clump at a time.
                    let want_nodes = (total_nodes + add_slots).max(grow_nodes + 8);
                    let more = btree_grow_blocks(
                        total_nodes,
                        want_nodes - total_nodes,
                        node_size,
                        block_size,
                    )
                    .max(grow_blocks);
                    add_slots = want_nodes.max(total_nodes + add_slots) - total_nodes;
                    if tree == HfsTree::Extents && all.len() >= 3 {
                        return Err(FilesystemError::DiskFull(
                            "extents-overflow file has no free extent slot to grow into".into(),
                        ));
                    }
                    // No run that long: settle for the clump and grow again later.
                    let (start, more) = match self.allocate_blocks(more) {
                        Ok(start) => (start, more),
                        Err(_) => {
                            add_slots = grow_nodes + u32::from(need_map);
                            (self.allocate_blocks(grow_blocks)?, grow_blocks)
                        }
                    };
                    all.push(HfsExtDescriptor {
                        start_block: start as u16,
                        block_count: more as u16,
                    });
                }
            }
            inline = [HfsExtDescriptor {
                start_block: 0,
                block_count: 0,
            }; 3];
            for (i, e) in all.iter().take(3).enumerate() {
                inline[i] = *e;
            }
            match tree {
                HfsTree::Catalog => {
                    self.mdb.catalog_file_extents = inline;
                    if all.len() > 3 {
                        // Re-key the overflow records from the full list.
                        let data = self.extents_overflow_data.as_mut().expect("loaded above");
                        remove_fork_overflow_records(data, CNID_CATALOG, 0x00)?;
                        self.insert_fork_overflow(CNID_CATALOG, 0x00, &all)?;
                        self.write_extents_overflow_back()?;
                    }
                }
                HfsTree::Extents => self.mdb.extents_file_extents = inline,
            }
        }
        let buf = self.tree_buf(tree)?;
        buf.resize(buf.len() + add_slots as usize * node_size, 0);
        if need_map {
            // The new map node takes the first new slot; its own bit is still
            // inside the bitmap the tree has, and the header or last map node links to it.
            let map_idx = total_nodes;
            let tail = btree_map_chain_tail(buf, node_size);
            hfs_common::init_map_node(buf, node_size, map_idx, tail, 0);
            let linker = tail as usize * node_size;
            BigEndian::write_u32(&mut buf[linker..linker + 4], map_idx);
            hfs_common::btree_bitmap_set(buf, node_size, map_idx);
        }
        let mut h = BTreeHeader::read(buf);
        h.total_nodes += add_slots;
        h.free_nodes += add_slots - u32::from(need_map);
        h.write(buf);
        let added = add_slots * node_size as u32;
        match tree {
            HfsTree::Catalog => self.mdb.catalog_file_size += added,
            HfsTree::Extents => self.mdb.extents_file_size += added,
        }
        Ok(())
    }

    /// The in-memory bytes of a B-tree file; the extents tree must be loaded.
    fn tree_buf(&mut self, tree: HfsTree) -> Result<&mut Vec<u8>, FilesystemError> {
        match tree {
            HfsTree::Catalog => Ok(&mut self.catalog_data),
            HfsTree::Extents => self.extents_overflow_data.as_mut().ok_or_else(|| {
                FilesystemError::Unsupported("volume has no extents-overflow B-tree".into())
            }),
        }
    }

    /// Take `count` blocks starting exactly at `start` when every one is free.
    fn allocate_blocks_at(&mut self, start: u32, count: u32) -> Result<bool, FilesystemError> {
        self.ensure_bitmap()?;
        let total = self.mdb.total_blocks as u32;
        let bitmap = self.bitmap.as_mut().unwrap();
        if start + count > total || (start..start + count).any(|b| bitmap_test_bit_be(bitmap, b)) {
            return Ok(false);
        }
        for b in start..start + count {
            bitmap_set_bit_be(bitmap, b);
        }
        self.mdb.free_blocks = self.mdb.free_blocks.saturating_sub(count as u16);
        Ok(true)
    }

    /// Remove a catalog record from a leaf node.
    fn remove_catalog_record(
        &mut self,
        node_idx: u32,
        rec_idx: usize,
    ) -> Result<(), FilesystemError> {
        let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as usize;
        if node_size == 0 {
            return Ok(());
        }
        let offset = node_idx as usize * node_size;
        if offset + node_size > self.catalog_data.len() {
            return Ok(());
        }

        let num_before = {
            let node = &self.catalog_data[offset..offset + node_size];
            BigEndian::read_u16(&node[10..12]) as usize
        };

        {
            let node = &mut self.catalog_data[offset..offset + node_size];
            btree_remove_record(node, node_size, rec_idx);
        }

        // If node is now empty, free it and fix links
        let node = &self.catalog_data[offset..offset + node_size];
        let num_after = BigEndian::read_u16(&node[10..12]) as usize;
        if num_after == 0 && num_before > 0 {
            let prev = BigEndian::read_u32(&self.catalog_data[offset + 4..offset + 8]);
            let next = BigEndian::read_u32(&self.catalog_data[offset..offset + 4]);

            if prev != 0 {
                let prev_off = prev as usize * node_size;
                if prev_off + 4 <= self.catalog_data.len() {
                    BigEndian::write_u32(&mut self.catalog_data[prev_off..prev_off + 4], next);
                }
            }
            if next != 0 {
                let next_off = next as usize * node_size;
                if next_off + 8 <= self.catalog_data.len() {
                    BigEndian::write_u32(&mut self.catalog_data[next_off + 4..next_off + 8], prev);
                }
            }

            let mut h = BTreeHeader::read(&self.catalog_data);
            if h.first_leaf_node == node_idx {
                h.first_leaf_node = next;
            }
            if h.last_leaf_node == node_idx {
                h.last_leaf_node = prev;
            }
            btree_free_node(&mut self.catalog_data, node_size, node_idx);
            h.free_nodes += 1;
            // The last leaf went with it: an empty tree has no root.
            if h.root_node == node_idx {
                h.root_node = 0;
                h.depth = 0;
            }
            h.write(&mut self.catalog_data);

            // Rebuild index nodes to clean up stale separator keys
            let header = BTreeHeader::read(&self.catalog_data);
            if header.depth > 1 {
                let mut dummy_report = disk_core::fsck::RepairReport {
                    fixes_applied: Vec::new(),
                    fixes_failed: Vec::new(),
                    unrepairable_count: 0,
                };
                crate::hfs_fsck::rebuild_index_nodes(
                    &mut self.catalog_data,
                    node_size,
                    &mut dummy_report,
                );
            }
        } else if rec_idx == 0 && num_after > 0 {
            // The leaf's first key changed: Disk First Aid wants the separators
            // above it to say so exactly (E_IKey).
            btree_refresh_index_keys(
                &mut self.catalog_data,
                node_size,
                node_idx,
                &BTreeKeyFormat::CLASSIC_CATALOG,
                &Self::catalog_compare,
            )?;
        }

        // Update leaf_records count
        let mut h = BTreeHeader::read(&self.catalog_data);
        h.leaf_records = h.leaf_records.saturating_sub(1);
        h.write(&mut self.catalog_data);
        Ok(())
    }

    /// Capture a snapshot of all mutable in-memory state for rollback.
    ///
    /// Returns `None` in bulk mode (see [`HfsFilesystem::bulk_mode`]): the
    /// clone of the whole catalog is the dominant per-operation cost during a
    /// large import, and the caller guarantees batch-level atomicity there.
    /// `restore_snapshot(None)` is then a no-op, so the existing
    /// `let snap = self.snapshot(); ... restore_snapshot(snap)` call sites need
    /// no changes.
    fn snapshot(&self) -> Option<(Vec<u8>, Option<Vec<u8>>, HfsMasterDirectoryBlock)> {
        if self.bulk_mode {
            return None;
        }
        Some((
            self.catalog_data.clone(),
            self.bitmap.clone(),
            self.mdb.clone(),
        ))
    }

    /// Restore in-memory state from a previously captured snapshot. A `None`
    /// snapshot (bulk mode) restores nothing — the caller owns rollback.
    fn restore_snapshot(
        &mut self,
        snap: Option<(Vec<u8>, Option<Vec<u8>>, HfsMasterDirectoryBlock)>,
    ) {
        let Some((catalog_data, bitmap, mdb)) = snap else {
            return;
        };
        self.catalog_data = catalog_data;
        self.bitmap = bitmap;
        self.mdb = mdb;
    }

    pub(crate) fn mdb(&self) -> &HfsMasterDirectoryBlock {
        &self.mdb
    }

    /// Lightweight read-only summary of the volume. Public so GUI callers
    /// outside the library crate can populate display fields without going
    /// through the full `Filesystem` browse API.
    pub fn volume_summary(&self) -> HfsVolumeSummary {
        let used_blocks = self.mdb.total_blocks.saturating_sub(self.mdb.free_blocks) as u64;
        HfsVolumeSummary {
            volume_name: self.mdb.volume_name.clone(),
            block_size: self.mdb.block_size,
            total_blocks: self.mdb.total_blocks,
            free_blocks: self.mdb.free_blocks,
            used_bytes: used_blocks * self.mdb.block_size as u64,
            file_count: self.mdb.file_count,
            folder_count: self.mdb.folder_count,
            catalog_file_size: self.mdb.catalog_file_size,
            extents_file_size: self.mdb.extents_file_size,
        }
    }

    pub(crate) fn catalog_data(&self) -> &[u8] {
        &self.catalog_data
    }

    #[allow(dead_code)]
    pub(crate) fn partition_offset(&self) -> u64 {
        self.partition_offset
    }

    /// Locate a file's data fork on disk by its catalog CNID. Returns the
    /// byte offset of the first extent **within the containing image file**
    /// (i.e. `partition_offset + first_alloc_block*512 + start_block*block_size`),
    /// the data-fork length, and a flag set when the fork is split across
    /// more than one extent — in which case callers that need every byte
    /// must walk all extents themselves; the offset returned points at the
    /// first one only.
    ///
    /// Resource forks are ignored. Returns `None` if the CNID is not a
    /// file in the catalog, or the file has zero data-fork extents
    /// allocated (e.g. an empty file).
    pub fn locate_file_by_cnid(&self, cnid: u32) -> Option<HfsFileLocation> {
        let (data_size, data_extents, _rsrc_size, _rsrc_extents) = self.find_file_by_id(cnid)?;
        let first = data_extents.first().copied()?;
        if first.block_count == 0 {
            return None;
        }
        let fragmented = data_extents.iter().skip(1).any(|e| e.block_count != 0);
        // alloc_block_offset returns the byte offset of `block` *within the
        // partition*; we add partition_offset so the caller (and any script
        // grepping the image file) gets an absolute file-byte offset.
        let offset_in_image =
            self.partition_offset + self.alloc_block_offset(first.start_block as u32);
        Some(HfsFileLocation {
            offset_in_image,
            length: data_size as u64,
            fragmented,
        })
    }

    /// Read the 1024-byte boot block region (sectors 0..1 of the partition).
    pub(crate) fn read_boot_blocks(&mut self) -> Result<[u8; 1024], FilesystemError> {
        self.reader.seek(SeekFrom::Start(self.partition_offset))?;
        let mut buf = [0u8; 1024];
        self.reader.read_exact(&mut buf)?;
        Ok(buf)
    }

    /// Read a fork's content via the given 3-extent descriptor, up to `size` bytes.
    /// This does not consult the extents-overflow B-tree.
    #[allow(dead_code)]
    pub(crate) fn read_fork(
        &mut self,
        extents: &[HfsExtDescriptor; 3],
        size: u64,
    ) -> Result<Vec<u8>, FilesystemError> {
        read_fork_data(
            &mut self.reader,
            self.partition_offset,
            &self.mdb,
            extents,
            size,
        )
    }

    /// Lazily load the extents-overflow B-tree fork into memory. No-op if
    /// already loaded or if the volume has no extents-overflow file.
    fn ensure_extents_overflow(&mut self) -> Result<(), FilesystemError> {
        if self.extents_overflow_data.is_some() {
            return Ok(());
        }
        if self.mdb.extents_file_size == 0 {
            return Ok(());
        }
        let data = read_fork_data(
            &mut self.reader,
            self.partition_offset,
            &self.mdb,
            &self.mdb.extents_file_extents,
            self.mdb.extents_file_size as u64,
        )?;
        self.extents_overflow_data = Some(data);
        Ok(())
    }

    /// Read a fork's content combining the 3 inline extents with any
    /// overflow records in the extents-overflow B-tree. Used for files
    /// fragmented past the inline limit.
    ///
    /// `fork_type`: `0x00` for the data fork, `0xFF` for the resource fork.
    /// Stream fork data (inline + extents-overflow) to a writer.
    fn write_fork_with_overflow_to(
        &mut self,
        file_id: u32,
        fork_type: u8,
        inline: &[HfsExtDescriptor; 3],
        size: u64,
        writer: &mut dyn std::io::Write,
    ) -> Result<u64, FilesystemError> {
        let mut written = write_fork_data_to(
            &mut self.reader,
            self.partition_offset,
            &self.mdb,
            inline,
            writer,
            size,
        )?;
        if written >= size {
            return Ok(written);
        }
        self.ensure_extents_overflow()?;
        let Some(ext_data) = self.extents_overflow_data.as_ref() else {
            return Err(FilesystemError::InvalidData(format!(
                "file {file_id} fork {fork_type:#x}: {size} bytes requested but only {written} \
                 bytes in inline extents and no extents-overflow B-tree present",
            )));
        };
        let inline_blocks: u32 = inline.iter().map(|e| e.block_count as u32).sum();
        let overflow = collect_fork_overflow_extents(ext_data, file_id, fork_type, inline_blocks);
        let block_size = self.mdb.block_size as u64;
        let first_alloc_offset = self.partition_offset + self.mdb.first_alloc_block as u64 * 512;
        let mut buf = vec![0u8; 64 * 1024];
        for ext in overflow {
            if written >= size {
                break;
            }
            if ext.block_count == 0 {
                continue;
            }
            let offset = first_alloc_offset + ext.start_block as u64 * block_size;
            let extent_len = ext.block_count as u64 * block_size;
            let to_emit = extent_len.min(size - written);
            self.reader.seek(SeekFrom::Start(offset))?;
            let mut left = to_emit;
            while left > 0 {
                let n = (buf.len() as u64).min(left) as usize;
                self.reader.read_exact(&mut buf[..n])?;
                writer.write_all(&buf[..n])?;
                left -= n as u64;
            }
            written += to_emit;
        }
        if written < size {
            return Err(FilesystemError::InvalidData(format!(
                "file {file_id} fork {fork_type:#x}: extents (inline + overflow) cover \
                 {written} of {size} bytes",
            )));
        }
        Ok(written)
    }

    fn read_fork_with_overflow(
        &mut self,
        file_id: u32,
        fork_type: u8,
        inline: &[HfsExtDescriptor; 3],
        size: u64,
    ) -> Result<Vec<u8>, FilesystemError> {
        let mut data = read_fork_data(
            &mut self.reader,
            self.partition_offset,
            &self.mdb,
            inline,
            size,
        )?;
        if (data.len() as u64) >= size {
            return Ok(data);
        }

        self.ensure_extents_overflow()?;
        let Some(ext_data) = self.extents_overflow_data.as_ref() else {
            return Err(FilesystemError::InvalidData(format!(
                "file {file_id} fork {fork_type:#x}: {size} bytes requested but only {} bytes \
                 in inline extents and no extents-overflow B-tree present",
                data.len()
            )));
        };

        let inline_blocks: u32 = inline.iter().map(|e| e.block_count as u32).sum();
        let overflow = collect_fork_overflow_extents(ext_data, file_id, fork_type, inline_blocks);

        let block_size = self.mdb.block_size as u64;
        let first_alloc_offset = self.partition_offset + self.mdb.first_alloc_block as u64 * 512;

        for ext in overflow {
            if data.len() as u64 >= size {
                break;
            }
            if ext.block_count == 0 {
                continue;
            }
            let offset = first_alloc_offset + ext.start_block as u64 * block_size;
            let extent_len = ext.block_count as u64 * block_size;
            let to_read = extent_len.min(size - data.len() as u64) as usize;
            self.reader.seek(SeekFrom::Start(offset))?;
            let mut buf = vec![0u8; to_read];
            self.reader.read_exact(&mut buf)?;
            data.extend_from_slice(&buf);
        }

        if (data.len() as u64) < size {
            return Err(FilesystemError::InvalidData(format!(
                "file {file_id} fork {fork_type:#x}: extents (inline + overflow) cover \
                 {} of {size} bytes",
                data.len()
            )));
        }
        Ok(data)
    }

    /// Locate the catalog record-data offset for a file or directory CNID.
    ///
    /// Directories always have a thread record (HFS spec mandates it), so we
    /// look them up via the thread -> key path. File thread records are
    /// optional in classic HFS — Finder, CiderPress2, and Inside Macintosh:
    /// Files all describe them as optional, and our `create_file` no longer
    /// emits them. So if the thread lookup fails, fall back to a leaf scan
    /// for a file record whose `filFlNum` (CNID) matches.
    ///
    /// The returned offset points at the record type byte (offset 0 of the
    /// record data).
    fn locate_record_data(&self, cnid: u32) -> Result<usize, FilesystemError> {
        if let Some((_, _, t_offset)) = self.find_catalog_record_by_cnid(cnid) {
            let key_len = self.catalog_data[t_offset] as usize;
            let mut rec_data_start = t_offset + 1 + key_len;
            if !rec_data_start.is_multiple_of(2) {
                rec_data_start += 1;
            }
            let thread_parent =
                BigEndian::read_u32(&self.catalog_data[rec_data_start + 10..rec_data_start + 14]);
            let thread_name_len = self.catalog_data[rec_data_start + 14] as usize;
            let thread_name = self.catalog_data
                [rec_data_start + 15..rec_data_start + 15 + thread_name_len]
                .to_vec();

            if let Some((_, _, f_offset)) =
                self.find_catalog_record_by_name(thread_parent, &thread_name)
            {
                let fkey_len = self.catalog_data[f_offset] as usize;
                let mut frec_start = f_offset + 1 + fkey_len;
                if !frec_start.is_multiple_of(2) {
                    frec_start += 1;
                }
                return Ok(frec_start);
            }
        }

        if let Some((_, _, frec_start)) = self.find_file_record_offset_by_cnid(cnid) {
            return Ok(frec_start);
        }

        Err(FilesystemError::NotFound(format!(
            "catalog record for CNID {cnid} not found"
        )))
    }

    /// Scan catalog leaves for a file record whose `filFlNum` equals `cnid`.
    /// Returns `(node_idx, rec_idx, record_data_offset)` — the third element
    /// has the same meaning as the third element of
    /// `find_catalog_record_by_name`, except it points at the record DATA
    /// (offset 0 = type byte) rather than the key.
    ///
    /// Used as a fallback for file CNID lookup since classic HFS file thread
    /// records are optional (and our `create_file` no longer emits them).
    fn find_file_record_offset_by_cnid(&self, cnid: u32) -> Option<(u32, usize, usize)> {
        if self.catalog_data.len() < 512 {
            return None;
        }
        let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as usize;
        let first_leaf = BigEndian::read_u32(&self.catalog_data[24..28]);

        hfs_common::walk_leaf_records(
            &self.catalog_data,
            first_leaf,
            node_size,
            |node_idx, rec_idx, abs_off, rec| {
                if rec.len() < 7 {
                    return None;
                }
                let key_len = rec[0] as usize;
                if key_len < 6 || 1 + key_len > rec.len() {
                    return None;
                }
                let mut data_rel = 1 + key_len;
                if !data_rel.is_multiple_of(2) {
                    data_rel += 1;
                }
                if data_rel + 24 > rec.len() {
                    return None;
                }
                if rec[data_rel] as i8 != CATALOG_FILE {
                    return None;
                }
                // filFlNum at offset 20 of the file record data
                let rec_cnid = BigEndian::read_u32(&rec[data_rel + 20..data_rel + 24]);
                if rec_cnid == cnid {
                    Some((node_idx, rec_idx, abs_off + data_rel))
                } else {
                    None
                }
            },
        )
    }

    /// Write the full 16-byte `FInfo` + 16-byte `FXInfo` Finder metadata
    /// blocks on a file catalog record. `entry` must be a file.
    pub fn set_finder_info(
        &mut self,
        entry: &FileEntry,
        finfo: [u8; 16],
        fxinfo: [u8; 16],
    ) -> Result<(), FilesystemError> {
        if entry.is_directory() {
            return Err(FilesystemError::InvalidData(
                "set_finder_info: entry is a directory".into(),
            ));
        }
        let snap = self.snapshot();
        let result = (|| {
            let rec = self.locate_record_data(entry.location as u32)?;
            if self.catalog_data[rec] as i8 != CATALOG_FILE {
                return Err(FilesystemError::InvalidData("not a file record".into()));
            }
            self.catalog_data[rec + 4..rec + 20].copy_from_slice(&finfo);
            self.catalog_data[rec + 56..rec + 72].copy_from_slice(&fxinfo);
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Write the full 16-byte `DInfo` + 16-byte `DXInfo` Finder metadata
    /// blocks on a directory catalog record. `entry` must be a directory.
    pub fn set_directory_finder_info(
        &mut self,
        entry: &FileEntry,
        dinfo: [u8; 16],
        dxinfo: [u8; 16],
    ) -> Result<(), FilesystemError> {
        if !entry.is_directory() {
            return Err(FilesystemError::InvalidData(
                "set_directory_finder_info: entry is not a directory".into(),
            ));
        }
        let snap = self.snapshot();
        let result = (|| {
            let rec = self.locate_record_data(entry.location as u32)?;
            if self.catalog_data[rec] as i8 != CATALOG_DIR {
                return Err(FilesystemError::InvalidData(
                    "not a directory record".into(),
                ));
            }
            self.catalog_data[rec + 22..rec + 38].copy_from_slice(&dinfo);
            self.catalog_data[rec + 38..rec + 54].copy_from_slice(&dxinfo);
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Set create/modify/backup dates (HFS epoch seconds) on a file or
    /// directory catalog record. File record offsets: crDate@44, mdDate@48,
    /// bkDate@52. Dir record offsets: crDate@10, mdDate@14, bkDate@18.
    pub fn set_dates(
        &mut self,
        entry: &FileEntry,
        create: u32,
        modify: u32,
        backup: u32,
    ) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let result = (|| {
            let rec = self.locate_record_data(entry.location as u32)?;
            let record_type = self.catalog_data[rec] as i8;
            let (cr_off, md_off, bk_off) = match record_type {
                CATALOG_FILE => (44, 48, 52),
                CATALOG_DIR => (10, 14, 18),
                other => {
                    return Err(FilesystemError::InvalidData(format!(
                        "unexpected catalog record type: {other}"
                    )))
                }
            };
            BigEndian::write_u32(
                &mut self.catalog_data[rec + cr_off..rec + cr_off + 4],
                create,
            );
            BigEndian::write_u32(
                &mut self.catalog_data[rec + md_off..rec + md_off + 4],
                modify,
            );
            BigEndian::write_u32(
                &mut self.catalog_data[rec + bk_off..rec + bk_off + 4],
                backup,
            );
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Set or clear the "locked" bit (0x01) in the catalog file record's
    /// flags byte at offset 2. Only meaningful for files.
    pub fn set_file_locked(
        &mut self,
        entry: &FileEntry,
        locked: bool,
    ) -> Result<(), FilesystemError> {
        if entry.is_directory() {
            return Err(FilesystemError::InvalidData(
                "set_file_locked: entry is a directory".into(),
            ));
        }
        let snap = self.snapshot();
        let result = (|| {
            let rec = self.locate_record_data(entry.location as u32)?;
            if self.catalog_data[rec] as i8 != CATALOG_FILE {
                return Err(FilesystemError::InvalidData("not a file record".into()));
            }
            let flags = self.catalog_data[rec + 2];
            self.catalog_data[rec + 2] = if locked { flags | 0x01 } else { flags & !0x01 };
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Set volume-level create / modify / backup dates. The modify date
    /// overrides the automatic `hfs_now()` stamp that `sync_metadata`
    /// normally applies.
    pub fn set_volume_dates(&mut self, create: u32, modify: u32, backup: u32) {
        self.pending_volume_dates = Some((create, modify, backup));
        self.mdb.create_date = create;
        self.mdb.modify_date = modify;
        BigEndian::write_u32(&mut self.mdb.raw_sector[2..6], create);
        BigEndian::write_u32(&mut self.mdb.raw_sector[6..10], modify);
        BigEndian::write_u32(&mut self.mdb.raw_sector[64..68], backup);
    }

    /// Stage a 1024-byte boot-block region (sectors 0–1) for the volume.
    /// The bytes are written verbatim at `sync_metadata` time.
    pub fn set_boot_blocks(&mut self, blocks: &[u8; 1024]) {
        self.pending_boot_blocks = Some(Box::new(*blocks));
    }

    /// Write the full 32-byte `drFndrInfo` (8 × u32) on the MDB. Useful when
    /// blessed-folder fingerprinting extends beyond `drFndrInfo[0]` (e.g.
    /// `drFndrInfo[3]` for the OS folder).
    pub fn set_volume_finder_info(&mut self, finder_info: &[u8; 32]) {
        for i in 0..8 {
            self.mdb.finder_info[i] = BigEndian::read_u32(&finder_info[i * 4..(i + 1) * 4]);
        }
    }

    /// Rename the volume. Updates the MDB `drVN`, the root directory's
    /// catalog key (which carries the volume name — Mac OS looks up the
    /// root by `(parent=1, drVN)` at mount time), and the root thread
    /// record's `thdCName`. Caller must `sync_metadata` to flush. New
    /// name must be 1..=27 Mac Roman bytes.
    pub fn set_volume_name(&mut self, new_name: &str) -> Result<(), FilesystemError>
    where
        R: Write,
    {
        let new_name_raw = utf8_to_mac_roman(new_name)?;
        if new_name_raw.is_empty() {
            return Err(FilesystemError::InvalidData(
                "HFS volume name must not be empty (Mac OS rejects unnamed volumes with -127)"
                    .into(),
            ));
        }
        if new_name_raw.len() > 27 {
            return Err(FilesystemError::InvalidData(format!(
                "HFS volume name '{new_name}' exceeds 27 Mac Roman bytes"
            )));
        }

        let snap = self.snapshot();
        let result = (|| -> Result<(), FilesystemError> {
            let old_name_raw = self.mdb.volume_name_raw.clone();
            if new_name_raw == old_name_raw {
                return Ok(());
            }

            // Locate the root dir record by its current key (parent=1, drVN).
            let (node_idx, rec_idx, key_abs) = self
                .find_catalog_record_by_name(1, &old_name_raw)
                .ok_or_else(|| {
                FilesystemError::NotFound("root directory record not found in catalog".into())
            })?;

            // Extract the existing data portion of the record so we can
            // re-emit it under a new key.
            let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as usize;
            let node_off = node_idx as usize * node_size;
            let node = &self.catalog_data[node_off..node_off + node_size];
            let (rec_start, rec_end) = hfs_common::btree_record_range(node, node_size, rec_idx);
            // key_abs == node_off + rec_start
            debug_assert_eq!(key_abs, node_off + rec_start);
            let key_len = node[rec_start] as usize;
            let mut data_rel = 1 + key_len;
            if !data_rel.is_multiple_of(2) {
                data_rel += 1;
            }
            let data_bytes = node[rec_start + data_rel..rec_end].to_vec();

            // Build the new record: new key + (pad to even) + data + (pad).
            let new_key = Self::build_catalog_key(1, &new_name_raw);
            let mut new_record = new_key;
            if !new_record.len().is_multiple_of(2) {
                new_record.push(0);
            }
            new_record.extend_from_slice(&data_bytes);
            if !new_record.len().is_multiple_of(2) {
                new_record.push(0);
            }

            self.remove_catalog_record(node_idx, rec_idx)?;
            self.insert_catalog_record(&new_record)?;

            // Rewrite the root thread record's `thdCName` (Str31 at +14).
            // Key stays (parent=2, name="") so the record's footprint is
            // unchanged — safe to rewrite in place.
            if let Some((_n, _r, t_key_abs)) = self.find_catalog_record_by_cnid(2) {
                let t_key_len = self.catalog_data[t_key_abs] as usize;
                let mut t_data_off = t_key_abs + 1 + t_key_len;
                if !t_data_off.is_multiple_of(2) {
                    t_data_off += 1;
                }
                if t_data_off + 15 + 27 <= self.catalog_data.len() {
                    self.catalog_data[t_data_off + 14] = new_name_raw.len() as u8;
                    for i in 0..27 {
                        self.catalog_data[t_data_off + 15 + i] = 0;
                    }
                    self.catalog_data[t_data_off + 15..t_data_off + 15 + new_name_raw.len()]
                        .copy_from_slice(&new_name_raw);
                }
            }

            // Update the MDB. `drVN` lives at offset 36 (length byte) +
            // 37..64 (up to 27 name bytes). `serialize_to_sector` reads
            // these from `raw_sector` verbatim, so the change propagates
            // on the next `sync_metadata`.
            self.mdb.volume_name = mac_roman_to_utf8(&new_name_raw);
            self.mdb.volume_name_raw = new_name_raw.clone();
            self.mdb.raw_sector[36] = new_name_raw.len() as u8;
            for i in 0..27 {
                self.mdb.raw_sector[37 + i] = 0;
            }
            self.mdb.raw_sector[37..37 + new_name_raw.len()].copy_from_slice(&new_name_raw);

            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }
}

/// Write helpers — require Read + Write + Seek.
impl<R: Read + Write + Seek> HfsFilesystem<R> {
    /// Write data to an allocation block.
    fn write_block(&mut self, block: u32, data: &[u8]) -> Result<(), FilesystemError> {
        let offset = self.partition_offset + self.alloc_block_offset(block);
        self.reader.seek(SeekFrom::Start(offset))?;
        self.reader.write_all(data)?;
        Ok(())
    }

    /// Write MDB to the primary location (offset+1024).
    /// The backup (alternate) MDB is intentionally not updated — its location
    /// depends on the exact partition size which may not be known. The primary
    /// MDB is authoritative; Mac OS only falls back to the alternate if the
    /// primary is corrupt, and the stale alternate remains structurally valid.
    fn write_mdb(&mut self) -> Result<(), FilesystemError> {
        // Stamp drAtrb with the "volume successfully unmounted" bit (0x0100).
        // Without it, classic Mac OS treats the volume as dirty and refuses
        // to put it on the desktop until it's scavenged — for a freshly
        // built clone that's never been mounted, that produces a disk LIDO
        // sees over SCSI but the Finder ignores. This is sync-time because
        // by the time we get here every catalog record + bitmap bit + alt
        // MDB has been flushed to the writer.
        BigEndian::write_u16(&mut self.mdb.raw_sector[10..12], 0x0100);

        // Count the root directory's direct children. drNmFls (offset 12)
        // and drNmRtDirs (offset 82) hold the number of files / directories
        // immediately under CNID 2; the Finder uses these to decide
        // whether the volume's root listing is consistent. Real-world
        // disks always populate them, so missing values look suspect.
        let (root_files, root_dirs) = match self.list_children(2) {
            Ok(children) => {
                let mut f = 0u16;
                let mut d = 0u16;
                for c in &children {
                    match c {
                        CatalogRecord::File { .. } => f = f.saturating_add(1),
                        CatalogRecord::Directory { .. } => d = d.saturating_add(1),
                    }
                }
                (f, d)
            }
            Err(_) => (0, 0),
        };
        BigEndian::write_u16(&mut self.mdb.raw_sector[12..14], root_files);
        BigEndian::write_u16(&mut self.mdb.raw_sector[82..84], root_dirs);

        let mdb_bytes = self.mdb.serialize_to_sector();
        self.reader
            .seek(SeekFrom::Start(self.partition_offset + 1024))?;
        self.reader.write_all(&mdb_bytes)?;
        // Mirror to the alternate MDB at the sector right after the last
        // allocation block. Mac OS rejects volumes whose primary and alt
        // MDBs disagree, so this must stay in sync with the primary write.
        if let Some(alt_offset) = self.alt_mdb_offset() {
            self.reader.seek(SeekFrom::Start(alt_offset))?;
            self.reader.write_all(&mdb_bytes)?;
        }
        Ok(())
    }

    /// Write catalog B-tree data back to disk through the catalog_file extents.
    fn write_catalog(&mut self) -> Result<(), FilesystemError> {
        write_hfs_fork_data(
            &mut self.reader,
            self.partition_offset,
            &self.mdb,
            &self.mdb.catalog_file_extents,
            &self.catalog_data,
        )?;
        // The part past the inline extents lives where the CNID 4 overflow
        // records say (F-016).
        let inline_blocks: u32 = self
            .mdb
            .catalog_file_extents
            .iter()
            .map(|e| e.block_count as u32)
            .sum();
        let inline_bytes = inline_blocks as usize * self.mdb.block_size as usize;
        if self.catalog_data.len() <= inline_bytes {
            return Ok(());
        }
        self.ensure_extents_overflow()?;
        let Some(ext_data) = self.extents_overflow_data.as_ref() else {
            return Err(FilesystemError::InvalidData(
                "catalog file runs past its inline extents and the volume has no extents-overflow tree".into(),
            ));
        };
        let overflow = collect_fork_overflow_extents(ext_data, CNID_CATALOG, 0x00, inline_blocks);
        let first_alloc = self.partition_offset + self.mdb.first_alloc_block as u64 * 512;
        let mut written = inline_bytes;
        for ext in overflow {
            if written >= self.catalog_data.len() {
                break;
            }
            let off = first_alloc + ext.start_block as u64 * self.mdb.block_size as u64;
            let len = (ext.block_count as usize * self.mdb.block_size as usize)
                .min(self.catalog_data.len() - written);
            self.reader.seek(SeekFrom::Start(off))?;
            self.reader
                .write_all(&self.catalog_data[written..written + len])?;
            written += len;
        }
        if written < self.catalog_data.len() {
            return Err(FilesystemError::InvalidData(format!(
                "catalog file: extents cover {written} of {} bytes",
                self.catalog_data.len()
            )));
        }
        Ok(())
    }

    /// Write the volume bitmap back to disk.
    fn write_volume_bitmap(&mut self) -> Result<(), FilesystemError> {
        if let Some(ref bm) = self.bitmap {
            let bitmap_offset = self.partition_offset + self.mdb.volume_bitmap_block as u64 * 512;
            self.reader.seek(SeekFrom::Start(bitmap_offset))?;
            self.reader.write_all(bm)?;
        }
        Ok(())
    }

    /// Allocate `count` contiguous blocks from the volume bitmap and return the
    /// start block; `allocate_extents` is the fallback when no run is long enough.
    fn allocate_blocks(&mut self, count: u32) -> Result<u32, FilesystemError> {
        self.ensure_bitmap()?;
        let bitmap = self.bitmap.as_mut().unwrap();
        let start = bitmap_find_clear_run_be(bitmap, self.mdb.total_blocks as u32, count)
            .ok_or_else(|| {
                FilesystemError::DiskFull(format!("cannot find {} contiguous free blocks", count))
            })?;
        for i in 0..count {
            bitmap_set_bit_be(bitmap, start + i);
        }
        // A stale-low drFreeBks (dirty unmount) must not wrap to ~65535.
        self.mdb.free_blocks = self
            .mdb
            .free_blocks
            .saturating_sub(count.min(u16::MAX as u32) as u16);
        // Advance drAllocPtr (MDB offset 16) past the run so subsequent
        // allocation searches start where the last one ended. hformat
        // maintains this; without it the field stays at 0 and the
        // allocator hint never moves, which diffs against reference
        // hformat-built volumes.
        let next = (start + count) % self.mdb.total_blocks.max(1) as u32;
        BigEndian::write_u16(&mut self.mdb.raw_sector[16..18], next as u16);
        Ok(start)
    }

    /// Allocate `count` blocks as a list of runs: one contiguous run when the
    /// volume has it, else first fit over the free runs in address order (F-011).
    fn allocate_extents(&mut self, count: u32) -> Result<Vec<HfsExtDescriptor>, FilesystemError> {
        if count == 0 {
            return Ok(Vec::new());
        }
        if count > u16::MAX as u32 {
            return Err(FilesystemError::InvalidData(
                "file too large for classic HFS (>65535 blocks)".into(),
            ));
        }
        if let Ok(start) = self.allocate_blocks(count) {
            return Ok(vec![HfsExtDescriptor {
                start_block: start as u16,
                block_count: count as u16,
            }]);
        }
        self.ensure_bitmap()?;
        let total_blocks = self.mdb.total_blocks as u32;
        let free = self.mdb.free_blocks as u32;
        if free < count {
            return Err(FilesystemError::DiskFull(format!(
                "{free} blocks free, {count} requested"
            )));
        }
        let bitmap = self.bitmap.as_mut().unwrap();
        let mut extents = Vec::new();
        let mut remaining = count;
        for (start, len) in bitmap_collect_clear_runs_be(bitmap, total_blocks) {
            if remaining == 0 {
                break;
            }
            let take = len.min(remaining);
            extents.push(HfsExtDescriptor {
                start_block: start as u16,
                block_count: take as u16,
            });
            remaining -= take;
        }
        if remaining > 0 {
            return Err(FilesystemError::DiskFull(format!(
                "needed {count} blocks, short by {remaining} after gathering every free run"
            )));
        }
        for ext in &extents {
            for i in 0..ext.block_count as u32 {
                bitmap_set_bit_be(bitmap, ext.start_block as u32 + i);
            }
        }
        self.mdb.free_blocks = self.mdb.free_blocks.saturating_sub(count as u16);
        let last = extents.last().unwrap();
        let next = (last.start_block as u32 + last.block_count as u32) % total_blocks.max(1);
        BigEndian::write_u16(&mut self.mdb.raw_sector[16..18], next as u16);
        Ok(extents)
    }

    /// Free `count` blocks starting at `start`.
    fn free_blocks(&mut self, start: u32, count: u32) {
        self.ensure_bitmap().ok();
        if let Some(ref mut bitmap) = self.bitmap {
            for i in 0..count {
                bitmap_clear_bit_be(bitmap, start + i);
            }
        }
        self.mdb.free_blocks += count as u16;
    }

    /// Free all blocks referenced by an extent array.
    fn free_extent_blocks(&mut self, extents: &[HfsExtDescriptor; 3]) {
        for ext in extents {
            if ext.block_count == 0 {
                break;
            }
            self.free_blocks(ext.start_block as u32, ext.block_count as u32);
        }
    }

    /// Free a fork's extents-overflow blocks and drop its records; true if any.
    fn free_fork_overflow(&mut self, file_id: u32, fork_type: u8) -> Result<bool, FilesystemError> {
        self.ensure_extents_overflow()?;
        let Some(data) = self.extents_overflow_data.as_ref() else {
            return Ok(false);
        };
        let extents = collect_fork_overflow_extents(data, file_id, fork_type, 0);
        for ext in &extents {
            self.free_blocks(ext.start_block as u32, ext.block_count as u32);
        }
        let data = self.extents_overflow_data.as_mut().expect("loaded above");
        Ok(remove_fork_overflow_records(data, file_id, fork_type)? > 0)
    }

    /// Write the in-memory extents-overflow B-tree back to disk.
    fn write_extents_overflow_back(&mut self) -> Result<(), FilesystemError> {
        if let Some(data) = self.extents_overflow_data.as_ref() {
            if self.mdb.extents_file_size > 0 {
                write_extents_overflow_data(
                    &mut self.reader,
                    self.partition_offset,
                    &self.mdb,
                    data,
                )?;
            }
        }
        Ok(())
    }

    /// Write file data to freshly allocated blocks; returns the fork's extents
    /// in fork order (the first three go inline, the rest into the overflow tree).
    fn write_data_to_blocks(
        &mut self,
        data: &mut dyn std::io::Read,
        data_len: u64,
    ) -> Result<Vec<HfsExtDescriptor>, FilesystemError> {
        if data_len == 0 {
            return Ok(Vec::new());
        }
        let block_size = self.mdb.block_size as u64;
        let blocks_needed = data_len.div_ceil(block_size) as u32;
        let extents = self.allocate_extents(blocks_needed)?;

        let mut buf = vec![0u8; block_size as usize];
        let mut remaining = data_len;
        for ext in &extents {
            for i in 0..ext.block_count as u32 {
                let to_read = remaining.min(block_size) as usize;
                buf.fill(0);
                data.read_exact(&mut buf[..to_read]).map_err(|e| {
                    FilesystemError::Io(std::io::Error::new(
                        e.kind(),
                        format!("reading file data: {e}"),
                    ))
                })?;
                self.write_block(ext.start_block as u32 + i, &buf)?;
                remaining -= to_read as u64;
            }
        }

        Ok(extents)
    }

    /// Total blocks of an extent list; `u16` because that is what filPyLen holds.
    fn extents_block_total(extents: &[HfsExtDescriptor]) -> u16 {
        extents.iter().map(|e| e.block_count).sum()
    }

    /// Fill a file record's three inline extent slots at `base` (74 data, 86 rsrc).
    fn set_inline_extents(rec: &mut [u8], base: usize, extents: &[HfsExtDescriptor]) {
        rec[base..base + 12].fill(0);
        for (i, ext) in extents.iter().take(3).enumerate() {
            let off = base + i * 4;
            BigEndian::write_u16(&mut rec[off..off + 2], ext.start_block);
            BigEndian::write_u16(&mut rec[off + 2..off + 4], ext.block_count);
        }
    }

    /// Record the fourth extent on into the extents-overflow tree, three per
    /// record keyed by fork block; true if a record was written (F-011).
    fn insert_fork_overflow(
        &mut self,
        file_id: u32,
        fork_type: u8,
        extents: &[HfsExtDescriptor],
    ) -> Result<bool, FilesystemError> {
        use crate::hfs_common::compare_classic_extents_keys;
        if extents.len() <= 3 {
            return Ok(false);
        }
        self.ensure_extents_overflow()?;
        if self.extents_overflow_data.is_none() {
            return Err(FilesystemError::Unsupported(
                "volume has no extents-overflow B-tree; a fragmented fork cannot be created".into(),
            ));
        }
        let mut fork_block: u32 = extents.iter().take(3).map(|e| e.block_count as u32).sum();
        for chunk in extents[3..].chunks(3) {
            // Key: keyLen(1) = 7, forkType(1), fileID(4), startBlock(2); 3 extents follow.
            let mut rec = vec![7u8, fork_type];
            rec.extend_from_slice(&file_id.to_be_bytes());
            rec.extend_from_slice(&(fork_block as u16).to_be_bytes());
            for i in 0..3 {
                let (start, count) = chunk
                    .get(i)
                    .map_or((0, 0), |e| (e.start_block, e.block_count));
                rec.extend_from_slice(&start.to_be_bytes());
                rec.extend_from_slice(&count.to_be_bytes());
            }
            let mut grown = false;
            loop {
                let data = self.extents_overflow_data.as_mut().expect("loaded above");
                match hfs_common::btree_insert_full(
                    data,
                    &rec,
                    &BTreeKeyFormat::CLASSIC_EXTENTS,
                    &compare_classic_extents_keys,
                ) {
                    Ok(()) => break,
                    Err(FilesystemError::DiskFull(_)) if !grown => {
                        self.grow_btree(HfsTree::Extents)?;
                        grown = true;
                    }
                    Err(e) => return Err(e),
                }
            }
            fork_block += chunk.iter().map(|e| e.block_count as u32).sum::<u32>();
        }
        Ok(true)
    }

    /// Build a classic HFS file record (102 bytes).
    /// `mtime_secs = Some(secs)` stamps that Unix time as both create and
    /// modify dates (a cross-fs copy carrying the source mtime through);
    /// `None` stamps `now` (a genuinely new file). The after-create
    /// `set_dates` Commander path still overrides both.
    #[allow(clippy::too_many_arguments)]
    fn build_file_record(
        file_id: u32,
        data_size: u32,
        data_start: u16,
        data_blocks: u16,
        rsrc_size: u32,
        rsrc_start: u16,
        rsrc_blocks: u16,
        type_code: &[u8; 4],
        creator_code: &[u8; 4],
        block_size: u32,
        mtime_secs: Option<u64>,
        finder_flags: u16,
    ) -> [u8; 102] {
        let mut rec = [0u8; 102];
        // Classic HFS stores local wall-clock time, not UTC.
        let now = match mtime_secs {
            Some(s) => disk_core::times::unix_to_mac_local(s),
            None => disk_core::times::mac_local_now(),
        };
        rec[0] = CATALOG_FILE as u8; // cdrType
                                     // rec[1] = reserved
                                     // FInfo at offset 4: fdType(4) + fdCreator(4)
        rec[4..8].copy_from_slice(type_code);
        rec[8..12].copy_from_slice(creator_code);
        BigEndian::write_u16(&mut rec[12..14], finder_flags); // fdFlags
                                                              // filFlNum at offset 20
        BigEndian::write_u32(&mut rec[20..24], file_id);
        // filStBlk at offset 24 stays 0: it's the File Manager's in-memory
        // "first allocation block" cache, NOT persisted on disk — the real
        // fork location lives in filExtRec (offset 74). `fsck_hfs` flags a
        // non-zero on-disk filStBlk as "Reserved fields in the catalog record
        // have incorrect data" (E_CatalogFlagsNotZero). See `data_start` used
        // for the extent record below.
        // filLgLen at offset 26 (data fork logical size)
        BigEndian::write_u32(&mut rec[26..30], data_size);
        // filPyLen at offset 30 (data fork physical size)
        BigEndian::write_u32(&mut rec[30..34], data_blocks as u32 * block_size);
        // filRStBlk at offset 34 stays 0 for the same reason as filStBlk.
        // filRLgLen at offset 36 (rsrc fork logical size)
        BigEndian::write_u32(&mut rec[36..40], rsrc_size);
        // filRPyLen at offset 40 (rsrc fork physical size)
        BigEndian::write_u32(&mut rec[40..44], rsrc_blocks as u32 * block_size);
        // filCrDat at offset 44
        BigEndian::write_u32(&mut rec[44..48], now);
        // filMdDat at offset 48
        BigEndian::write_u32(&mut rec[48..52], now);
        // Data fork extents at offset 74 (3 × 4 bytes)
        if data_blocks > 0 {
            BigEndian::write_u16(&mut rec[74..76], data_start);
            BigEndian::write_u16(&mut rec[76..78], data_blocks);
        }
        // Resource fork extents at offset 86 (3 × 4 bytes)
        if rsrc_blocks > 0 {
            BigEndian::write_u16(&mut rec[86..88], rsrc_start);
            BigEndian::write_u16(&mut rec[88..90], rsrc_blocks);
        }
        rec
    }

    /// Build a classic HFS directory record (70 bytes). `mtime_secs = Some(secs)`
    /// stamps that Unix time into the create and modify dates (a cross-fs
    /// copy carrying the source mtime through); `None` stamps `now`. The
    /// after-create Commander `set_dates` path still overrides both.
    fn build_dir_record_with_dates(dir_id: u32, mtime_secs: Option<u64>) -> [u8; 70] {
        let mut rec = [0u8; 70];
        // Classic HFS stores local wall-clock time, not UTC.
        let now = match mtime_secs {
            Some(s) => disk_core::times::unix_to_mac_local(s),
            None => disk_core::times::mac_local_now(),
        };
        rec[0] = CATALOG_DIR as u8; // cdrType
                                    // dirFlags at offset 2 (u16) = 0
                                    // dirVal at offset 4 (u16) = 0 (child count)
                                    // dirDirID at offset 6
        BigEndian::write_u32(&mut rec[6..10], dir_id);
        // dirCrDat at offset 10
        BigEndian::write_u32(&mut rec[10..14], now);
        // dirMdDat at offset 14
        BigEndian::write_u32(&mut rec[14..18], now);
        rec
    }

    /// Build a thread record for classic HFS.
    /// Thread key: (cnid, ""). Thread data: type(1) + reserved(1) + reserved(8) + parentID(4) + name(Pascal string).
    pub(crate) fn build_thread_record(
        thread_type: i8,
        parent_id: u32,
        name: &[u8],
    ) -> (Vec<u8>, Vec<u8>) {
        // Key: (entry_cnid, "")  — built by caller with build_catalog_key(cnid, &[])
        // Record data: cdrType(1) + reserved(1) + reserved(8) + thdParID(4) + thdCName(Str31=32)
        // Total data = 46 bytes (per hfsutils: fixed Str31 field, not variable-length)
        let mut rec = Vec::with_capacity(46);
        rec.push(thread_type as u8); // cdrType
        rec.push(0); // reserved
        rec.extend_from_slice(&[0u8; 8]); // reserved (2 x LongInt)
        let mut buf4 = [0u8; 4];
        BigEndian::write_u32(&mut buf4, parent_id);
        rec.extend_from_slice(&buf4); // thdParID
                                      // Str31: 1 byte length + up to 31 bytes name + zero padding = 32 bytes total
        let name_len = name.len().min(31);
        let mut str31 = [0u8; 32];
        str31[0] = name_len as u8;
        str31[1..1 + name_len].copy_from_slice(&name[..name_len]);
        rec.extend_from_slice(&str31);
        // Key for the thread (not built here — caller uses build_catalog_key)
        (vec![], rec) // key is unused; caller builds key separately
    }

    /// Sync metadata: write catalog + bitmap + MDB + flush.
    fn do_sync_metadata(&mut self) -> Result<(), FilesystemError> {
        if let Some((create, modify, backup)) = self.pending_volume_dates.take() {
            self.mdb.create_date = create;
            self.mdb.modify_date = modify;
            BigEndian::write_u32(&mut self.mdb.raw_sector[2..6], create);
            BigEndian::write_u32(&mut self.mdb.raw_sector[6..10], modify);
            BigEndian::write_u32(&mut self.mdb.raw_sector[64..68], backup);
        } else {
            self.mdb.modify_date = disk_core::times::mac_local_now();
        }
        if let Some(blocks) = self.pending_boot_blocks.take() {
            self.reader.seek(SeekFrom::Start(self.partition_offset))?;
            self.reader.write_all(&blocks[..])?;
        }
        self.write_catalog()?;
        self.write_volume_bitmap()?;
        self.write_mdb()?;
        self.reader.flush()?;
        Ok(())
    }

    /// If the catalog and/or extents-overflow B-trees are blank (e.g. Disk
    /// Jockey "Empty HFS" output where the MDB reserves extents for both
    /// B-trees but leaves the bytes zeroed), build fresh B-trees and commit
    /// them to disk. Subsequent edits can then use the normal insert paths
    /// instead of panicking on an empty B-tree header.
    fn ensure_catalog_initialized(&mut self) -> Result<(), FilesystemError> {
        // Once confirmed live, never re-check: the extents read below hits disk
        // and would otherwise repeat on every single edit (e.g. per file in a
        // large `untar`).
        if self.btrees_initialized {
            return Ok(());
        }
        let catalog_blank = is_catalog_uninitialized(&self.catalog_data);
        // Read the extents B-tree bytes so we can detect a blank one.
        let extents_data = if self.mdb.extents_file_size > 0 {
            read_fork_data(
                &mut self.reader,
                self.partition_offset,
                &self.mdb,
                &self.mdb.extents_file_extents,
                self.mdb.extents_file_size as u64,
            )
            .ok()
        } else {
            None
        };
        let extents_blank = extents_data
            .as_deref()
            .map(is_catalog_uninitialized)
            .unwrap_or(false);
        if !catalog_blank && !extents_blank {
            self.btrees_initialized = true;
            return Ok(());
        }
        self.initialize_empty_btrees(catalog_blank, extents_blank)?;
        self.btrees_initialized = true;
        Ok(())
    }

    fn initialize_empty_btrees(
        &mut self,
        init_catalog: bool,
        init_extents: bool,
    ) -> Result<(), FilesystemError> {
        if init_catalog {
            let catalog_size = self.catalog_data.len();
            if catalog_size < 1024 {
                return Err(FilesystemError::InvalidData(format!(
                    "cannot initialize empty HFS catalog: region is only {catalog_size} bytes"
                )));
            }
            // Build the empty catalog with the current volume name so the
            // root dir record's key carries it (Mac OS looks up the root by
            // (parent=1, drVN) and rejects volumes with an empty key).
            let vol_name = self.mdb.volume_name_raw.clone();
            let node_size = pick_btree_node_size(catalog_size as u64) as usize;
            let buf = build_empty_hfs_catalog_with_node_size(
                catalog_size,
                node_size,
                &vol_name,
                hfs_common::hfs_now(),
            )?;
            self.catalog_data = buf;
            self.write_catalog()?;
        }

        if init_extents {
            let extents_size = self.mdb.extents_file_size as usize;
            if extents_size >= 512 {
                let buf = build_empty_hfs_extents_btree(extents_size)?;
                write_hfs_fork_data(
                    &mut self.reader,
                    self.partition_offset,
                    &self.mdb,
                    &self.mdb.extents_file_extents,
                    &buf,
                )?;
            }
        }

        // Rebuild the volume bitmap from scratch: only the blocks occupied by
        // the two B-trees should be marked allocated. This avoids trusting any
        // pre-existing garbage in the on-disk bitmap.
        let bitmap_size = (self.mdb.total_blocks as u32).div_ceil(8) as usize;
        let mut bitmap = vec![0u8; bitmap_size];
        let mut used_blocks = 0u32;
        for ext in self.mdb.catalog_file_extents.iter() {
            if ext.block_count == 0 {
                break;
            }
            for i in 0..ext.block_count {
                let bit = ext.start_block as u32 + i as u32;
                if bit < self.mdb.total_blocks as u32 {
                    hfs_common::bitmap_set_bit_be(&mut bitmap, bit);
                    used_blocks += 1;
                }
            }
        }
        for ext in self.mdb.extents_file_extents.iter() {
            if ext.block_count == 0 {
                break;
            }
            for i in 0..ext.block_count {
                let bit = ext.start_block as u32 + i as u32;
                if bit < self.mdb.total_blocks as u32 {
                    hfs_common::bitmap_set_bit_be(&mut bitmap, bit);
                    used_blocks += 1;
                }
            }
        }
        self.bitmap = Some(bitmap);
        self.mdb.free_blocks = (self.mdb.total_blocks as u32).saturating_sub(used_blocks) as u16;

        // Reset volume counters to reflect a truly-empty volume.
        self.mdb.file_count = 0;
        self.mdb.folder_count = 0;
        if self.mdb.next_catalog_id < 16 {
            self.mdb.next_catalog_id = 16;
        }
        self.mdb.modify_date = disk_core::times::mac_local_now();

        self.write_volume_bitmap()?;
        self.write_mdb()?;
        self.reader.flush()?;
        Ok(())
    }
}

/// Classic Mac OS expects HFS B-tree node size = 512 bytes. While the on-disk
/// format technically allows larger node sizes, Apple's reference tools and
/// CiderPress2 both hard-code 512, and an emulated Quadra produced "error
/// type -127" when fed a catalog with 1024-byte nodes. Always use 512 — this
/// is a hard mountability constraint, not a sizing convenience, so do *not* be
/// tempted to scale it up for large catalogs.
///
/// The header node's bitmap covers only `(512 - 256) * 8 = 2048` nodes, but
/// that is no longer a ceiling: B-tree files larger than 2048 nodes chain MAP
/// nodes (NodeType=2) off the header to extend the allocation bitmap (see
/// [`hfs_map_nodes_required`] / [`hfs_common::init_map_node`] and the
/// segment-aware bitmap helpers). Catalogs of tens of thousands of nodes are
/// fully supported at node_size=512; the index is maintained incrementally so
/// there is no per-split rebuild to choke on the larger node count.
fn pick_btree_node_size(_target_bytes: u64) -> u16 {
    512
}

/// Largest B-tree file size the blank-volume builder will produce. With
/// node_size=512, the header bitmap covers 2048 nodes (= 1 MiB) on its own;
/// each appended map node extends this by 3952 nodes. We cap at 16 MiB —
/// 32768 nodes — which is plenty for any real-world HFS catalog while
/// staying well under HFS's 32-bit node-index space.
pub const HFS_MAX_BTREE_FILE_SIZE: u32 = 16 * 1024 * 1024;

/// Number of map nodes (BTNodeKind=2) needed to extend the node-allocation
/// bitmap so it covers `total_nodes` indices, given a node size.
fn hfs_map_nodes_required(total_nodes: u32, node_size: usize) -> u32 {
    let header_cap = ((node_size - 256) * 8) as u32; // header-node bitmap bits
    if total_nodes <= header_cap {
        return 0;
    }
    let per_map = (hfs_common::map_node_bitmap_bytes(node_size) * 8) as u32;
    if per_map == 0 {
        return 0;
    }
    let extra = total_nodes - header_cap;
    extra.div_ceil(per_map)
}

fn build_empty_hfs_catalog_with_node_size(
    catalog_size: usize,
    node_size: usize,
    volume_name_raw: &[u8],
    now: u32,
) -> Result<Vec<u8>, FilesystemError> {
    if volume_name_raw.len() > 27 {
        return Err(FilesystemError::InvalidData(format!(
            "HFS volume name length {} exceeds 27 Mac Roman bytes",
            volume_name_raw.len()
        )));
    }
    let total_nodes = (catalog_size / node_size) as u32;
    if total_nodes < 2 {
        return Err(FilesystemError::InvalidData(format!(
            "cannot initialize empty HFS catalog: only {total_nodes} node(s) fit"
        )));
    }
    // Layout: 0 = header, 1 = root leaf, 2..2+map_nodes = map nodes (BTNodeKind=2)
    // extending the node bitmap beyond the header-node bitmap's capacity.
    let map_nodes = hfs_map_nodes_required(total_nodes, node_size);
    let used_nodes = 2 + map_nodes;
    if total_nodes < used_nodes {
        return Err(FilesystemError::InvalidData(format!(
            "cannot initialize empty HFS catalog: {total_nodes} nodes < {used_nodes} required \
             (header + leaf + {map_nodes} map nodes)"
        )));
    }
    let mut buf = vec![0u8; catalog_size];

    // ---- Node 0: B-tree header node (kind=1, 3 records) ----
    // fLink at byte 0..4 points to the first map node (when map_nodes > 0).
    if map_nodes > 0 {
        BigEndian::write_u32(&mut buf[0..4], 2);
    }
    buf[8] = hfs_common::BTREE_HEADER_NODE as u8;
    buf[9] = 0;
    BigEndian::write_u16(&mut buf[10..12], 3);

    // BTHeaderRec at offset 14
    BigEndian::write_u16(&mut buf[14..16], 1); // depth
    BigEndian::write_u32(&mut buf[16..20], 1); // rootNode = 1
    BigEndian::write_u32(&mut buf[20..24], 2); // leafRecords
    BigEndian::write_u32(&mut buf[24..28], 1); // firstLeafNode
    BigEndian::write_u32(&mut buf[28..32], 1); // lastLeafNode
    BigEndian::write_u16(&mut buf[32..34], node_size as u16); // nodeSize
    BigEndian::write_u16(&mut buf[34..36], 37); // maxKeyLen
    BigEndian::write_u32(&mut buf[36..40], total_nodes);
    BigEndian::write_u32(&mut buf[40..44], total_nodes - used_nodes); // freeNodes

    // Record 1: user data at offset 120 (128 bytes zero)
    // Record 2: node-allocation bitmap at offset 248. Mark nodes 0..used_nodes
    // as allocated. The header bitmap covers the first 2048 bits (at
    // node_size=512); the map-node initialization below claims any indices
    // beyond that. Since used_nodes ≤ 2 + map_nodes ≪ 2048 in practice, all
    // initial bits land in the header bitmap.
    let bitmap_rec_offset = 248usize;
    let header_bitmap_len = node_size - 256; // bytes
    for bit in 0..used_nodes {
        // Mark in header bitmap (MSB-first within each byte).
        let local = bit;
        let byte_idx = (local / 8) as usize;
        let bit_in_byte = 7 - (local % 8) as u8;
        if byte_idx < header_bitmap_len {
            buf[bitmap_rec_offset + byte_idx] |= 1u8 << bit_in_byte;
        }
    }

    // Offset table for header node (stored bottom-up)
    let free_offset = (node_size - 8) as u16;
    BigEndian::write_u16(&mut buf[node_size - 2..node_size], 14);
    BigEndian::write_u16(&mut buf[node_size - 4..node_size - 2], 120);
    BigEndian::write_u16(
        &mut buf[node_size - 6..node_size - 4],
        bitmap_rec_offset as u16,
    );
    BigEndian::write_u16(&mut buf[node_size - 8..node_size - 6], free_offset);

    // ---- Node 1: Leaf node with root dir record + thread ----
    let leaf = node_size;
    buf[leaf + 8] = hfs_common::BTREE_LEAF_NODE as u8; // -1
    buf[leaf + 9] = 1; // height
    BigEndian::write_u16(&mut buf[leaf + 10..leaf + 12], 2); // 2 records

    // Record 0: Root directory (key: parent CNID 1, name = volume name).
    // Mac OS looks up the root dir via (parent=1, drVN); a record with
    // name="" makes it return -127 ("File system internal error").
    let name_len = volume_name_raw.len();
    let r0_key = leaf + 14;
    let key_data_len: u8 = (1 + 4 + 1 + name_len) as u8; // resv + parID + nameLen + name
    buf[r0_key] = key_data_len;
    buf[r0_key + 1] = 0;
    BigEndian::write_u32(&mut buf[r0_key + 2..r0_key + 6], 1);
    buf[r0_key + 6] = name_len as u8;
    buf[r0_key + 7..r0_key + 7 + name_len].copy_from_slice(volume_name_raw);
    // Records start on even offsets within a node; pad an extra byte if the
    // key total (1 + key_data_len) is odd.
    let r0_key_total = 1 + key_data_len as usize;
    let r0_pad = r0_key_total & 1;
    let r0_data = r0_key + r0_key_total + r0_pad;
    buf[r0_data] = CATALOG_DIR as u8;
    BigEndian::write_u32(&mut buf[r0_data + 6..r0_data + 10], 2); // dirDirID = root CNID 2
    BigEndian::write_u32(&mut buf[r0_data + 10..r0_data + 14], now); // crDate
    BigEndian::write_u32(&mut buf[r0_data + 14..r0_data + 18], now); // mdDate
                                                                     // Remainder of the 70-byte CdrDirRec stays zero.

    // Record 1: Root directory thread (key: parent CNID 2, empty name).
    // Per HFS spec the thread RECORD's *key* uses an empty name; the volume
    // name lives in the thread DATA's `thdCName` field at offset 14 of the
    // 46-byte thread record.
    let r1_key = r0_data + 70;
    buf[r1_key] = 6;
    buf[r1_key + 1] = 0;
    BigEndian::write_u32(&mut buf[r1_key + 2..r1_key + 6], 2);
    buf[r1_key + 6] = 0;
    buf[r1_key + 7] = 0;
    let r1_data = r1_key + 8;
    buf[r1_data] = CATALOG_DIR_THREAD as u8;
    BigEndian::write_u32(&mut buf[r1_data + 10..r1_data + 14], 1); // thdParID = 1
    buf[r1_data + 14] = name_len as u8;
    buf[r1_data + 15..r1_data + 15 + name_len].copy_from_slice(volume_name_raw);
    // Remaining bytes of the Str31 name stay zero. Thread record = 46 bytes.

    let free_rel = (r1_data + 46 - leaf) as u16;

    // Leaf offset table (2 records + free space)
    BigEndian::write_u16(&mut buf[leaf + node_size - 2..leaf + node_size], 14);
    BigEndian::write_u16(
        &mut buf[leaf + node_size - 4..leaf + node_size - 2],
        (r1_key - leaf) as u16,
    );
    BigEndian::write_u16(
        &mut buf[leaf + node_size - 6..leaf + node_size - 4],
        free_rel,
    );

    // ---- Map nodes (BTNodeKind=2) at indices 2..2+map_nodes ----
    for i in 0..map_nodes {
        let node_idx = 2 + i;
        let next_link = if i + 1 < map_nodes { node_idx + 1 } else { 0 };
        let prev_link = if i == 0 { 0 } else { node_idx - 1 };
        hfs_common::init_map_node(&mut buf, node_size, node_idx, prev_link, next_link);
    }

    Ok(buf)
}

/// Build a fresh classic HFS extents-overflow B-tree containing only the
/// header node (no leaf records). This is the minimal valid shape for a
/// volume with no files that spill beyond three extents per fork.
fn build_empty_hfs_extents_btree(size: usize) -> Result<Vec<u8>, FilesystemError> {
    build_empty_hfs_extents_btree_with_node_size(size, 512)
}

fn build_empty_hfs_extents_btree_with_node_size(
    size: usize,
    node_size: usize,
) -> Result<Vec<u8>, FilesystemError> {
    let total_nodes = (size / node_size) as u32;
    if total_nodes < 1 {
        return Err(FilesystemError::InvalidData(format!(
            "cannot initialize empty HFS extents B-tree: region is only {size} bytes"
        )));
    }
    let map_nodes = hfs_map_nodes_required(total_nodes, node_size);
    let used_nodes = 1 + map_nodes;
    if total_nodes < used_nodes {
        return Err(FilesystemError::InvalidData(format!(
            "cannot initialize empty HFS extents B-tree: {total_nodes} nodes < {used_nodes} \
             required (header + {map_nodes} map nodes)"
        )));
    }
    let mut buf = vec![0u8; size];

    // Header descriptor. fLink -> first map node when one exists.
    if map_nodes > 0 {
        BigEndian::write_u32(&mut buf[0..4], 1);
    }
    buf[8] = hfs_common::BTREE_HEADER_NODE as u8;
    buf[9] = 0;
    BigEndian::write_u16(&mut buf[10..12], 3);

    // BTHeaderRec: depth=0, root=0, no leaves.
    BigEndian::write_u16(&mut buf[14..16], 0); // depth
    BigEndian::write_u32(&mut buf[16..20], 0); // rootNode
    BigEndian::write_u32(&mut buf[20..24], 0); // leafRecords
    BigEndian::write_u32(&mut buf[24..28], 0); // firstLeafNode
    BigEndian::write_u32(&mut buf[28..32], 0); // lastLeafNode
    BigEndian::write_u16(&mut buf[32..34], node_size as u16); // nodeSize
    BigEndian::write_u16(&mut buf[34..36], 7); // maxKeyLen for extents key (keyLen+forkType+fileID+startBlock)
    BigEndian::write_u32(&mut buf[36..40], total_nodes);
    BigEndian::write_u32(&mut buf[40..44], total_nodes - used_nodes);

    // Record 1: user data (128 bytes, zero) at offset 120
    // Record 2: node bitmap at offset 248; mark node 0 (header) and nodes
    // 1..1+map_nodes (map nodes) as allocated.
    let bitmap_rec_offset = 248usize;
    let header_bitmap_len = node_size - 256;
    for bit in 0..used_nodes {
        let byte_idx = (bit / 8) as usize;
        let bit_in_byte = 7 - (bit % 8) as u8;
        if byte_idx < header_bitmap_len {
            buf[bitmap_rec_offset + byte_idx] |= 1u8 << bit_in_byte;
        }
    }

    let free_offset = (node_size - 8) as u16;
    BigEndian::write_u16(&mut buf[node_size - 2..node_size], 14);
    BigEndian::write_u16(&mut buf[node_size - 4..node_size - 2], 120);
    BigEndian::write_u16(
        &mut buf[node_size - 6..node_size - 4],
        bitmap_rec_offset as u16,
    );
    BigEndian::write_u16(&mut buf[node_size - 8..node_size - 6], free_offset);

    // Map nodes at indices 1..1+map_nodes
    for i in 0..map_nodes {
        let node_idx = 1 + i;
        let next_link = if i + 1 < map_nodes { node_idx + 1 } else { 0 };
        let prev_link = if i == 0 { 0 } else { node_idx - 1 };
        hfs_common::init_map_node(&mut buf, node_size, node_idx, prev_link, next_link);
    }

    Ok(buf)
}

/// Build a brand-new, empty classic-HFS partition image with the given total
/// size and allocation block size. The returned `Vec<u8>` is a standalone
/// partition blob (no APM wrapper) containing:
///
/// - sectors 0..1: zeroed boot blocks
/// - sector 2: primary MDB (Master Directory Block)
/// - starting at sector 3: volume bitmap
/// - aligned up to `drAlBlSt`: allocation blocks
/// - blocks 0..4: extents-overflow B-tree (header-only)
/// - blocks 4..8: catalog B-tree (header + leaf with root dir + root thread)
/// - blocks 8..: free
/// - next-to-last sector: alternate MDB (mirror of primary)
/// - last sector: reserved (zero) — required by HFS spec
///
/// The volume's `drFndrInfo`, dates and boot blocks are left at defaults;
/// callers (e.g. Step 6 of the expand-block-size plan) overwrite those
/// afterward. `drNxtCNID` starts at 16, matching real-world HFS volumes.
///
/// `block_size` must be a non-zero multiple of 512 and small enough that
/// `total_blocks` fits in a `u16` (<= 65535).
pub fn create_blank_hfs(
    target_size_bytes: u64,
    block_size: u32,
    volume_name: &str,
) -> Result<Vec<u8>, FilesystemError> {
    create_blank_hfs_sized(target_size_bytes, block_size, volume_name, 0, 0)
}

/// Default B-tree sizes that loosely follow `hformat` (hfsutils).
/// The classic clump-size convention is `4 × block_size`; hformat scales
/// the Catalog file with volume size so steady-state file activity
/// rarely triggers an extension (each extension fragments the metadata).
/// Returns `(catalog_bytes, extents_bytes)` — both clump-aligned, with a
/// 24-block floor. Catalog ≈ 0.5 % of the volume; Extents ≈ half that.
///
/// Inputs are taken in bytes (`target_volume_bytes`) so callers don't
/// need to repeat the `first_alloc_block` math; `block_size` must be a
/// non-zero multiple of 512 (the create_blank_hfs precondition).
pub fn default_btree_sizes(target_volume_bytes: u64, block_size: u32) -> (u32, u32) {
    if block_size == 0 {
        return (0, 0);
    }
    let clump = 4u64 * block_size as u64;
    let floor = 24u64 * block_size as u64;
    let raw = target_volume_bytes / 200; // 0.5 %
    let catalog = raw.max(floor).div_ceil(clump) * clump;
    let extents = (raw / 2).max(floor).div_ceil(clump) * clump;
    (
        catalog.min(u32::MAX as u64) as u32,
        extents.min(u32::MAX as u64) as u32,
    )
}

/// Choose catalog + extents-overflow B-tree sizes (in bytes) for a freshly
/// built HFS **clone target** of `target_size` at `block_size`, given the
/// source volume's B-tree sizes.
///
/// Returns the *larger* of the source-derived estimate (1.5× the source
/// catalog, 1× the source extents) and the volume-scaled blank-format default
/// ([`default_btree_sizes`]), clamped to [`HFS_MAX_BTREE_FILE_SIZE`].
///
/// Using the blank default as a floor is the important part: a densely-packed
/// source catalog reports a small byte size, but the target re-inserts every
/// record through the byte-based leaf split, which can pack *less* densely and
/// need more nodes than the source used. A catalog pre-sized to only 1.5× the
/// source then runs out of nodes mid-clone ("no free B-tree nodes"), because
/// the B-tree file can't grow. Flooring at the same size a blank volume of
/// `target_size` would get (≈0.5 % of the volume) gives ample headroom while
/// staying well under the 16 MiB ceiling for any classic-HFS-sized volume.
pub fn clone_target_btree_sizes(
    target_size: u64,
    block_size: u32,
    source_catalog: u32,
    source_extents: u32,
) -> (u32, u32) {
    let (default_cat, default_ext) = default_btree_sizes(target_size, block_size);
    let catalog = source_catalog
        .saturating_mul(3)
        .saturating_div(2)
        .max(default_cat)
        .min(HFS_MAX_BTREE_FILE_SIZE);
    let extents = source_extents.max(default_ext).min(HFS_MAX_BTREE_FILE_SIZE);
    (catalog, extents)
}

/// Pick the smallest 512-byte-multiple allocation block size that keeps a
/// volume of `volume_bytes` within HFS's 65535-block (`drNmAlBlks`) ceiling.
pub fn pick_block_size(volume_bytes: u64) -> u32 {
    let mut bs: u32 = 512;
    while volume_bytes / bs as u64 > 65535 {
        bs = bs.saturating_mul(2);
        if bs == 0 {
            return 1 << 16;
        }
    }
    bs
}

/// Variant of [`create_blank_hfs`] that lets the caller request minimum
/// extents-overflow and catalog B-tree sizes (in bytes). Each is rounded up
/// to a whole allocation block with a 4-block floor; zero means the
/// volume-scaled [`default_btree_sizes`]. Used by the expand-block-size
/// pipeline so the new volume's catalog can hold every record from a
/// fragmented source.
pub fn create_blank_hfs_sized(
    target_size_bytes: u64,
    block_size: u32,
    volume_name: &str,
    min_extents_bytes: u32,
    min_catalog_bytes: u32,
) -> Result<Vec<u8>, FilesystemError> {
    create_blank_hfs_sized_at(
        target_size_bytes,
        block_size,
        volume_name,
        min_extents_bytes,
        min_catalog_bytes,
        hfs_common::hfs_now(),
    )
}

/// [`create_blank_hfs_sized`] with the volume dates fixed at `now`.
pub(crate) fn create_blank_hfs_sized_at(
    target_size_bytes: u64,
    block_size: u32,
    volume_name: &str,
    min_extents_bytes: u32,
    min_catalog_bytes: u32,
    now: u32,
) -> Result<Vec<u8>, FilesystemError> {
    let (front, mdb, image_size) = build_blank_hfs_front(
        target_size_bytes,
        block_size,
        volume_name,
        min_extents_bytes,
        min_catalog_bytes,
        now,
    )?;
    let mut img = vec![0u8; image_size as usize];
    img[..front.len()].copy_from_slice(&front);
    let alt_off = image_size as usize - 1024;
    img[alt_off..alt_off + 512].copy_from_slice(&mdb);
    Ok(img)
}

/// Streaming variant of [`create_blank_hfs_sized`]: writes the metadata regions
/// (boot blocks, MDB, bitmap, B-trees, alternate MDB) at `at_offset` in `target`
/// and leaves the free middle untouched. Returns the volume's image size, which
/// is `target_size_bytes` rounded down to what a whole number of allocation
/// blocks covers.
///
/// The caller sizes the backing file (`File::set_len`) so the untouched middle
/// reads back as zeros — the same contract as `fs_unix::efs::write_blank_efs`.
pub fn write_blank_hfs_into<W: Write + Seek>(
    target: &mut W,
    at_offset: u64,
    target_size_bytes: u64,
    block_size: u32,
    volume_name: &str,
) -> Result<u64, FilesystemError> {
    write_blank_hfs_into_at(
        target,
        at_offset,
        target_size_bytes,
        block_size,
        volume_name,
        hfs_common::hfs_now(),
    )
}

/// [`write_blank_hfs_into`] with the volume dates fixed at `now`.
pub(crate) fn write_blank_hfs_into_at<W: Write + Seek>(
    target: &mut W,
    at_offset: u64,
    target_size_bytes: u64,
    block_size: u32,
    volume_name: &str,
    now: u32,
) -> Result<u64, FilesystemError> {
    let (front, mdb, image_size) =
        build_blank_hfs_front(target_size_bytes, block_size, volume_name, 0, 0, now)?;
    target.seek(SeekFrom::Start(at_offset))?;
    target.write_all(&front)?;
    target.seek(SeekFrom::Start(at_offset + image_size - 1024))?;
    target.write_all(&mdb)?;
    target.write_all(&[0u8; 512])?;
    Ok(image_size)
}

/// Build a blank HFS volume's front region (boot blocks, MDB, bitmap, both
/// B-trees) plus the 512-byte MDB the tail mirrors and the total image size.
/// Shared by the in-memory and streaming constructors above, so a multi-hundred-
/// MB blank never has to materialize its free space in RAM.
fn build_blank_hfs_front(
    target_size_bytes: u64,
    block_size: u32,
    volume_name: &str,
    min_extents_bytes: u32,
    min_catalog_bytes: u32,
    now: u32,
) -> Result<(Vec<u8>, [u8; 512], u64), FilesystemError> {
    if block_size == 0 || !block_size.is_multiple_of(512) {
        return Err(FilesystemError::InvalidData(format!(
            "HFS block_size must be a non-zero multiple of 512 (got {block_size})"
        )));
    }

    let name_raw = utf8_to_mac_roman(volume_name)?;
    if name_raw.len() > 27 {
        return Err(FilesystemError::InvalidData(format!(
            "HFS volume name '{volume_name}' exceeds 27 Mac Roman bytes"
        )));
    }

    // Iteratively determine first_alloc_block. Bitmap starts at sector 3; its
    // size depends on total_blocks, which depends on first_alloc_block, so
    // grow the reserved region until it stops changing.
    let mut first_alloc_block: u16 = 3;
    let total_blocks: u32;
    loop {
        let pre_alloc = first_alloc_block as u64 * 512;
        if target_size_bytes <= pre_alloc + 512 {
            return Err(FilesystemError::InvalidData(format!(
                "HFS volume too small ({target_size_bytes} bytes) for block_size {block_size}"
            )));
        }
        let usable = target_size_bytes - pre_alloc - 1024; // minus alt MDB + reserved last sector
        let tb = usable / block_size as u64;
        if tb == 0 {
            return Err(FilesystemError::InvalidData(format!(
                "HFS volume too small for block_size {block_size}"
            )));
        }
        if tb > 65535 {
            return Err(FilesystemError::InvalidData(format!(
                "HFS would have {tb} allocation blocks at block_size {block_size}, exceeding u16 ceiling 65535"
            )));
        }
        let tb = tb as u32;
        let bitmap_bytes = (tb as u64).div_ceil(8);
        let bitmap_sectors = bitmap_bytes.div_ceil(512) as u16;
        let needed = 3u16 + bitmap_sectors;
        if needed <= first_alloc_block {
            total_blocks = tb;
            break;
        }
        first_alloc_block = needed;
    }

    // B-trees consume contiguous allocation blocks at the start of the
    // partition; rb-cli cannot grow a classic catalog later, so a zero request
    // takes the volume-scaled hformat default rather than a 4-block stub (R-060).
    let (default_catalog, default_extents) = default_btree_sizes(target_size_bytes, block_size);
    let blocks_for = |bytes: u32, default: u32| -> u16 {
        let bytes = if bytes == 0 { default } else { bytes };
        let n = (bytes as u64).div_ceil(block_size as u64).max(4);
        n.min(u16::MAX as u64) as u16
    };
    let extents_blocks = blocks_for(min_extents_bytes, default_extents);
    let catalog_blocks = blocks_for(min_catalog_bytes, default_catalog);
    let extents_start: u16 = 0;
    let catalog_start: u16 = extents_blocks;
    let btree_blocks: u16 = extents_blocks + catalog_blocks;

    if total_blocks < btree_blocks as u32 {
        return Err(FilesystemError::InvalidData(format!(
            "HFS volume too small: {total_blocks} allocation blocks is below the minimum of {btree_blocks} needed for B-trees"
        )));
    }

    let extents_size = extents_blocks as u32 * block_size;
    let catalog_size = catalog_blocks as u32 * block_size;

    // Scale node_size up from 512 when the B-tree file would have more nodes
    // than the header-node bitmap can address. This avoids needing dedicated
    // "map nodes" while still being spec-compliant.
    let extents_node_size = pick_btree_node_size(extents_size as u64) as usize;
    let catalog_node_size = pick_btree_node_size(catalog_size as u64) as usize;

    // Per HFS spec: alt MDB lives at the *next-to-last* sector of the volume,
    // and the very last sector is reserved (zero). Reserve two trailing sectors.
    let image_size =
        first_alloc_block as u64 * 512 + total_blocks as u64 * block_size as u64 + 1024;
    // Everything the format touches at the head is contiguous: the reserved
    // sectors (boot blocks, MDB, bitmap) then the B-trees in the first
    // allocation blocks. The rest of the volume is free space.
    let front_size = first_alloc_block as usize * 512 + btree_blocks as usize * block_size as usize;
    let mut front = vec![0u8; front_size];

    // Volume bitmap at sector 3: mark the first btree_blocks allocation
    // blocks as used (the rest remain free).
    let bitmap_off = 3 * 512;
    for b in 0..btree_blocks as u32 {
        let byte_idx = (b / 8) as usize;
        let bit_idx = 7 - (b % 8) as u8;
        front[bitmap_off + byte_idx] |= 1 << bit_idx;
    }

    // Extents B-tree (header-only; no leaf records)
    let extents_bytes =
        build_empty_hfs_extents_btree_with_node_size(extents_size as usize, extents_node_size)?;
    let extents_off = first_alloc_block as u64 * 512 + extents_start as u64 * block_size as u64;
    front[extents_off as usize..extents_off as usize + extents_bytes.len()]
        .copy_from_slice(&extents_bytes);

    // Catalog B-tree with root directory (CNID 2) + its thread record.
    // The volume name lives in the root dir record's KEY (parent=1) and
    // in the root thread record's `thdCName` data field. Mac OS looks
    // these up by drVN at mount time.
    let catalog_bytes = build_empty_hfs_catalog_with_node_size(
        catalog_size as usize,
        catalog_node_size,
        &name_raw,
        now,
    )?;
    let catalog_off = first_alloc_block as u64 * 512 + catalog_start as u64 * block_size as u64;
    front[catalog_off as usize..catalog_off as usize + catalog_bytes.len()]
        .copy_from_slice(&catalog_bytes);

    // Primary MDB at sector 2
    let mdb = build_blank_mdb(
        now,
        &name_raw,
        total_blocks as u16,
        block_size,
        first_alloc_block,
        catalog_start,
        catalog_blocks,
        catalog_size,
        extents_start,
        extents_blocks,
        extents_size,
        btree_blocks,
    );
    front[1024..1024 + 512].copy_from_slice(&mdb);

    // The alternate MDB goes at the next-to-last sector (= immediately after the
    // last allocation block); the final sector stays zero (reserved by Apple).
    // Both constructors place it from the returned copy.
    Ok((front, mdb, image_size))
}

#[allow(clippy::too_many_arguments)]
fn build_blank_mdb(
    now: u32,
    name_raw: &[u8],
    total_blocks: u16,
    block_size: u32,
    first_alloc_block: u16,
    catalog_start: u16,
    catalog_blocks: u16,
    catalog_size: u32,
    extents_start: u16,
    extents_blocks: u16,
    extents_size: u32,
    allocated_blocks: u16,
) -> [u8; 512] {
    let mut mdb = [0u8; 512];
    BigEndian::write_u16(&mut mdb[0..2], HFS_SIGNATURE);
    BigEndian::write_u32(&mut mdb[2..6], now); // drCrDate
    BigEndian::write_u32(&mut mdb[6..10], now); // drLsMod
                                                // drAtrb: kHFSVolumeUnmountedMask (0x0100). Without this bit, classic
                                                // Mac OS treats the volume as needing repair on first mount and runs
                                                // Disk First Aid — manifests as a slow startup on a real Mac.
    BigEndian::write_u16(&mut mdb[10..12], 0x0100);
    BigEndian::write_u16(&mut mdb[14..16], 3); // drVBMSt = bitmap sector
    BigEndian::write_u16(&mut mdb[18..20], total_blocks); // drNmAlBlks
    BigEndian::write_u32(&mut mdb[20..24], block_size); // drAlBlkSiz
    BigEndian::write_u32(&mut mdb[24..28], 4 * block_size); // drClpSiz
    BigEndian::write_u16(&mut mdb[28..30], first_alloc_block); // drAlBlSt
    BigEndian::write_u32(&mut mdb[30..34], 16); // drNxtCNID
    BigEndian::write_u16(&mut mdb[34..36], total_blocks - allocated_blocks); // drFreeBks
    mdb[36] = name_raw.len() as u8;
    mdb[37..37 + name_raw.len()].copy_from_slice(name_raw);
    BigEndian::write_u32(&mut mdb[74..78], extents_size); // drXTClpSiz
    BigEndian::write_u32(&mut mdb[78..82], catalog_size); // drCTClpSiz
                                                          // drFilCnt (84..88) and drDirCnt (88..92) both 0: no files and no
                                                          // non-root directories on a fresh volume. (HFS drDirCnt excludes the
                                                          // root directory — see hfs_fsck.rs.)
    BigEndian::write_u32(&mut mdb[130..134], extents_size); // drXTFlSize
    BigEndian::write_u16(&mut mdb[134..136], extents_start);
    BigEndian::write_u16(&mut mdb[136..138], extents_blocks);
    BigEndian::write_u32(&mut mdb[146..150], catalog_size); // drCTFlSize
    BigEndian::write_u16(&mut mdb[150..152], catalog_start);
    BigEndian::write_u16(&mut mdb[152..154], catalog_blocks);
    mdb
}

impl<R: Read + Seek + Send> Filesystem for HfsFilesystem<R> {
    fn root(&mut self) -> Result<FileEntry, FilesystemError> {
        Ok(FileEntry {
            name: "/".into(),
            path: "/".into(),
            entry_type: EntryType::Directory,
            size: 0,
            location: 2, // HFS root directory CNID
            modified: None,
            modified_unix: None,
            type_code: None,
            creator_code: None,
            symlink_target: None,
            special_type: None,
            mode: None,
            uid: None,
            gid: None,
            resource_fork_size: None,
            aux_type: None,
            link_target_cnid: None,
            amiga_protection: None,
            amiga_comment: None,
            amiga_date: None,
            dos_attributes: None,
            finder_flags: None,
            prodos_file_type: None,
            mac_dates: None,
            owner_label: None,
            native_attrs: None,
            qnx2_attrs: None,
        })
    }

    fn list_directory(&mut self, entry: &FileEntry) -> Result<Vec<FileEntry>, FilesystemError> {
        let parent_id = entry.location as u32;
        let children = self.list_children(parent_id)?;

        let mut entries = Vec::new();
        for child in children {
            match child {
                CatalogRecord::Directory {
                    dir_id,
                    name,
                    dates,
                    ..
                } => {
                    let path = if entry.path == "/" {
                        format!("/{name}")
                    } else {
                        format!("{}/{name}", entry.path)
                    };
                    let mut fe = FileEntry::new_directory(name, path, dir_id as u64);
                    fe.modified = hfs_common::format_mac_date(dates.1);
                    fe.modified_unix = disk_core::times::mac_local_to_unix(dates.1);
                    fe.mac_dates = Some(dates);
                    entries.push(fe);
                }
                CatalogRecord::File {
                    file_id,
                    name,
                    data_size,
                    rsrc_size,
                    rsrc_extents,
                    type_code,
                    creator_code,
                    finder_flags,
                    dates,
                    ..
                } => {
                    let path = if entry.path == "/" {
                        format!("/{name}")
                    } else {
                        format!("{}/{name}", entry.path)
                    };
                    let mut fe = FileEntry::new_file(name, path, data_size as u64, file_id as u64);
                    fe.type_code = Some(type_code);
                    fe.creator_code = Some(creator_code);
                    fe.finder_flags = Some(finder_flags);
                    fe.modified = hfs_common::format_mac_date(dates.1);
                    fe.modified_unix = disk_core::times::mac_local_to_unix(dates.1);
                    fe.mac_dates = Some(dates);
                    if rsrc_size > 0 {
                        fe.resource_fork_size = Some(rsrc_size as u64);
                    }
                    // Classic-Mac alias: fdFlags bit 0x8000 set. Read the
                    // resource fork (small for aliases, typically <4KB) and
                    // parse the `alis` resource to surface the target.
                    if finder_flags & crate::mac_alias::IS_ALIAS_FLAG != 0 && rsrc_size > 0 {
                        if let Ok(rsrc) = read_fork_data(
                            &mut self.reader,
                            self.partition_offset,
                            &self.mdb,
                            &rsrc_extents,
                            rsrc_size as u64,
                        ) {
                            if let Some(target) = crate::mac_alias::resolve_alias_target(&rsrc) {
                                fe.symlink_target = Some(target);
                            }
                        }
                    }
                    entries.push(fe);
                }
            }
        }

        entries.sort_by_key(|a| a.name.to_lowercase());
        Ok(entries)
    }

    fn read_file(
        &mut self,
        entry: &FileEntry,
        max_bytes: usize,
    ) -> Result<Vec<u8>, FilesystemError> {
        let file_id = entry.location as u32;
        let (data_size, extents, _rsrc_size, _rsrc_extents) =
            self.find_file_by_id(file_id).ok_or_else(|| {
                FilesystemError::NotFound(format!("file id {file_id} not found in catalog"))
            })?;

        let mut data = self.read_fork_with_overflow(file_id, 0x00, &extents, data_size as u64)?;
        data.truncate(max_bytes);
        Ok(data)
    }

    fn write_file_to(
        &mut self,
        entry: &FileEntry,
        writer: &mut dyn std::io::Write,
    ) -> Result<u64, FilesystemError> {
        if entry.is_directory() {
            return Err(FilesystemError::NotADirectory(entry.path.clone()));
        }
        let file_id = entry.location as u32;
        let (data_size, extents, _rsrc_size, _rsrc_extents) =
            self.find_file_by_id(file_id).ok_or_else(|| {
                FilesystemError::NotFound(format!("file id {file_id} not found in catalog"))
            })?;
        self.write_fork_with_overflow_to(file_id, 0x00, &extents, data_size as u64, writer)
    }

    fn volume_label(&self) -> Option<&str> {
        if self.mdb.volume_name.is_empty() {
            None
        } else {
            Some(&self.mdb.volume_name)
        }
    }

    fn fs_type(&self) -> &str {
        "HFS"
    }

    fn validate_name(&self, name: &str) -> Result<(), FilesystemError> {
        validate_hfs_create_name(name).map(|_| ())
    }

    fn uses_colon_paths(&self) -> bool {
        true
    }

    fn total_size(&self) -> u64 {
        self.mdb.total_blocks as u64 * self.mdb.block_size as u64
    }

    fn used_size(&self) -> u64 {
        (self.mdb.total_blocks - self.mdb.free_blocks) as u64 * self.mdb.block_size as u64
    }

    /// HFS allocates fork storage in fixed-size allocation blocks
    /// (`drAlBlkSiz`), so a fork's real on-disk footprint is its length
    /// rounded up to this unit. Exposing it lets the copy preflight and
    /// `du` model destination consumption exactly instead of falling back
    /// to a 512-byte floor.
    fn allocation_unit(&self) -> Option<u64> {
        if self.mdb.block_size == 0 {
            None
        } else {
            Some(self.mdb.block_size as u64)
        }
    }

    fn last_data_byte(&mut self) -> Result<u64, FilesystemError> {
        let bitmap = self.read_volume_bitmap()?;
        let last_block = find_last_set_bit(&bitmap, self.mdb.total_blocks as u32);
        match last_block {
            Some(block) => {
                let byte = self.alloc_block_offset(block + 1);
                Ok(byte)
            }
            None => Ok(self.total_size()),
        }
    }

    fn write_resource_fork_to(
        &mut self,
        entry: &FileEntry,
        writer: &mut dyn std::io::Write,
    ) -> Result<u64, FilesystemError> {
        let file_id = entry.location as u32;
        let (_data_size, _data_ext, rsrc_size, rsrc_extents) =
            self.find_file_by_id(file_id).ok_or_else(|| {
                FilesystemError::NotFound(format!("file id {file_id} not found in catalog"))
            })?;
        if rsrc_size == 0 {
            return Ok(0);
        }
        let data = self.read_fork_with_overflow(file_id, 0xFF, &rsrc_extents, rsrc_size as u64)?;
        writer.write_all(&data)?;
        Ok(data.len() as u64)
    }

    fn resource_fork_size(&mut self, entry: &FileEntry) -> u64 {
        let file_id = entry.location as u32;
        self.find_file_by_id(file_id)
            .map(|(_ds, _de, rs, _re)| rs as u64)
            .unwrap_or(0)
    }

    fn fragmentation_stats(
        &mut self,
    ) -> Option<Result<disk_core::filesystem::FragmentationStats, FilesystemError>> {
        Some(Ok(hfs_fragmentation_stats(&self.catalog_data)))
    }

    fn blessed_system_folder(&mut self) -> Option<(u64, String)> {
        let cnid = self.mdb.finder_info[0];
        if cnid == 0 {
            return None;
        }
        // Look up folder name via thread record
        if let Some((_node, _rec, offset)) = self.find_catalog_record_by_cnid(cnid) {
            let key_len = self.catalog_data[offset] as usize;
            let mut rec_data_start = offset + 1 + key_len;
            if !rec_data_start.is_multiple_of(2) {
                rec_data_start += 1;
            }
            // Thread record: type(1) + reserved(1) + reserved(8) + parentID(4) + name(Pascal)
            if rec_data_start + 15 <= self.catalog_data.len() {
                let name_len = self.catalog_data[rec_data_start + 14] as usize;
                if rec_data_start + 15 + name_len <= self.catalog_data.len() {
                    let name = mac_roman_to_utf8(
                        &self.catalog_data[rec_data_start + 15..rec_data_start + 15 + name_len],
                    );
                    return Some((cnid as u64, name));
                }
            }
        }
        Some((cnid as u64, format!("CNID {}", cnid)))
    }

    fn fsck(&mut self) -> Option<Result<disk_core::fsck::FsckResult, FilesystemError>> {
        Some(self.fsck())
    }
}

/// Classic HFS thread record type for directories. (File threads exist in
/// the spec but are optional and we don't emit them — see `create_file`.)
const CATALOG_DIR_THREAD: i8 = 3;

impl<R: Read + Write + Seek + Send> EditableFilesystem for HfsFilesystem<R> {
    fn as_filesystem(&self) -> &dyn disk_core::filesystem::Filesystem {
        self
    }
    fn as_filesystem_mut(&mut self) -> &mut dyn disk_core::filesystem::Filesystem {
        self
    }
    fn begin_bulk(&mut self) {
        self.bulk_mode = true;
    }

    fn end_bulk(&mut self) {
        self.bulk_mode = false;
    }

    fn create_file(
        &mut self,
        parent: &FileEntry,
        name: &str,
        data: &mut dyn std::io::Read,
        data_len: u64,
        options: &CreateFileOptions,
    ) -> Result<FileEntry, FilesystemError> {
        self.ensure_catalog_initialized()?;
        let snap = self.snapshot();
        let extents_before = self.extents_overflow_data.clone();
        let result = (|| {
            let parent_id = parent.location as u32;

            let name_bytes = validate_hfs_create_name(name)?;

            // Check for duplicates
            if self
                .find_catalog_record_by_name(parent_id, &name_bytes)
                .is_some()
            {
                return Err(FilesystemError::AlreadyExists(name.into()));
            }

            // Assign CNID
            let file_id = self.mdb.next_catalog_id;
            self.mdb.next_catalog_id += 1;

            // Determine type/creator: prefer caller-supplied (e.g. from an
            // imported AppleDouble), fill any missing or blank half from the
            // extension dictionary so a partial FInfo isn't thrown away.
            let (type_code, creator_code) = hfs_common::resolve_create_type_creator(
                name,
                options.os_type,
                options.os_creator,
                options.type_code.as_deref(),
                options.creator_code.as_deref(),
            );

            // Allocate blocks and write data
            let data_extents = self.write_data_to_blocks(data, data_len)?;

            // Handle resource fork
            let (rsrc_extents, rsrc_size) = if let Some(ref rsrc_src) = options.resource_fork {
                match rsrc_src {
                    disk_core::filesystem::ResourceForkSource::Data(rsrc_data) => {
                        let mut cursor = std::io::Cursor::new(rsrc_data);
                        let ext = self.write_data_to_blocks(&mut cursor, rsrc_data.len() as u64)?;
                        (ext, rsrc_data.len() as u32)
                    }
                    disk_core::filesystem::ResourceForkSource::File(path) => {
                        let mut f = std::fs::File::open(path)?;
                        let len = f.metadata()?.len();
                        let ext = self.write_data_to_blocks(&mut f, len)?;
                        (ext, len as u32)
                    }
                }
            } else {
                (Vec::new(), 0)
            };

            // Build file record. A cross-fs copy passes the source mtime
            // through `options.unix_times`; a genuinely new file leaves it None
            // and takes `now`. Commander's `PreservedDates.mac` path still
            // overrides both via a follow-up `set_dates` when present.
            let mtime = options.unix_times.map(|t| t.mtime_or_now());
            let mut file_rec = Self::build_file_record(
                file_id,
                data_len as u32,
                data_extents.first().map_or(0, |e| e.start_block),
                Self::extents_block_total(&data_extents),
                rsrc_size,
                rsrc_extents.first().map_or(0, |e| e.start_block),
                Self::extents_block_total(&rsrc_extents),
                &type_code,
                &creator_code,
                self.mdb.block_size,
                mtime,
                options.finder_flags.unwrap_or(0),
            );
            Self::set_inline_extents(&mut file_rec, 74, &data_extents);
            Self::set_inline_extents(&mut file_rec, 86, &rsrc_extents);

            // Build key + record for catalog insertion
            let key = Self::build_catalog_key(parent_id, &name_bytes);
            let mut key_record = key;
            key_record.extend_from_slice(&file_rec);

            self.insert_catalog_record(&key_record)?;

            // No file thread record: classic HFS file threads are optional
            // (Inside Macintosh: Files), and Finder / CiderPress2 don't emit
            // them. Skipping them roughly halves catalog size for file-heavy
            // volumes (map nodes now lift the old 2048-node header-bitmap limit,
            // so this is a size/compat choice, not a hard cap workaround). File
            // CNID lookups fall back to a leaf scan in `locate_record_data` /
            // `find_file_record_offset_by_cnid`.

            // Update parent valence
            self.update_parent_valence(parent_id, 1)?;

            // Update MDB counts
            self.mdb.file_count += 1;

            let mut overflow_changed = self.insert_fork_overflow(file_id, 0x00, &data_extents)?;
            overflow_changed |= self.insert_fork_overflow(file_id, 0xFF, &rsrc_extents)?;
            if overflow_changed {
                self.write_extents_overflow_back()?;
            }

            let path = if parent.path == "/" {
                format!("/{name}")
            } else {
                format!("{}/{name}", parent.path)
            };
            let mut fe = FileEntry::new_file(name.to_string(), path, data_len, file_id as u64);
            if type_code != [0; 4] {
                fe.type_code = Some(type_code);
                fe.creator_code = Some(creator_code);
            }
            fe.finder_flags = options.finder_flags;
            if rsrc_size > 0 {
                fe.resource_fork_size = Some(rsrc_size as u64);
            }
            let stamped = mtime.unwrap_or_else(disk_core::times::now);
            fe.modified_unix = Some(stamped);
            fe.mac_dates = Some((
                disk_core::times::unix_to_mac_local(stamped),
                disk_core::times::unix_to_mac_local(stamped),
                0,
            ));
            Ok(fe)
        })();
        if result.is_err() {
            self.extents_overflow_data = extents_before;
            self.restore_snapshot(snap);
        }
        result
    }

    fn create_directory(
        &mut self,
        parent: &FileEntry,
        name: &str,
        options: &CreateDirectoryOptions,
    ) -> Result<FileEntry, FilesystemError> {
        self.ensure_catalog_initialized()?;
        let snap = self.snapshot();
        let result = (|| {
            let parent_id = parent.location as u32;

            let name_bytes = validate_hfs_create_name(name)?;

            // Check duplicates
            if self
                .find_catalog_record_by_name(parent_id, &name_bytes)
                .is_some()
            {
                return Err(FilesystemError::AlreadyExists(name.into()));
            }

            // Assign CNID
            let folder_id = self.mdb.next_catalog_id;
            self.mdb.next_catalog_id += 1;

            // Build folder record — see build_file_record's comment on how
            // options.unix_times threads a source mtime through.
            let mtime = options.unix_times.map(|t| t.mtime_or_now());
            let folder_rec = Self::build_dir_record_with_dates(folder_id, mtime);

            // Build key + record
            let key = Self::build_catalog_key(parent_id, &name_bytes);
            let mut key_record = key;
            key_record.extend_from_slice(&folder_rec);

            self.insert_catalog_record(&key_record)?;

            // Thread record
            let (_, thread_data) =
                Self::build_thread_record(CATALOG_DIR_THREAD, parent_id, &name_bytes);
            let thread_key = Self::build_catalog_key(folder_id, &[]);
            let mut thread_record = thread_key;
            thread_record.extend_from_slice(&thread_data);
            self.insert_catalog_record(&thread_record)?;

            // Update parent valence
            self.update_parent_valence(parent_id, 1)?;

            // Update MDB
            self.mdb.folder_count += 1;

            let path = if parent.path == "/" {
                format!("/{name}")
            } else {
                format!("{}/{name}", parent.path)
            };
            let mut fe = FileEntry::new_directory(name.to_string(), path, folder_id as u64);
            let stamped = mtime.unwrap_or_else(disk_core::times::now);
            fe.modified_unix = Some(stamped);
            fe.mac_dates = Some((
                disk_core::times::unix_to_mac_local(stamped),
                disk_core::times::unix_to_mac_local(stamped),
                0,
            ));
            Ok(fe)
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    fn delete_entry(
        &mut self,
        parent: &FileEntry,
        entry: &FileEntry,
    ) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let extents_before = self.extents_overflow_data.clone();
        let result = (|| {
            let parent_id = parent.location as u32;
            let cnid = entry.location as u32;

            // Check directory is empty
            if entry.is_directory() {
                let children = self.list_children(cnid)?;
                if !children.is_empty() {
                    return Err(FilesystemError::InvalidData(
                        "cannot delete non-empty directory".into(),
                    ));
                }
            }

            // Find the entry record
            let name_bytes = utf8_to_mac_roman(&entry.name)?;
            let (node_idx, rec_idx, _offset) = self
                .find_catalog_record_by_name(parent_id, &name_bytes)
                .ok_or_else(|| {
                    FilesystemError::NotFound(format!(
                        "entry '{}' not found in catalog",
                        entry.name
                    ))
                })?;

            // If it's a file, free its fork blocks
            let mut overflow_changed = false;
            if !entry.is_directory() {
                if let Some((_, data_extents, _, rsrc_extents)) = self.find_file_by_id(cnid) {
                    self.free_extent_blocks(&data_extents);
                    self.free_extent_blocks(&rsrc_extents);
                    // A fork fragmented past three extents keeps the rest in the overflow tree.
                    overflow_changed |= self.free_fork_overflow(cnid, 0x00)?;
                    overflow_changed |= self.free_fork_overflow(cnid, 0xFF)?;
                }
            }

            self.remove_catalog_record(node_idx, rec_idx)?;

            // Find and remove the thread record
            if let Some((t_node, t_rec, _)) = self.find_catalog_record_by_cnid(cnid) {
                self.remove_catalog_record(t_node, t_rec)?;
            }

            // Update parent valence
            self.update_parent_valence(parent_id, -1)?;

            // Update MDB counts
            if entry.is_directory() {
                self.mdb.folder_count = self.mdb.folder_count.saturating_sub(1);
            } else {
                self.mdb.file_count = self.mdb.file_count.saturating_sub(1);
            }

            if overflow_changed {
                self.write_extents_overflow_back()?;
            }

            Ok(())
        })();
        if result.is_err() {
            self.extents_overflow_data = extents_before;
            self.restore_snapshot(snap);
        }
        result
    }

    fn rename(
        &mut self,
        parent: &FileEntry,
        entry: &FileEntry,
        new_name: &str,
    ) -> Result<(), FilesystemError> {
        if new_name == entry.name {
            return Ok(());
        }
        let parent_id = parent.location as u32;
        let cnid = entry.location as u32;
        let new_name_raw = validate_hfs_create_name(new_name)?;
        let old_name_raw = utf8_to_mac_roman(&entry.name)?;

        let snap = self.snapshot();
        let result = (|| -> Result<(), FilesystemError> {
            // Locate the entry's catalog record by its current (parent, name) key.
            let (node_idx, rec_idx, _key_abs) = self
                .find_catalog_record_by_name(parent_id, &old_name_raw)
                .ok_or_else(|| {
                    FilesystemError::NotFound(format!(
                        "entry '{}' not found in catalog",
                        entry.name
                    ))
                })?;

            // Reject a collision only with a DIFFERENT record. HFS folds case, so
            // a case-only rename resolves back to this same record (allowed).
            if let Some((n2, r2, _)) = self.find_catalog_record_by_name(parent_id, &new_name_raw) {
                if (n2, r2) != (node_idx, rec_idx) {
                    return Err(FilesystemError::AlreadyExists(new_name.to_string()));
                }
            }

            // Extract the record's data body to re-emit it verbatim under the new
            // key (the CNID and all fork/Finder data are unchanged).
            let node_size = BigEndian::read_u16(&self.catalog_data[32..34]) as usize;
            let node_off = node_idx as usize * node_size;
            let node = &self.catalog_data[node_off..node_off + node_size];
            let (rec_start, rec_end) = hfs_common::btree_record_range(node, node_size, rec_idx);
            let key_len = node[rec_start] as usize;
            let mut data_rel = 1 + key_len;
            if !data_rel.is_multiple_of(2) {
                data_rel += 1;
            }
            let data_bytes = node[rec_start + data_rel..rec_end].to_vec();

            let mut new_record = Self::build_catalog_key(parent_id, &new_name_raw);
            if !new_record.len().is_multiple_of(2) {
                new_record.push(0);
            }
            new_record.extend_from_slice(&data_bytes);
            if !new_record.len().is_multiple_of(2) {
                new_record.push(0);
            }

            self.remove_catalog_record(node_idx, rec_idx)?;
            self.insert_catalog_record(&new_record)?;

            // Rewrite the thread record's `thdCName` (fixed Str31 at data +14, so
            // the record footprint is unchanged — safe to patch in place).
            // Directories always have a thread; files may not.
            if let Some((_n, _r, t_key_abs)) = self.find_catalog_record_by_cnid(cnid) {
                let t_key_len = self.catalog_data[t_key_abs] as usize;
                let mut t_data_off = t_key_abs + 1 + t_key_len;
                if !t_data_off.is_multiple_of(2) {
                    t_data_off += 1;
                }
                if t_data_off + 15 + 31 <= self.catalog_data.len() {
                    self.catalog_data[t_data_off + 14] = new_name_raw.len() as u8;
                    for i in 0..31 {
                        self.catalog_data[t_data_off + 15 + i] = 0;
                    }
                    self.catalog_data[t_data_off + 15..t_data_off + 15 + new_name_raw.len()]
                        .copy_from_slice(&new_name_raw);
                }
            }
            // A same-parent rename leaves parent valence and MDB counts unchanged.
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    fn set_type_creator(
        &mut self,
        entry: &FileEntry,
        type_code: &str,
        creator_code: &str,
    ) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let result = (|| {
            let frec_start = self.locate_record_data(entry.location as u32)?;
            if self.catalog_data[frec_start] as i8 != CATALOG_FILE {
                return Err(FilesystemError::InvalidData(
                    "set_type_creator: not a file record".into(),
                ));
            }

            // Write type at FInfo+0 (rec offset 4), creator at FInfo+4 (rec offset 8)
            let tc = hfs_common::encode_fourcc(type_code);
            let cc = hfs_common::encode_fourcc(creator_code);
            self.catalog_data[frec_start + 4..frec_start + 8].copy_from_slice(&tc);
            self.catalog_data[frec_start + 8..frec_start + 12].copy_from_slice(&cc);

            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    fn write_resource_fork(
        &mut self,
        entry: &FileEntry,
        data: &mut dyn std::io::Read,
        len: u64,
    ) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let extents_before = self.extents_overflow_data.clone();
        let result = (|| {
            let cnid = entry.location as u32;

            // Free existing resource fork blocks, overflow records included
            let mut overflow_changed = false;
            if let Some((_, _, _, rsrc_extents)) = self.find_file_by_id(cnid) {
                self.free_extent_blocks(&rsrc_extents);
                overflow_changed = self.free_fork_overflow(cnid, 0xFF)?;
            }

            // Allocate and write new resource fork
            let rsrc_extents = self.write_data_to_blocks(data, len)?;

            let frec_start = self.locate_record_data(cnid)?;
            if self.catalog_data[frec_start] as i8 != CATALOG_FILE {
                return Err(FilesystemError::InvalidData(
                    "write_resource_fork: not a file record".into(),
                ));
            }

            // Update rsrc fork fields in file record. filRStBlk (offset 34)
            // stays 0 — it's the File Manager's in-memory cache, not persisted;
            // a non-zero on-disk value makes fsck_hfs report "Reserved fields
            // in the catalog record have incorrect data". The real location is
            // the rsrc extent record at offset 86 (written below).
            self.catalog_data[frec_start + 34..frec_start + 36].fill(0);
            // filRLgLen at offset 36
            BigEndian::write_u32(
                &mut self.catalog_data[frec_start + 36..frec_start + 40],
                len as u32,
            );
            // filRPyLen at offset 40
            BigEndian::write_u32(
                &mut self.catalog_data[frec_start + 40..frec_start + 44],
                Self::extents_block_total(&rsrc_extents) as u32 * self.mdb.block_size,
            );
            // Rsrc extents at offset 86; a fourth extent on goes to the overflow tree.
            Self::set_inline_extents(
                &mut self.catalog_data[frec_start..frec_start + 102],
                86,
                &rsrc_extents,
            );
            overflow_changed |= self.insert_fork_overflow(cnid, 0xFF, &rsrc_extents)?;

            if overflow_changed {
                self.write_extents_overflow_back()?;
            }

            Ok(())
        })();
        if result.is_err() {
            self.extents_overflow_data = extents_before;
            self.restore_snapshot(snap);
        }
        result
    }

    fn repair(&mut self) -> Result<disk_core::fsck::RepairReport, FilesystemError> {
        self.ensure_bitmap()?;
        let mut extents_data = if self.mdb.extents_file_size > 0 {
            read_fork_data(
                &mut self.reader,
                self.partition_offset,
                &self.mdb,
                &self.mdb.extents_file_extents,
                self.mdb.extents_file_size as u64,
            )
            .ok()
        } else {
            None
        };

        let report = crate::hfs_fsck::repair_hfs(
            &mut self.mdb,
            &mut self.catalog_data,
            self.bitmap.as_mut().unwrap(),
            extents_data.as_mut(),
        );

        // Write back repaired extents overflow B-tree if modified
        if let Some(ref ext_data) = extents_data {
            if self.mdb.extents_file_size > 0 {
                write_extents_overflow_data(
                    &mut self.reader,
                    self.partition_offset,
                    &self.mdb,
                    ext_data,
                )?;
            }
        }

        self.do_sync_metadata()?;
        Ok(report)
    }

    fn sync_metadata(&mut self) -> Result<(), FilesystemError> {
        self.do_sync_metadata()
    }

    fn free_space(&mut self) -> Result<u64, FilesystemError> {
        Ok(self.mdb.free_blocks as u64 * self.mdb.block_size as u64)
    }

    fn set_blessed_folder(&mut self, entry: &FileEntry) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let result = (|| {
            if !entry.is_directory() {
                return Err(FilesystemError::InvalidData(
                    "can only bless a directory".into(),
                ));
            }
            self.mdb.finder_info[0] = entry.location as u32;
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    fn write_boot_blocks(&mut self, blocks: &[u8; 1024]) -> Result<(), FilesystemError> {
        HfsFilesystem::set_boot_blocks(self, blocks);
        Ok(())
    }

    fn set_volume_name(&mut self, new_name: &str) -> Result<(), FilesystemError> {
        HfsFilesystem::set_volume_name(self, new_name)
    }

    fn set_finder_info(
        &mut self,
        entry: &FileEntry,
        finfo: [u8; 16],
        fxinfo: [u8; 16],
    ) -> Result<(), FilesystemError> {
        HfsFilesystem::set_finder_info(self, entry, finfo, fxinfo)
    }

    fn set_dates(
        &mut self,
        entry: &FileEntry,
        create: u32,
        modify: u32,
        backup: u32,
    ) -> Result<(), FilesystemError> {
        HfsFilesystem::set_dates(self, entry, create, modify, backup)
    }
}

/// Read fork data from the 3-extent descriptor array in the MDB.
/// Walk the extents-overflow B-tree leaf chain and collect every extent
/// record matching `(file_id, fork_type)` whose key startBlock is at or after
/// `min_start_block`. Returned in startBlock order (records appear in key
/// order on disk; we sort defensively in case of corruption).
fn collect_fork_overflow_extents(
    extents_data: &[u8],
    file_id: u32,
    fork_type: u8,
    min_start_block: u32,
) -> Vec<HfsExtDescriptor> {
    use crate::hfs_common::{btree_record_range, BTreeHeader, BTREE_LEAF_NODE};
    use std::collections::HashSet;

    let mut out: Vec<(u16, HfsExtDescriptor)> = Vec::new();
    if extents_data.len() < 512 {
        return Vec::new();
    }
    let header = BTreeHeader::read(extents_data);
    let node_size = header.node_size as usize;
    if node_size == 0 || extents_data.len() < node_size {
        return Vec::new();
    }

    let mut node_idx = header.first_leaf_node;
    let mut visited: HashSet<u32> = HashSet::new();
    while node_idx != 0 {
        if !visited.insert(node_idx) {
            break;
        }
        let off = node_idx as usize * node_size;
        if off + node_size > extents_data.len() {
            break;
        }
        let node = &extents_data[off..off + node_size];
        let flink = BigEndian::read_u32(&node[0..4]);
        let kind = node[8] as i8;
        if kind != BTREE_LEAF_NODE {
            break;
        }
        let num_records = BigEndian::read_u16(&node[10..12]) as usize;
        for i in 0..num_records {
            let (rec_start, _) = btree_record_range(node, node_size, i);
            if rec_start + 8 > node_size {
                continue;
            }
            let key_len = node[rec_start] as usize;
            if key_len < 7 || rec_start + 1 + key_len > node_size {
                continue;
            }
            let rec_fork_type = node[rec_start + 1];
            let rec_file_id = BigEndian::read_u32(&node[rec_start + 2..rec_start + 6]);
            let rec_start_block = BigEndian::read_u16(&node[rec_start + 6..rec_start + 8]);
            if rec_fork_type != fork_type || rec_file_id != file_id {
                continue;
            }
            if (rec_start_block as u32) < min_start_block {
                continue;
            }
            let mut data_off = rec_start + 1 + key_len;
            if !data_off.is_multiple_of(2) {
                data_off += 1;
            }
            if data_off + 12 > node_size {
                continue;
            }
            for j in 0..3 {
                let ext = HfsExtDescriptor::parse(&node[data_off + j * 4..data_off + j * 4 + 4]);
                if ext.block_count > 0 {
                    out.push((rec_start_block, ext));
                }
            }
        }
        node_idx = flink;
    }

    out.sort_by_key(|(sb, _)| *sb);
    out.into_iter().map(|(_, e)| e).collect()
}

fn read_fork_data<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
    mdb: &HfsMasterDirectoryBlock,
    extents: &[HfsExtDescriptor; 3],
    size: u64,
) -> Result<Vec<u8>, FilesystemError> {
    let mut data = Vec::with_capacity(size as usize);
    let first_alloc_offset = partition_offset + mdb.first_alloc_block as u64 * 512;

    for ext in extents {
        if ext.block_count == 0 {
            break;
        }
        let offset = first_alloc_offset + ext.start_block as u64 * mdb.block_size as u64;
        let len = ext.block_count as u64 * mdb.block_size as u64;
        reader.seek(SeekFrom::Start(offset))?;
        let read_len = len.min(size - data.len() as u64) as usize;
        let mut buf = vec![0u8; read_len];
        reader.read_exact(&mut buf)?;
        data.extend_from_slice(&buf);
        if data.len() as u64 >= size {
            break;
        }
    }

    data.truncate(size as usize);
    Ok(data)
}

/// Remove every extents-overflow record of `(file_id, fork_type)`, freeing a
/// leaf that empties; returns the number of records removed.
fn remove_fork_overflow_records(
    extents_data: &mut [u8],
    file_id: u32,
    fork_type: u8,
) -> Result<u32, FilesystemError> {
    use crate::hfs_common::{
        btree_remove_record, btree_retire_empty_leaf, compare_classic_extents_keys,
        walk_leaf_records, BTreeHeader,
    };
    let kf = BTreeKeyFormat::CLASSIC_EXTENTS;
    if extents_data.len() < 512 {
        return Ok(0);
    }
    let header = BTreeHeader::read(extents_data);
    let node_size = header.node_size as usize;
    if node_size == 0 || extents_data.len() < node_size {
        return Ok(0);
    }
    let mut victims: Vec<(u32, usize)> = Vec::new();
    walk_leaf_records::<(), _>(
        extents_data,
        header.first_leaf_node,
        node_size,
        |node_idx, rec_idx, _off, rec| {
            // Key: keyLen(1) = 7, forkType(1), fileID(4), startBlock(2).
            if rec.len() >= 8
                && rec[0] >= 7
                && rec[1] == fork_type
                && BigEndian::read_u32(&rec[2..6]) == file_id
            {
                victims.push((node_idx, rec_idx));
            }
            None
        },
    );
    if victims.is_empty() {
        return Ok(0);
    }
    // Highest record index first per node, so earlier indices stay valid.
    victims.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
    for &(node_idx, rec_idx) in &victims {
        let off = node_idx as usize * node_size;
        btree_remove_record(&mut extents_data[off..off + node_size], node_size, rec_idx);
    }
    let mut h = BTreeHeader::read(extents_data);
    h.leaf_records = h.leaf_records.saturating_sub(victims.len() as u32);
    h.write(extents_data);
    let mut nodes: Vec<u32> = victims.iter().map(|v| v.0).collect();
    nodes.dedup();
    for node_idx in nodes {
        let off = node_idx as usize * node_size;
        if BigEndian::read_u16(&extents_data[off + 10..off + 12]) == 0 {
            // An emptied leaf leaves the chain, the node map and the index.
            btree_retire_empty_leaf(
                extents_data,
                node_size,
                node_idx,
                &kf,
                &compare_classic_extents_keys,
            )?;
        } else if victims.iter().any(|&(n, r)| n == node_idx && r == 0) {
            // The leaf's first key changed: the separators above must match it.
            btree_refresh_index_keys(
                extents_data,
                node_size,
                node_idx,
                &kf,
                &compare_classic_extents_keys,
            )?;
        }
    }
    Ok(victims.len() as u32)
}

/// Write the extents-overflow B-tree back over the extents file's blocks.
fn write_extents_overflow_data<W: std::io::Write + Seek>(
    writer: &mut W,
    partition_offset: u64,
    mdb: &HfsMasterDirectoryBlock,
    data: &[u8],
) -> Result<(), FilesystemError> {
    let alloc_start = partition_offset + mdb.first_alloc_block as u64 * 512;
    let mut data_start = 0usize;
    for extent in mdb.extents_file_extents.iter() {
        if extent.block_count == 0 {
            break;
        }
        let block_off = alloc_start + extent.start_block as u64 * mdb.block_size as u64;
        let byte_len = extent.block_count as usize * mdb.block_size as usize;
        let data_end = (data_start + byte_len).min(data.len());
        if data_start < data_end {
            writer.seek(std::io::SeekFrom::Start(block_off))?;
            writer.write_all(&data[data_start..data_end])?;
        }
        data_start += byte_len;
    }
    Ok(())
}

/// Stream fork data through inline extents to a writer. Returns bytes written.
fn write_fork_data_to<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
    mdb: &HfsMasterDirectoryBlock,
    extents: &[HfsExtDescriptor; 3],
    writer: &mut dyn std::io::Write,
    size: u64,
) -> Result<u64, FilesystemError> {
    let first_alloc_offset = partition_offset + mdb.first_alloc_block as u64 * 512;
    let mut written: u64 = 0;
    let mut buf = vec![0u8; 64 * 1024];

    for ext in extents {
        if ext.block_count == 0 || written >= size {
            break;
        }
        let offset = first_alloc_offset + ext.start_block as u64 * mdb.block_size as u64;
        let extent_len = ext.block_count as u64 * mdb.block_size as u64;
        let to_emit = extent_len.min(size - written);
        reader.seek(SeekFrom::Start(offset))?;
        let mut left = to_emit;
        while left > 0 {
            let n = (buf.len() as u64).min(left) as usize;
            reader.read_exact(&mut buf[..n])?;
            writer.write_all(&buf[..n])?;
            left -= n as u64;
        }
        written += to_emit;
    }
    Ok(written)
}

/// Write fork data to disk through extent descriptors.
fn write_hfs_fork_data<R: Write + Seek>(
    writer: &mut R,
    partition_offset: u64,
    mdb: &HfsMasterDirectoryBlock,
    extents: &[HfsExtDescriptor; 3],
    data: &[u8],
) -> Result<(), FilesystemError> {
    let first_alloc_offset = partition_offset + mdb.first_alloc_block as u64 * 512;
    let mut written = 0usize;
    for ext in extents {
        if ext.block_count == 0 || written >= data.len() {
            break;
        }
        let offset = first_alloc_offset + ext.start_block as u64 * mdb.block_size as u64;
        let extent_len = ext.block_count as u64 * mdb.block_size as u64;
        let to_write = extent_len.min((data.len() - written) as u64) as usize;
        writer.seek(SeekFrom::Start(offset))?;
        writer.write_all(&data[written..written + to_write])?;
        written += to_write;
    }
    Ok(())
}

/// Find the index of the last set bit in a bitmap (MSB-first).
fn find_last_set_bit(bitmap: &[u8], max_bits: u32) -> Option<u32> {
    let mut last = None;
    for bit in 0..max_bits {
        let byte_idx = bit as usize / 8;
        let bit_idx = 7 - (bit % 8); // MSB-first
        if byte_idx < bitmap.len() && (bitmap[byte_idx] >> bit_idx) & 1 == 1 {
            last = Some(bit);
        }
    }
    last
}

/// Compact reader for classic HFS: layout-preserving image with zeros for free blocks.
///
/// Outputs the full pre-allocation region (boot blocks + MDB + volume bitmap,
/// `first_alloc_block * 512` bytes) followed by all allocation blocks in order,
/// with free blocks replaced by zeros. This preserves the original block layout:
/// allocation block N is always at byte offset `first_alloc_block*512 + N*block_size`,
/// enabling correct filesystem browsing and reliable restore.
pub struct CompactHfsReader<R: Read + Seek> {
    reader: R,
    partition_offset: u64,
    mdb: HfsMasterDirectoryBlock,
    bitmap: Vec<u8>,
    /// Current phase: 0=pre-alloc region, 1=allocation blocks, 2=done.
    phase: u8,
    /// Byte position within the pre-alloc region (phase 0).
    pre_alloc_pos: u64,
    /// Current allocation block index (phase 1).
    current_block: u32,
    /// Byte position within the current allocation block (phase 1).
    block_pos: u64,
    #[allow(dead_code)]
    original_size: u64,
    #[allow(dead_code)]
    allocated_blocks: u32,
}

impl<R: Read + Seek> CompactHfsReader<R> {
    pub fn new(
        mut reader: R,
        partition_offset: u64,
    ) -> Result<(Self, CompactResult), FilesystemError> {
        // Read MDB
        log::debug!(
            "[HFS compact] seeking to MDB at offset {}",
            partition_offset + 1024
        );
        reader.seek(SeekFrom::Start(partition_offset + 1024))?;
        let mut mdb_buf = [0u8; 162];
        reader.read_exact(&mut mdb_buf)?;
        let mdb = HfsMasterDirectoryBlock::parse(&mdb_buf).map_err(|e| {
            log::debug!("[HFS compact] MDB parse failed: {e}");
            e
        })?;
        log::debug!(
            "[HFS compact] MDB ok: block_size={}, total_blocks={}, first_alloc_block={}, volume_bitmap_block={}",
            mdb.block_size, mdb.total_blocks, mdb.first_alloc_block, mdb.volume_bitmap_block,
        );

        if mdb.has_embedded_hfs_plus() {
            log::debug!("[HFS compact] has embedded HFS+ — refusing to compact HFS wrapper");
            return Err(FilesystemError::Unsupported(
                "cannot compact HFS wrapper with embedded HFS+".into(),
            ));
        }

        // Read volume bitmap
        let bitmap_offset = partition_offset + mdb.volume_bitmap_block as u64 * 512;
        log::debug!("[HFS compact] reading bitmap at offset {bitmap_offset}");
        let bitmap_size = (mdb.total_blocks as u32).div_ceil(8) as usize;
        reader.seek(SeekFrom::Start(bitmap_offset))?;
        let mut bitmap = vec![0u8; bitmap_size];
        reader.read_exact(&mut bitmap)?;
        log::debug!("[HFS compact] bitmap read: {bitmap_size} bytes");

        // Count allocated blocks
        let mut allocated = 0u32;
        for bit in 0..mdb.total_blocks as u32 {
            let byte_idx = bit as usize / 8;
            let bit_idx = 7 - (bit % 8);
            if byte_idx < bitmap.len() && (bitmap[byte_idx] >> bit_idx) & 1 == 1 {
                allocated += 1;
            }
        }
        log::debug!(
            "[HFS compact] allocated={} / {} total blocks ({} free)",
            allocated,
            mdb.total_blocks,
            mdb.total_blocks as u32 - allocated,
        );

        // Full partition data: pre-alloc region + all allocation blocks.
        let pre_alloc_size = mdb.first_alloc_block as u64 * 512;
        let original_size = pre_alloc_size + mdb.total_blocks as u64 * mdb.block_size as u64;
        // Layout-preserving: compacted_size == original_size.
        // Free allocation blocks are zeroed, so they compress extremely well.
        let compacted_size = original_size;
        // data_size: pre-alloc is always read from disk; only allocated alloc blocks are read.
        let data_size = pre_alloc_size + allocated as u64 * mdb.block_size as u64;
        log::debug!(
            "[HFS compact] pre_alloc_size={}, data_size={}, compacted_size={} original_size={} (layout-preserving; free blocks -> zeros)",
            pre_alloc_size, data_size, compacted_size, original_size
        );

        let result = CompactResult {
            original_size,
            compacted_size,
            data_size,
            clusters_used: allocated,
        };

        Ok((
            CompactHfsReader {
                reader,
                partition_offset,
                mdb,
                bitmap,
                phase: 0,
                pre_alloc_pos: 0,
                current_block: 0,
                block_pos: 0,
                original_size,
                allocated_blocks: allocated,
            },
            result,
        ))
    }

    fn is_block_allocated(&self, block: u32) -> bool {
        let byte_idx = block as usize / 8;
        let bit_idx = 7 - (block % 8);
        byte_idx < self.bitmap.len() && (self.bitmap[byte_idx] >> bit_idx) & 1 == 1
    }
}

impl<R: Read + Seek> Read for CompactHfsReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.phase > 1 {
            return Ok(0);
        }

        if self.phase == 0 {
            // Phase 0: pre-alloc region (boot blocks, MDB, volume bitmap).
            // Covers sectors 0..first_alloc_block — always preserved verbatim.
            let pre_alloc_size = self.mdb.first_alloc_block as u64 * 512;
            let remaining = pre_alloc_size - self.pre_alloc_pos;
            if remaining == 0 {
                self.phase = 1;
                return self.read(buf);
            }
            let to_read = (remaining as usize).min(buf.len());
            let offset = self.partition_offset + self.pre_alloc_pos;
            self.reader
                .seek(SeekFrom::Start(offset))
                .map_err(disk_core::io_other)?;
            let n = self.reader.read(&mut buf[..to_read])?;
            self.pre_alloc_pos += n as u64;
            return Ok(n);
        }

        // Phase 1: allocation blocks 0..total_blocks.
        // Allocated blocks -> real data; free blocks -> zeros.
        let total_blocks = self.mdb.total_blocks as u32;
        if self.current_block >= total_blocks {
            self.phase = 2;
            return Ok(0);
        }

        let block_size = self.mdb.block_size as u64;

        // Coalesce the longest run starting at current_block whose
        // allocation state matches. Each per-block seek + read on a
        // slow source media (SD card) costs milliseconds; this turns
        // O(blocks) syscalls into O(extents).
        let allocated = self.is_block_allocated(self.current_block);
        let mut run_end = self.current_block + 1;
        while run_end < total_blocks && self.is_block_allocated(run_end) == allocated {
            run_end += 1;
        }
        let bytes_in_run = (run_end - self.current_block) as u64 * block_size - self.block_pos;
        let to_read = (bytes_in_run as usize).min(buf.len());

        let n = if allocated {
            let offset = self.partition_offset
                + self.mdb.first_alloc_block as u64 * 512
                + self.current_block as u64 * block_size
                + self.block_pos;
            self.reader
                .seek(SeekFrom::Start(offset))
                .map_err(disk_core::io_other)?;
            self.reader.read(&mut buf[..to_read])?
        } else {
            // Free run — emit zeros so free space compresses to nothing.
            buf[..to_read].fill(0);
            to_read
        };

        // Advance cursor (current_block + block_pos) by `n` bytes.
        let mut remaining_in_n = n as u64;
        if self.block_pos > 0 {
            let want = block_size - self.block_pos;
            let take = remaining_in_n.min(want);
            self.block_pos += take;
            remaining_in_n -= take;
            if self.block_pos >= block_size {
                self.block_pos = 0;
                self.current_block += 1;
            }
        }
        let whole = (remaining_in_n / block_size) as u32;
        self.current_block += whole;
        remaining_in_n -= whole as u64 * block_size;
        if remaining_in_n > 0 {
            self.block_pos = remaining_in_n;
        }

        Ok(n)
    }
}

// --- Resize and validation functions ---

/// Resize an HFS filesystem in place.
/// Probe a classic HFS volume and return the maximum size (bytes) it can be
/// grown to in-place, given its allocation block size and Volume Bitmap
/// capacity. Returns `None` if the partition doesn't start with a valid HFS
/// MDB (e.g. it's HFS+, HFSX, or something else).
///
/// The ceiling is `min(65535 blocks, VBM bit capacity) * block_size + overhead`.
/// Growing beyond this requires reformatting with a larger block size.
/// Grow a classic HFS volume to fill its partition (R-058). Mac OS reads the
/// alternate MDB two sectors before the partition end and expects the
/// allocation area to end there, so a smaller volume fails Disk First Aid
/// however its headers are placed. Returns whether the volume was grown.
pub fn fit_hfs_volume_to_partition(
    device: &mut (impl Read + Write + Seek),
    partition_offset: u64,
    partition_len: u64,
    log: &mut impl FnMut(&str),
) -> anyhow::Result<bool> {
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    let mut sector = [0u8; 512];
    device.read_exact(&mut sector)?;
    if BigEndian::read_u16(&sector[0..2]) != HFS_SIGNATURE {
        return Ok(false);
    }
    // A wrapper's embedded HFS+ volume keeps its own headers; leave it alone.
    if BigEndian::read_u16(&sector[0x7C..0x7E]) == 0x482B {
        return Ok(false);
    }
    let total_blocks = BigEndian::read_u16(&sector[0x12..0x14]) as u64;
    let block_size = BigEndian::read_u32(&sector[0x14..0x18]) as u64;
    let first_alloc = BigEndian::read_u16(&sector[0x1C..0x1E]) as u64;
    let volume_len = first_alloc * 512 + total_blocks * block_size + 1024;
    if block_size == 0 || volume_len >= partition_len {
        return Ok(false);
    }
    let growable = hfs_max_growable_size(device, partition_offset).unwrap_or(0);
    if growable < partition_len {
        log(&format!(
            "Warning: the HFS volume ({volume_len} bytes) does not fill its {partition_len}-byte \
             partition and its volume bitmap cannot address more blocks; Disk First Aid will \
             report an invalid allocation block start. Format the volume at the partition size"
        ));
        return Ok(false);
    }
    resize_hfs_in_place(device, partition_offset, partition_len, log)?;
    log(&format!(
        "HFS volume grown from {volume_len} bytes to fill its {partition_len}-byte partition"
    ));
    Ok(true)
}

pub fn hfs_max_growable_size(
    device: &mut (impl Read + Seek),
    partition_offset: u64,
) -> Option<u64> {
    device.seek(SeekFrom::Start(partition_offset + 1024)).ok()?;
    let mut sector = [0u8; 512];
    device.read_exact(&mut sector).ok()?;

    let sig = BigEndian::read_u16(&sector[0..2]);
    if sig != HFS_SIGNATURE {
        return None;
    }

    let block_size = BigEndian::read_u32(&sector[20..24]) as u64;
    let vbm_start = BigEndian::read_u16(&sector[14..16]) as u64;
    let first_alloc = BigEndian::read_u16(&sector[28..30]) as u64;

    if block_size == 0 || first_alloc <= vbm_start {
        return None;
    }

    let vbm_capacity = (first_alloc - vbm_start) * 512 * 8;
    let max_blocks = vbm_capacity.min(u16::MAX as u64);
    // Plus the alternate MDB and the trailing sector the allocation area stops short of.
    let overhead = first_alloc * 512 + 1024;

    Some(max_blocks * block_size + overhead)
}

pub fn resize_hfs_in_place(
    device: &mut (impl Read + Write + Seek),
    partition_offset: u64,
    new_size_bytes: u64,
    log: &mut impl FnMut(&str),
) -> anyhow::Result<()> {
    // Read MDB sector (512-byte aligned I/O for raw device compatibility)
    // The MDB is at partition_offset + 1024 and is 162 bytes, but we read/write
    // a full 512-byte sector to satisfy raw device alignment requirements.
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    let mut sector = [0u8; 512];
    device.read_exact(&mut sector)?;

    let sig = BigEndian::read_u16(&sector[0..2]);
    if sig != HFS_SIGNATURE {
        log("HFS resize: not an HFS volume, skipping");
        return Ok(());
    }

    let block_size = BigEndian::read_u32(&sector[20..24]);
    let old_total = BigEndian::read_u16(&sector[18..20]);
    let free_blocks = BigEndian::read_u16(&sector[34..36]);
    let vbm_start = BigEndian::read_u16(&sector[14..16]);
    let first_alloc = BigEndian::read_u16(&sector[28..30]);
    let used_blocks = old_total - free_blocks;

    // Volume Bitmap lives in sectors [vbm_start, first_alloc) and holds 1 bit
    // per allocation block. If new_total exceeds that bit capacity, the OS
    // would walk allocation blocks not represented in the VBM.
    let vbm_capacity_blocks = if first_alloc > vbm_start {
        (first_alloc - vbm_start) as u64 * 512 * 8
    } else {
        0
    };

    // The alternate MDB and the unused sector after it stay outside the
    // allocation area, as the formatter lays them out (R-059).
    let overhead = first_alloc as u64 * 512 + 1024;
    if new_size_bytes <= overhead {
        anyhow::bail!(
            "HFS resize: new size {} bytes <= overhead {} bytes",
            new_size_bytes,
            overhead
        );
    }
    let new_total_u64 = (new_size_bytes - overhead) / block_size as u64;

    // drNmAlBlks is a u16 — 65535 allocation blocks is the hard HFS ceiling.
    // Silently truncating here would write a bogus block count to the MDB.
    if new_total_u64 > u16::MAX as u64 {
        let max_bytes = u16::MAX as u64 * block_size as u64 + overhead;
        anyhow::bail!(
            "HFS resize: requested size {} MB needs {} allocation blocks at {}-byte blocks, \
             but HFS caps at 65535 blocks (max {} MB for this volume). \
             Growing further would require reformatting with a larger allocation block size.",
            new_size_bytes / 1024 / 1024,
            new_total_u64,
            block_size,
            max_bytes / 1024 / 1024,
        );
    }
    if new_total_u64 > vbm_capacity_blocks {
        anyhow::bail!(
            "HFS resize: requested {} allocation blocks exceeds the Volume Bitmap capacity \
             ({} blocks) for this volume. The VBM lives in fixed sectors [{}..{}) and cannot \
             be grown without reformatting: the most this volume can grow to is {} bytes. \
             Mac OS wants a classic HFS volume to fill its partition, so format one at the \
             partition size instead (`new volume hfs --size`, then `new hd --fill`).",
            new_total_u64,
            vbm_capacity_blocks,
            vbm_start,
            first_alloc,
            vbm_capacity_blocks.min(u16::MAX as u64) * block_size as u64 + overhead,
        );
    }
    let new_total = new_total_u64 as u16;

    // A count says nothing about position: a volume with free blocks near the
    // front still has data at its tail, and cutting there loses it.
    let vbm_len = (first_alloc - vbm_start) as usize * 512;
    let mut vbm = vec![0u8; vbm_len];
    device.seek(SeekFrom::Start(partition_offset + vbm_start as u64 * 512))?;
    device.read_exact(&mut vbm)?;
    let highest_used = find_last_set_bit(&vbm, old_total as u32).map_or(0, |b| b + 1);
    if (new_total as u32) < highest_used {
        anyhow::bail!(
            "HFS resize: new size {} blocks ends before the last allocated block ({}); \
             {} of {} blocks are in use",
            new_total,
            highest_used,
            used_blocks,
            old_total
        );
    }
    // Blocks the volume gains, or gives up, read as free rather than as
    // whatever the bits past the old count held.
    for b in old_total.min(new_total) as u32..old_total.max(new_total) as u32 {
        bitmap_clear_bit_be(&mut vbm, b);
    }
    device.seek(SeekFrom::Start(partition_offset + vbm_start as u64 * 512))?;
    device.write_all(&vbm)?;

    let new_free = new_total - used_blocks;

    log(&format!(
        "HFS resize: {} -> {} blocks ({} free)",
        old_total, new_total, new_free
    ));

    // Update MDB fields in the sector buffer
    BigEndian::write_u16(&mut sector[18..20], new_total);
    BigEndian::write_u16(&mut sector[34..36], new_free);

    // Write primary MDB sector at offset + 1024
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    device.write_all(&sector)?;

    // Write backup MDB sector at offset + new_size - 1024
    if new_size_bytes > 1024 {
        device.seek(SeekFrom::Start(partition_offset + new_size_bytes - 1024))?;
        device.write_all(&sector)?;
    }

    device.flush()?;
    Ok(())
}

/// Validate HFS filesystem integrity.
pub fn validate_hfs_integrity(
    device: &mut (impl Read + Seek),
    partition_offset: u64,
    log: &mut impl FnMut(&str),
) -> anyhow::Result<()> {
    // Read MDB sector (512-byte aligned I/O for raw device compatibility)
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    let mut sector = [0u8; 512];
    device.read_exact(&mut sector)?;

    let sig = BigEndian::read_u16(&sector[0..2]);
    if sig != HFS_SIGNATURE {
        log("HFS validate: not an HFS volume, skipping");
        return Ok(());
    }

    let block_size = BigEndian::read_u32(&sector[20..24]);
    let total_blocks = BigEndian::read_u16(&sector[18..20]);

    // Basic sanity checks
    if !block_size.is_power_of_two() || block_size < 512 {
        anyhow::bail!("HFS validate: invalid block size {block_size}");
    }
    if total_blocks == 0 {
        anyhow::bail!("HFS validate: zero total blocks");
    }

    log(&format!(
        "HFS validate: OK ({total_blocks} blocks, {} block size)",
        block_size
    ));
    Ok(())
}

#[cfg(test)]
#[allow(clippy::identity_op)] // `1 * 1024 * 1024` reads as "1 MB" in size tables
mod tests {
    use super::*;
    use std::io::Cursor;

    /// The streaming and in-memory blank formatters must agree byte for byte —
    /// the streaming one only skips writing the free middle, which reads back
    /// as zeros from a `set_len`'d file.
    #[test]
    fn write_blank_hfs_into_matches_create_blank_hfs() {
        let (size, bs) = (8 * 1024 * 1024u64, 4096u32);
        let now = 0xB0A1_2345;
        let mem = create_blank_hfs_sized_at(size, bs, "StreamEq", 0, 0, now).unwrap();

        let mut sink = Cursor::new(vec![0u8; 0]);
        let written = write_blank_hfs_into_at(&mut sink, 0, size, bs, "StreamEq", now).unwrap();
        let mut streamed = sink.into_inner();
        streamed.resize(written as usize, 0);

        assert_eq!(written as usize, mem.len());
        assert_eq!(streamed, mem);
    }

    /// The same at a non-zero offset, which is how the Mac CD-ROM builder lays
    /// the volume inside its `Apple_HFS` partition.
    #[test]
    fn write_blank_hfs_into_honours_the_offset() {
        let (size, bs) = (4 * 1024 * 1024u64, 2048u32);
        let now = 0xB0A1_2345;
        let mem = create_blank_hfs_sized_at(size, bs, "Offset", 0, 0, now).unwrap();

        let offset = 64 * 512u64;
        let mut sink = Cursor::new(vec![0u8; 0]);
        let written = write_blank_hfs_into_at(&mut sink, offset, size, bs, "Offset", now).unwrap();
        let mut streamed = sink.into_inner();
        streamed.resize((offset + written) as usize, 0);

        assert!(streamed[..offset as usize].iter().all(|&b| b == 0));
        assert_eq!(&streamed[offset as usize..], &mem[..]);
    }

    #[test]
    fn test_mac_roman_to_utf8_ascii() {
        let data = b"Hello World";
        assert_eq!(mac_roman_to_utf8(data), "Hello World");
    }

    #[test]
    fn test_mac_roman_to_utf8_special() {
        // 0x80 = Ä, 0x81 = Å, 0x87 = á
        let data = [0x80, 0x81, 0x87];
        assert_eq!(mac_roman_to_utf8(&data), "ÄÅá");
    }

    #[test]
    fn test_decode_mac_filename_utf8() {
        // "HeapFixer" + UTF-8 ™ (E2 84 A2) + " 1.01" — a re-packed archive
        // whose name is already UTF-8. Must NOT be re-decoded as Mac Roman.
        let mut data = b"HeapFixer".to_vec();
        data.extend_from_slice(&[0xE2, 0x84, 0xA2]);
        data.extend_from_slice(b" 1.01");
        assert_eq!(decode_mac_filename(&data), "HeapFixer™ 1.01");
    }

    #[test]
    fn test_decode_mac_filename_macroman() {
        // Genuine Mac Roman names: 0xC4 = ƒ, 0xA5 = •, 0xA8 = ®. These are lone
        // high bytes (invalid standalone UTF-8) so they take the Mac Roman path.
        assert_eq!(decode_mac_filename(&[0xC4]), "ƒ");
        assert_eq!(decode_mac_filename(b"Cache\xA5Flow"), "Cache•Flow");
        assert_eq!(decode_mac_filename(b"Virex\xA8 3.51"), "Virex® 3.51");
    }

    #[test]
    fn test_decode_mac_filename_ascii() {
        assert_eq!(decode_mac_filename(b"ScriptEdit"), "ScriptEdit");
    }

    #[test]
    fn test_format_ostype() {
        // High Mac Roman byte in a creator code must render as its glyph, not �.
        assert_eq!(format_ostype(&[b'S', 0xA5, b'L', b' ']), "S•L");
        assert_eq!(format_ostype(b"APPL"), "APPL");
        // Trailing NUL/space padding is trimmed.
        assert_eq!(format_ostype(&[b'L', b's', 0x00, 0x00]), "Ls");
    }

    #[test]
    fn test_mdb_parse() {
        let mut data = [0u8; 162];
        // Signature
        BigEndian::write_u16(&mut data[0..2], HFS_SIGNATURE);
        // total_blocks
        BigEndian::write_u16(&mut data[18..20], 1000);
        // block_size
        BigEndian::write_u32(&mut data[20..24], 4096);
        // free_blocks
        BigEndian::write_u16(&mut data[34..36], 200);
        // volume name: Pascal string "TestVol"
        data[36] = 7;
        data[37..44].copy_from_slice(b"TestVol");

        let mdb = HfsMasterDirectoryBlock::parse(&data).unwrap();
        assert_eq!(mdb.signature, HFS_SIGNATURE);
        assert_eq!(mdb.total_blocks, 1000);
        assert_eq!(mdb.block_size, 4096);
        assert_eq!(mdb.free_blocks, 200);
        assert_eq!(mdb.volume_name, "TestVol");
        assert!(!mdb.has_embedded_hfs_plus());
    }

    #[test]
    fn test_mdb_detect_embedded_hfs_plus() {
        let mut data = [0u8; 162];
        BigEndian::write_u16(&mut data[0..2], HFS_SIGNATURE);
        BigEndian::write_u16(&mut data[18..20], 1000);
        BigEndian::write_u32(&mut data[20..24], 4096);
        // Embedded HFS+ signature
        BigEndian::write_u16(&mut data[124..126], HFS_PLUS_EMBEDDED_SIGNATURE);
        BigEndian::write_u16(&mut data[126..128], 10); // start
        BigEndian::write_u16(&mut data[128..130], 500); // count

        let mdb = HfsMasterDirectoryBlock::parse(&data).unwrap();
        assert!(mdb.has_embedded_hfs_plus());
    }

    #[test]
    fn test_find_last_set_bit() {
        let bitmap = [0b10100000, 0b00001000]; // bits 0, 2, 12
        assert_eq!(find_last_set_bit(&bitmap, 16), Some(12));

        let bitmap_empty = [0u8; 2];
        assert_eq!(find_last_set_bit(&bitmap_empty, 16), None);

        let bitmap_first = [0b10000000]; // bit 0
        assert_eq!(find_last_set_bit(&bitmap_first, 8), Some(0));
    }

    #[test]
    fn test_utf8_to_mac_roman_roundtrip() {
        let text = "Hello World";
        let mac = utf8_to_mac_roman(text).unwrap();
        assert_eq!(mac, b"Hello World");
        assert_eq!(mac_roman_to_utf8(&mac), text);
    }

    #[test]
    fn test_utf8_to_mac_roman_special() {
        let text = "Ä"; // U+00C4 => Mac Roman 0x80
        let mac = utf8_to_mac_roman(text).unwrap();
        assert_eq!(mac, &[0x80]);
        assert_eq!(mac_roman_to_utf8(&mac), text);
    }

    #[test]
    fn test_utf8_to_mac_roman_unencodable() {
        let text = "\u{4E2D}"; // Chinese character — not in Mac Roman
        assert!(utf8_to_mac_roman(text).is_err());
    }

    /// H13: the shrink guard compared block counts, so a volume with free
    /// space at its front and one file at its tail could be cut through.
    /// H10: classic HFS keeps wall-clock local time, but stamps went out as
    /// UTC and came back shifted by the zone offset on every read.
    #[test]
    fn classic_hfs_stamps_are_local_time_and_round_trip_to_utc() {
        use disk_core::filesystem::{CreateFileOptions, EditableFilesystem, Filesystem};
        use disk_core::times::{local_utc_offset_secs, unix_to_mac_epoch, UnixTimes};
        const T: u64 = 1_700_000_000; // 2023-11-14 22:13:20 UTC
        let mut img = create_blank_hfs(4 * 1024 * 1024, 4096, "Zone").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(&mut img), 0).unwrap();
        let root = fs.root().unwrap();
        let opts = CreateFileOptions {
            unix_times: Some(UnixTimes::mtime_only(T)),
            ..Default::default()
        };
        fs.create_file(&root, "stamp", &mut &b"x"[..], 1, &opts)
            .unwrap();
        fs.sync_metadata().unwrap();
        let entry = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "stamp")
            .unwrap();
        assert_eq!(entry.modified_unix, Some(T), "UTC must round-trip");
        let raw = entry.mac_dates.expect("raw Mac dates").1;
        let expected = (T as i64 + local_utc_offset_secs()) as u64;
        assert_eq!(
            raw,
            unix_to_mac_epoch(expected),
            "on disk it is the local wall clock"
        );
    }

    /// H7: the alternate MDB was mirrored to the sector after the last
    /// allocation block; Mac OS and Disk First Aid read the partition's
    /// next-to-last sector, which differs whenever the blocks do not reach it.
    #[test]
    fn the_alternate_mdb_follows_the_partition_end_when_the_length_is_known() {
        use disk_core::filesystem::{CreateFileOptions, EditableFilesystem, Filesystem};
        const VOLUME: u64 = 8 * 1024 * 1024;
        const PARTITION: u64 = VOLUME + 64 * 1024;
        let mut img = create_blank_hfs(VOLUME, 4096, "Slack").unwrap();
        img.resize(PARTITION as usize, 0);
        {
            let mut fs =
                HfsFilesystem::open_sized(Cursor::new(&mut img), 0, Some(PARTITION)).unwrap();
            let root = fs.root().unwrap();
            fs.create_file(&root, "a", &mut &b"x"[..], 1, &CreateFileOptions::default())
                .unwrap();
            fs.sync_metadata().unwrap();
        }
        let primary = &img[1024..1536];
        let alt = &img[PARTITION as usize - 1024..PARTITION as usize - 512];
        assert_eq!(
            &alt[0..2],
            b"BD",
            "alternate MDB missing at the partition end"
        );
        assert_eq!(primary, alt, "the mirror must equal the primary MDB");
    }

    /// H14: an imported file's Finder flags (invisible, bundle, custom icon)
    /// had no way into create_file and came out zero.
    #[test]
    fn create_file_writes_the_finder_flags_it_is_given() {
        use disk_core::filesystem::{CreateFileOptions, EditableFilesystem, Filesystem};
        let mut img = create_blank_hfs(4 * 1024 * 1024, 4096, "Flags").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(&mut img), 0).unwrap();
        let root = fs.root().unwrap();
        let opts = CreateFileOptions {
            os_type: Some(*b"APPL"),
            os_creator: Some(*b"ttxt"),
            finder_flags: Some(0x2000),
            ..Default::default()
        };
        fs.create_file(&root, "app", &mut &b"x"[..], 1, &opts)
            .unwrap();
        fs.sync_metadata().unwrap();
        let entry = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "app")
            .unwrap();
        assert_eq!(entry.finder_flags, Some(0x2000));
    }

    #[test]
    fn shrink_is_refused_when_data_sits_past_the_new_end() {
        use disk_core::filesystem::{CreateFileOptions, EditableFilesystem, Filesystem};
        const SIZE: u64 = 8 * 1024 * 1024;
        let mut img = create_blank_hfs(SIZE, 4096, "Tail").unwrap();
        {
            let mut fs = HfsFilesystem::open(Cursor::new(&mut img), 0).unwrap();
            let root = fs.root().unwrap();
            fs.create_file(&root, "a", &mut &b"x"[..], 1, &CreateFileOptions::default())
                .unwrap();
            fs.sync_metadata().unwrap();
        }
        let total = BigEndian::read_u16(&img[1024 + 18..1024 + 20]) as usize;
        let vbm_start = BigEndian::read_u16(&img[1024 + 14..1024 + 16]) as usize;
        // Mark the last allocation block used without touching the counts.
        let tail = total - 1;
        let byte = vbm_start * 512 + tail / 8;
        img[byte] |= 0x80 >> (tail % 8);
        let err = resize_hfs_in_place(&mut Cursor::new(&mut img), 0, SIZE / 2, &mut |_| {})
            .expect_err("a tail block in use must refuse the shrink");
        assert!(format!("{err}").contains("last allocated block"), "{err}");
        img[byte] &= !(0x80 >> (tail % 8));
        resize_hfs_in_place(&mut Cursor::new(&mut img), 0, SIZE / 2, &mut |_| {})
            .expect("with the tail free the shrink goes through");
    }

    #[test]
    fn test_resize_hfs_rejects_u16_overflow() {
        // Build a minimal HFS MDB with 8192-byte blocks. The u16 ceiling at this
        // block size is 65535 * 8192 = ~512 MB, so a 2047 MB resize request must
        // bail (not silently truncate via `as u16`).
        let mut sector = [0u8; 512];
        BigEndian::write_u16(&mut sector[0..2], HFS_SIGNATURE);
        BigEndian::write_u16(&mut sector[14..16], 3); // vbm_st
        BigEndian::write_u16(&mut sector[18..20], 64110); // drNmAlBlks
        BigEndian::write_u32(&mut sector[20..24], 8192); // drAlBlkSiz
        BigEndian::write_u16(&mut sector[28..30], 19); // drAlBlSt
        BigEndian::write_u16(&mut sector[34..36], 31423); // drFreeBks

        // resize_hfs_in_place reads only the MDB at offset 1024 and bails on the
        // u16 block-count check *before* it seeks to the (would-be) backup MDB
        // near the end, so the image just needs to hold the MDB sector — no
        // multi-hundred-MB pad. (This also lets the test run on 32-bit targets,
        // which couldn't allocate the old 512 MB buffer.)
        let mut img = vec![0u8; 2048];
        img[1024..1024 + 512].copy_from_slice(&sector);

        let mut cursor = Cursor::new(img);
        let res = resize_hfs_in_place(
            &mut cursor,
            0,
            2047 * 1024 * 1024, // would need ~262016 blocks, overflows u16
            &mut |_| {},
        );
        let err = res.expect_err("resize should have bailed on u16 overflow");
        let msg = format!("{err}");
        assert!(
            msg.contains("65535") || msg.contains("u16") || msg.contains("Volume Bitmap"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_mdb_serialize_roundtrip() {
        let mut data = [0u8; 512];
        BigEndian::write_u16(&mut data[0..2], HFS_SIGNATURE);
        BigEndian::write_u16(&mut data[18..20], 100);
        BigEndian::write_u32(&mut data[20..24], 4096);
        BigEndian::write_u16(&mut data[34..36], 50);
        BigEndian::write_u32(&mut data[30..34], 10); // next_catalog_id
        BigEndian::write_u32(&mut data[92..96], 42); // finder_info[0]
        data[36] = 4;
        data[37..41].copy_from_slice(b"Test");

        let mdb = HfsMasterDirectoryBlock::parse(&data).unwrap();
        let serialized = mdb.serialize_to_sector();
        assert_eq!(BigEndian::read_u16(&serialized[18..20]), 100);
        assert_eq!(BigEndian::read_u32(&serialized[30..34]), 10);
        assert_eq!(BigEndian::read_u32(&serialized[92..96]), 42);
    }

    /// Create a minimal valid in-memory classic HFS image for testing.
    /// Layout: 128 blocks × 4096 bytes = 512 KB
    /// - Sectors 0-1: Boot blocks (1024 bytes)
    /// - Sector 2: MDB (1024 bytes)
    /// - Sectors 3-4: Volume bitmap (1024 bytes, covers 128 blocks = 16 bytes needed)
    /// - first_alloc_block = 5 (sectors), allocation starts at byte 2560
    /// - Block 0-3: catalog B-tree (4 blocks = 16 KB)
    ///   - Node 0: header node (4096 bytes)
    ///   - Node 1: leaf node with root folder + thread
    ///   - Nodes 2-3: free
    /// - Blocks 4+: free for user data
    fn make_editable_hfs_image() -> Vec<u8> {
        let block_size = 4096u32;
        let total_blocks = 128u16;
        let first_alloc_block = 5u16; // start at sector 5 (byte 2560)
        let alloc_start = first_alloc_block as usize * 512;
        let image_size = alloc_start + total_blocks as usize * block_size as usize;
        let mut img = vec![0u8; image_size];

        let catalog_start = 0u16; // first 8 allocation blocks
        let catalog_blocks = 8u16;
        let catalog_size = catalog_blocks as u32 * block_size;

        // Volume bitmap at sector 3 (byte 1536)
        let bitmap_sector = 3u16;
        let bitmap_off = bitmap_sector as usize * 512;
        // Mark blocks 0-7 as allocated (catalog spans 8 blocks)
        img[bitmap_off] = 0b11111111;

        // Build catalog B-tree
        let node_size = 4096usize;
        let catalog_offset = alloc_start; // block 0 of allocation area

        // Node 0: Header node
        let hdr_off = catalog_offset;
        img[hdr_off + 8] = 1; // kind = header node
        BigEndian::write_u16(&mut img[hdr_off + 10..hdr_off + 12], 3); // 3 records

        // B-tree header record (record 0, at offset 14)
        let hr = hdr_off + 14;
        BigEndian::write_u16(&mut img[hr..hr + 2], 1); // depth = 1
        BigEndian::write_u32(&mut img[hr + 2..hr + 6], 1); // root_node = 1
        BigEndian::write_u32(&mut img[hr + 6..hr + 10], 2); // leaf_records = 2
        BigEndian::write_u32(&mut img[hr + 10..hr + 14], 1); // first_leaf_node = 1
        BigEndian::write_u32(&mut img[hr + 14..hr + 18], 1); // last_leaf_node = 1
        BigEndian::write_u16(&mut img[hr + 18..hr + 20], node_size as u16); // node_size
        BigEndian::write_u16(&mut img[hr + 20..hr + 22], 37); // max_key_len
        BigEndian::write_u32(&mut img[hr + 22..hr + 26], 8); // total_nodes = 8
        BigEndian::write_u32(&mut img[hr + 26..hr + 30], 6); // free_nodes = 6

        // Record offset table for header node
        let ot = hdr_off + node_size;
        BigEndian::write_u16(&mut img[ot - 2..ot], 14); // record 0
        BigEndian::write_u16(&mut img[ot - 4..ot - 2], 142); // record 1 (user data)
        BigEndian::write_u16(&mut img[ot - 6..ot - 4], 270); // record 2 (bitmap)
        BigEndian::write_u16(&mut img[ot - 8..ot - 6], 526); // free space

        // Node bitmap (record 2): mark nodes 0 and 1 as allocated
        img[hdr_off + 270] = 0b11000000;

        // Node 1: Leaf node with root folder + thread
        let leaf_off = catalog_offset + node_size;
        img[leaf_off + 8] = 0xFF; // kind = -1 (leaf)
        img[leaf_off + 9] = 1; // height = 1
        BigEndian::write_u16(&mut img[leaf_off + 10..leaf_off + 12], 2); // 2 records

        // Record 0: Root folder record (CNID 2)
        // Key: key_len(1) + reserved(1) + parent_id(4, =1) + name_len(1) + name(0) = 7 bytes
        // Pad to even: 8 bytes total
        let r0_off = leaf_off + 14;
        img[r0_off] = 6; // key_len = 6 (reserved + parent_id + name_len)
        img[r0_off + 1] = 0; // reserved
        BigEndian::write_u32(&mut img[r0_off + 2..r0_off + 6], 1); // parent_id = 1
        img[r0_off + 6] = 0; // name_len = 0
                             // Pad to even
        img[r0_off + 7] = 0;
        // Record data at offset 8 (even-aligned)
        let r0_data = r0_off + 8;
        img[r0_data] = CATALOG_DIR as u8; // type = directory
                                          // dir record: type(1) + reserved(1) + flags(2) + valence(2) + dirID(4) + ...
        BigEndian::write_u32(&mut img[r0_data + 6..r0_data + 10], 2); // dirID = 2
                                                                      // Dir record = 70 bytes

        // Record 1: Thread record for root (CNID 2)
        let r1_off = r0_data + 70;
        img[r1_off] = 6; // key_len = 6
        img[r1_off + 1] = 0; // reserved
        BigEndian::write_u32(&mut img[r1_off + 2..r1_off + 6], 2); // parent_id = 2 (CNID)
        img[r1_off + 6] = 0; // name_len = 0
        img[r1_off + 7] = 0; // padding
        let r1_data = r1_off + 8;
        img[r1_data] = CATALOG_DIR_THREAD as u8; // type = dir thread
        img[r1_data + 1] = 0; // reserved
                              // reserved(8) at offset 2-9
        BigEndian::write_u32(&mut img[r1_data + 10..r1_data + 14], 1); // parentID = 1
                                                                       // Str31 name field: 32 bytes (1 length byte + 31 bytes name/padding)
        img[r1_data + 14] = 0; // name_len = 0 (rest of 32 bytes already zero)
                               // Thread data total = 2 (type+rsv) + 8 (rsv) + 4 (parentID) + 32 (Str31) = 46 bytes

        // Record offset table for leaf node
        let lot = leaf_off + node_size;
        BigEndian::write_u16(&mut img[lot - 2..lot], 14); // record 0
        let r1_rel = (r1_off - leaf_off) as u16;
        BigEndian::write_u16(&mut img[lot - 4..lot - 2], r1_rel); // record 1
        let free_rel = (r1_data + 46 - leaf_off) as u16;
        BigEndian::write_u16(&mut img[lot - 6..lot - 4], free_rel); // free space

        // MDB at byte 1024
        let mdb_off = 1024;
        let mut mdb = [0u8; 512];
        BigEndian::write_u16(&mut mdb[0..2], HFS_SIGNATURE);
        BigEndian::write_u32(&mut mdb[2..6], hfs_common::hfs_now()); // create date
        BigEndian::write_u32(&mut mdb[6..10], hfs_common::hfs_now()); // modify date
        BigEndian::write_u16(&mut mdb[14..16], bitmap_sector); // volume bitmap block
        BigEndian::write_u16(&mut mdb[18..20], total_blocks);
        BigEndian::write_u32(&mut mdb[20..24], block_size);
        BigEndian::write_u16(&mut mdb[28..30], first_alloc_block);
        BigEndian::write_u32(&mut mdb[30..34], 16); // next_catalog_id
        BigEndian::write_u16(&mut mdb[34..36], total_blocks - catalog_blocks); // free blocks
                                                                               // Volume name: "TestVol"
        mdb[36] = 7;
        mdb[37..44].copy_from_slice(b"TestVol");
        BigEndian::write_u32(&mut mdb[84..88], 0); // file_count
        BigEndian::write_u32(&mut mdb[88..92], 0); // folder_count (drDirCnt excludes root)
                                                   // Catalog file size
        BigEndian::write_u32(&mut mdb[146..150], catalog_size);
        // Catalog extents
        BigEndian::write_u16(&mut mdb[150..152], catalog_start);
        BigEndian::write_u16(&mut mdb[152..154], catalog_blocks);

        img[mdb_off..mdb_off + 512].copy_from_slice(&mdb);

        img
    }

    /// Create an "uninitialized" HFS image mimicking Disk Jockey's Empty HFS
    /// output: MDB present with catalog/extents extents reserved, but the
    /// catalog and extents-overflow regions are all zeros and the volume
    /// bitmap is blank.
    fn make_uninitialized_hfs_image() -> Vec<u8> {
        let block_size = 512u32;
        let total_blocks = 256u16;
        let first_alloc_block = 6u16;
        let alloc_start = first_alloc_block as usize * 512;
        let image_size = alloc_start + total_blocks as usize * block_size as usize;
        let mut img = vec![0u8; image_size];

        // Extents B-tree: blocks 0..3 (4 × 512 = 2048 bytes)
        let extents_start = 0u16;
        let extents_blocks = 4u16;
        // Catalog B-tree: blocks 4..7 (4 × 512 = 2048 bytes)
        let catalog_start = 4u16;
        let catalog_blocks = 4u16;

        // MDB at byte 1024, bitmap at sector 3 (byte 1536), both left blank
        // for the catalog and extents regions.
        let mdb_off = 1024usize;
        let mut mdb = [0u8; 512];
        BigEndian::write_u16(&mut mdb[0..2], HFS_SIGNATURE);
        BigEndian::write_u32(&mut mdb[2..6], hfs_common::hfs_now());
        BigEndian::write_u32(&mut mdb[6..10], hfs_common::hfs_now());
        BigEndian::write_u16(&mut mdb[14..16], 3); // vbm_block sector
        BigEndian::write_u16(&mut mdb[18..20], total_blocks);
        BigEndian::write_u32(&mut mdb[20..24], block_size);
        BigEndian::write_u16(&mut mdb[28..30], first_alloc_block);
        BigEndian::write_u32(&mut mdb[30..34], 16);
        BigEndian::write_u16(
            &mut mdb[34..36],
            total_blocks - extents_blocks - catalog_blocks,
        );
        // Volume name "Blank"
        mdb[36] = 5;
        mdb[37..42].copy_from_slice(b"Blank");
        // Extents file
        BigEndian::write_u32(&mut mdb[130..134], extents_blocks as u32 * block_size);
        BigEndian::write_u16(&mut mdb[134..136], extents_start);
        BigEndian::write_u16(&mut mdb[136..138], extents_blocks);
        // Catalog file
        BigEndian::write_u32(&mut mdb[146..150], catalog_blocks as u32 * block_size);
        BigEndian::write_u16(&mut mdb[150..152], catalog_start);
        BigEndian::write_u16(&mut mdb[152..154], catalog_blocks);

        img[mdb_off..mdb_off + 512].copy_from_slice(&mdb);
        img
    }

    #[test]
    fn test_hfs_empty_volume_auto_initialize_and_create_file() {
        // Blank catalog + extents regions should be auto-initialized on the
        // first mutating call instead of panicking in btree_find_insert_leaf.
        let img = make_uninitialized_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();
        assert_eq!(fs.fs_type(), "HFS");

        // list_directory on a blank catalog returns an empty list (no panic).
        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        assert!(entries.is_empty());

        // create_file triggers the auto-init path.
        let data = b"auto-init test";
        let mut cursor = Cursor::new(data.as_slice());
        let fe = fs
            .create_file(
                &root,
                "hello.txt",
                &mut cursor,
                data.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap();
        assert_eq!(fe.name, "hello.txt");
        fs.sync_metadata().unwrap();

        // The new file should be listed and readable.
        let entries = fs.list_directory(&root).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "hello.txt");
        let read_back = fs.read_file(&fe, 1024).unwrap();
        assert_eq!(&read_back, data);

        // fsck should report no errors or warnings on the initialized volume.
        let result = fs.fsck().unwrap();
        let err_msgs: Vec<_> = result.errors.iter().map(|e| e.message.clone()).collect();
        let warn_msgs: Vec<_> = result.warnings.iter().map(|w| w.message.clone()).collect();
        assert!(
            result.errors.is_empty(),
            "unexpected fsck errors: {err_msgs:?}"
        );
        assert!(
            result.warnings.is_empty(),
            "unexpected fsck warnings: {warn_msgs:?}"
        );
    }

    #[test]
    fn test_hfs_editable_open_and_free_space() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();
        assert_eq!(fs.fs_type(), "HFS");
        assert_eq!(fs.volume_label(), Some("TestVol"));
        let free = fs.free_space().unwrap();
        // 128 total - 8 catalog blocks = 120 free × 4096
        assert_eq!(free, 120 * 4096);
    }

    #[test]
    fn test_hfs_editable_create_file_and_read() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"Hello, HFS World!";
        let mut data_reader = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        let fe = fs
            .create_file(
                &root,
                "test.txt",
                &mut data_reader,
                test_data.len() as u64,
                &options,
            )
            .unwrap();

        assert_eq!(fe.name, "test.txt");
        assert_eq!(fe.size, test_data.len() as u64);

        // Verify listing
        let entries = fs.list_directory(&root).unwrap();
        assert!(entries.iter().any(|e| e.name == "test.txt"));

        // Read back
        let read_back = fs.read_file(&fe, 1024).unwrap();
        assert_eq!(&read_back, test_data);
    }

    /// `filStBlk` (offset 24) and `filRStBlk` (offset 34) of an HFS file record
    /// are the File Manager's in-memory "first allocation block" cache and MUST
    /// be zero on disk — the real fork location lives in the extent record at
    /// offset 74 / 86. A non-zero on-disk value makes Apple's `fsck_hfs` (incl.
    /// Mac OS X 10.4 Tiger, which fully supports HFS Standard) report
    /// "Reserved fields in the catalog record have incorrect data"
    /// (E_CatalogFlagsNotZero). Validated fsck_hfs-clean + mountable on Tiger.
    #[test]
    fn test_hfs_file_record_first_alloc_block_fields_are_zero() {
        use crate::hfs_common::walk_leaf_records;
        use disk_core::filesystem::ResourceForkSource;

        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();

        // A file with BOTH a data fork and a resource fork, so both filStBlk
        // and filRStBlk are exercised.
        let data = b"data fork contents that span a block";
        let options = CreateFileOptions {
            resource_fork: Some(ResourceForkSource::Data(b"resource fork bytes".to_vec())),
            ..Default::default()
        };
        fs.create_file(
            &root,
            "forked.bin",
            &mut Cursor::new(data.as_slice()),
            data.len() as u64,
            &options,
        )
        .unwrap();
        fs.sync_metadata().unwrap();

        let node_size = BigEndian::read_u16(&fs.catalog_data[32..34]) as usize;
        let first_leaf = BigEndian::read_u32(&fs.catalog_data[24..28]);
        let found = walk_leaf_records::<bool, _>(
            &fs.catalog_data,
            first_leaf,
            node_size,
            |_n, _i, _off, rec| {
                let klen = rec[0] as usize;
                let mut ds = 1 + klen;
                if !ds.is_multiple_of(2) {
                    ds += 1;
                }
                let body = &rec[ds..];
                if body.first() != Some(&2) {
                    return None; // not a file record
                }
                let fil_st_blk = BigEndian::read_u16(&body[24..26]);
                let fil_rst_blk = BigEndian::read_u16(&body[34..36]);
                let data_ext_start = BigEndian::read_u16(&body[74..76]);
                let rsrc_ext_start = BigEndian::read_u16(&body[86..88]);
                assert_eq!(fil_st_blk, 0, "filStBlk (offset 24) must be 0 on disk");
                assert_eq!(fil_rst_blk, 0, "filRStBlk (offset 34) must be 0 on disk");
                // The real fork locations are still recorded in the extents.
                assert_ne!(data_ext_start, 0, "data fork extent should be allocated");
                assert_ne!(rsrc_ext_start, 0, "rsrc fork extent should be allocated");
                Some(true)
            },
        );
        assert_eq!(found, Some(true), "file record not found in catalog");
    }

    /// Catalog dates surface on `FileEntry::mac_dates` (and the modify value on
    /// `modified`), and an in-place `set_dates` round-trips through sync +
    /// reopen. Exercises the M4 read path (catalog decode) plus the write path
    /// (`set_dates`, the setter `StagedEdit::SetDates` dispatches to).
    #[test]
    fn test_hfs_catalog_dates_round_trip() {
        let img = make_editable_hfs_image();
        let mut buf = img.clone();

        // create_file stamps create/modify to "now" (non-zero); backup is 0.
        {
            let mut fs = HfsFilesystem::open(Cursor::new(&mut buf), 0).unwrap();
            let root = fs.root().unwrap();
            let data = b"x";
            let fe = fs
                .create_file(
                    &root,
                    "dated.txt",
                    &mut Cursor::new(data.as_slice()),
                    1,
                    &CreateFileOptions::default(),
                )
                .unwrap();
            fs.sync_metadata().unwrap();

            let listed = fs.list_directory(&root).unwrap();
            let f = listed.iter().find(|e| e.name == "dated.txt").unwrap();
            let (c, m, b) = f.mac_dates.expect("HFS file should carry mac_dates");
            assert!(c != 0 && m != 0, "create/modify stamped by create_file");
            assert_eq!(b, 0, "backup date defaults to 0");

            // Stage specific dates via the in-place setter and persist.
            let target = (0x10000000u32, 0x20000000u32, 0x30000000u32);
            fs.set_dates(&fe, target.0, target.1, target.2).unwrap();
            fs.sync_metadata().unwrap();
        }

        // Reopen and confirm the dates decoded back, including the formatted
        // string surfaced in `modified`.
        let mut fs = HfsFilesystem::open(Cursor::new(&mut buf), 0).unwrap();
        let root = fs.root().unwrap();
        let listed = fs.list_directory(&root).unwrap();
        let f = listed.iter().find(|e| e.name == "dated.txt").unwrap();
        assert_eq!(f.mac_dates, Some((0x10000000, 0x20000000, 0x30000000)));
        assert_eq!(f.modified, hfs_common::format_mac_date(0x20000000));
    }

    #[test]
    fn test_hfs_editable_create_directory() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let options = CreateDirectoryOptions::default();
        let dir = fs.create_directory(&root, "NewDir", &options).unwrap();

        assert_eq!(dir.name, "NewDir");
        assert!(dir.is_directory());

        let entries = fs.list_directory(&root).unwrap();
        assert!(entries
            .iter()
            .any(|e| e.name == "NewDir" && e.is_directory()));
    }

    #[test]
    fn test_hfs_editable_rename_file() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();

        let data = b"keep my bytes across a rename";
        let mut r = Cursor::new(data.as_slice());
        let fe = fs
            .create_file(
                &root,
                "Before",
                &mut r,
                data.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap();
        let cnid = fe.location;

        fs.rename(&root, &fe, "After Doc").unwrap();

        let entries = fs.list_directory(&root).unwrap();
        assert!(entries.iter().any(|e| e.name == "After Doc"), "{entries:?}");
        assert!(!entries.iter().any(|e| e.name == "Before"), "{entries:?}");
        let renamed = entries.iter().find(|e| e.name == "After Doc").unwrap();
        // Identity (CNID) preserved and content intact (the catalog re-key keeps
        // the fork data untouched).
        assert_eq!(renamed.location, cnid);
        assert_eq!(&fs.read_file(renamed, 1024).unwrap(), data);

        // Renaming a directory keeps it browsable (its thread record name is
        // updated in place).
        fs.create_directory(&root, "OldDir", &CreateDirectoryOptions::default())
            .unwrap();
        let old_dir = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "OldDir")
            .unwrap();
        fs.rename(&root, &old_dir, "NewDir").unwrap();
        let new_dir = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "NewDir")
            .expect("renamed dir present");
        assert!(fs.list_directory(&new_dir).is_ok());

        // A collision with a different entry is rejected.
        let after = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "After Doc")
            .unwrap();
        assert!(matches!(
            fs.rename(&root, &after, "NewDir"),
            Err(FilesystemError::AlreadyExists(_))
        ));

        fs.sync_metadata().unwrap();
    }

    #[test]
    fn test_hfs_editable_delete_file() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"delete me";
        let mut data_reader = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        let fe = fs
            .create_file(
                &root,
                "gone.txt",
                &mut data_reader,
                test_data.len() as u64,
                &options,
            )
            .unwrap();

        let free_before = fs.free_space().unwrap();
        fs.delete_entry(&root, &fe).unwrap();

        let entries = fs.list_directory(&root).unwrap();
        assert!(!entries.iter().any(|e| e.name == "gone.txt"));

        let free_after = fs.free_space().unwrap();
        assert!(free_after > free_before);
    }

    #[test]
    fn test_hfs_editable_duplicate_name_rejected() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"first";
        let mut r1 = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        fs.create_file(&root, "dup.txt", &mut r1, 5, &options)
            .unwrap();

        let mut r2 = Cursor::new(test_data.as_slice());
        let result = fs.create_file(&root, "dup.txt", &mut r2, 5, &options);
        assert!(matches!(result, Err(FilesystemError::AlreadyExists(_))));
    }

    #[test]
    fn test_hfs_editable_name_too_long() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let long_name = "a".repeat(32); // 32 bytes > 31 limit
        let test_data = b"x";
        let mut r = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        let result = fs.create_file(&root, &long_name, &mut r, 1, &options);
        assert!(matches!(result, Err(FilesystemError::InvalidData(_))));
    }

    #[test]
    fn test_hfs_editable_blessed_folder() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        // Initially no blessed folder
        assert!(fs.blessed_system_folder().is_none());

        // Create a system folder
        let root = fs.root().unwrap();
        let options = CreateDirectoryOptions::default();
        let sys_dir = fs.create_directory(&root, "System", &options).unwrap();

        // Bless it
        fs.set_blessed_folder(&sys_dir).unwrap();

        // Verify
        let blessed = fs.blessed_system_folder();
        assert!(blessed.is_some());
        let (cnid, name) = blessed.unwrap();
        assert_eq!(cnid, sys_dir.location);
        assert_eq!(name, "System");
    }

    #[test]
    fn test_hfs_editable_type_creator_auto_detect() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"text content";
        let mut data_reader = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        let fe = fs
            .create_file(
                &root,
                "readme.txt",
                &mut data_reader,
                test_data.len() as u64,
                &options,
            )
            .unwrap();

        assert!(fe.type_code.is_some());
        assert_eq!(fe.type_code, Some(*b"TEXT"));
    }

    /// Helper: run fsck on an HfsFilesystem and panic if any errors are found.
    fn assert_fsck_clean<R: Read + Seek>(fs: &mut HfsFilesystem<R>) {
        let result = fs.fsck().unwrap();
        if !result.is_clean() {
            let msgs: Vec<_> = result
                .errors
                .iter()
                .map(|e| format!("[{}] {}", e.code, e.message))
                .collect();
            panic!("fsck found {} error(s):\n{}", msgs.len(), msgs.join("\n"));
        }
    }

    #[test]
    fn test_fsck_clean_fresh_image() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let result = fs.fsck().unwrap();
        let err_msgs: Vec<&str> = result.errors.iter().map(|e| e.message.as_str()).collect();
        assert!(
            result.is_clean(),
            "fresh image should be clean: {:?}",
            err_msgs
        );
        assert_eq!(result.stats.directories_checked, 1); // root only
        assert_eq!(result.stats.files_checked, 0);
    }

    #[test]
    fn test_fsck_clean_after_create_file() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"Hello, HFS World!";
        let mut data_reader = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        fs.create_file(
            &root,
            "test.txt",
            &mut data_reader,
            test_data.len() as u64,
            &options,
        )
        .unwrap();

        assert_fsck_clean(&mut fs);
    }

    #[test]
    fn test_fsck_clean_after_create_directory() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let options = CreateDirectoryOptions::default();
        fs.create_directory(&root, "NewDir", &options).unwrap();

        assert_fsck_clean(&mut fs);
    }

    #[test]
    fn test_fsck_clean_after_delete_file() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"delete me";
        let mut data_reader = Cursor::new(test_data.as_slice());
        let options = CreateFileOptions::default();
        let fe = fs
            .create_file(
                &root,
                "gone.txt",
                &mut data_reader,
                test_data.len() as u64,
                &options,
            )
            .unwrap();

        assert_fsck_clean(&mut fs);
        fs.delete_entry(&root, &fe).unwrap();
        assert_fsck_clean(&mut fs);
    }

    /// Random-order bulk inserts must pack the catalog densely *and* stay
    /// fsck-clean. The greedy "pack-left-full" split used to split off only the
    /// overflow on a middle insert, leaving a trail of ~1-record leaves: a
    /// random import packed ~1.6 records/node, roughly half what classic Mac OS
    /// writes (a real MacPack disk sits near 3.0). The B*-style sibling rotation
    /// (redistribute into a neighbour before splitting, at both the leaf and the
    /// index level) lifts random-order packing to ~3.0 records/node while
    /// leaving sequential growth fully packed (4 records/leaf).
    #[test]
    fn test_hfs_random_insert_packs_densely_and_fsck_clean() {
        use crate::hfs_common::BTreeHeader;
        type Fs = HfsFilesystem<Cursor<Vec<u8>>>;
        let block_size = 32 * 1024u32;
        let img = create_blank_hfs_sized(64 * 1024 * 1024, block_size, "Pack", 0, 16 * 1024 * 1024)
            .unwrap();
        let mut fs = Fs::open(Cursor::new(img), 0).unwrap();
        let root_id = fs.root().unwrap().location as u32;

        // Pseudo-random insertion order (multiplicative hash), de-duplicated.
        let n = 16000u32;
        let mut seen = std::collections::HashSet::new();
        let order: Vec<u32> = (0..n)
            .map(|i| i.wrapping_mul(2654435761) % n)
            .filter(|x| seen.insert(*x))
            .collect();
        let count = order.len() as u32;
        fs.begin_bulk();
        for &i in &order {
            let name = format!("f{:05}", i);
            let mut kr = Fs::build_catalog_key(root_id, name.as_bytes());
            kr.extend_from_slice(&Fs::build_file_record(
                16 + i,
                0,
                0,
                0,
                0,
                0,
                0,
                &[0u8; 4],
                &[0u8; 4],
                block_size,
                None,
                0,
            ));
            fs.insert_catalog_record(&kr).unwrap();
        }
        fs.end_bulk();
        fs.mdb.file_count = count;
        fs.mdb.next_catalog_id = 16 + n;
        fs.update_parent_valence(root_id, count as i32).unwrap();

        // Density: well above the ~1.6 the old split produced, and now close to
        // the ~3.2 of a fully-packed sequential build thanks to sibling rotation.
        let h = BTreeHeader::read(fs.catalog_data());
        let used = h.total_nodes - h.free_nodes;
        let rec_per_node = count as f64 / used as f64;
        assert!(
            rec_per_node > 2.8,
            "random-order packing too sparse: {count} records in {used} nodes ({rec_per_node:.2}/node)"
        );

        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck errors after random import: {:?}",
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );
    }

    /// Bulk mode (`begin_bulk` / `end_bulk`) skips the per-operation catalog
    /// snapshot for speed — the dominant per-file cost on a large import once
    /// the duplicate check is index-based. A successful batch must still leave
    /// a fsck-clean volume identical to the per-op path (on the success path no
    /// rollback ever happens, so the only difference is the skipped clone).
    /// This is the path `tar_import` drives.
    #[test]
    fn test_hfs_bulk_mode_import_fsck_clean() {
        let block_size = 32 * 1024u32;
        let img = create_blank_hfs_sized(
            64 * 1024 * 1024,
            block_size,
            "BulkImport",
            0,
            8 * 1024 * 1024,
        )
        .expect("create blank volume");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let root_id = root.location as u32;
        let options = CreateFileOptions::default();

        fs.begin_bulk();
        for i in 0..9000 {
            let name = format!("f{:05}.txt", i);
            let mut empty = Cursor::new(Vec::new());
            fs.create_file(&root, &name, &mut empty, 0, &options)
                .unwrap_or_else(|e| panic!("bulk create_file #{i}: {e}"));
        }
        fs.end_bulk();

        assert_eq!(fs.mdb.file_count, 9000);
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "bulk-mode import left fsck errors: {:?}",
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );
        // Records inserted under skipped snapshots are still correct/findable.
        assert!(fs
            .find_catalog_record_by_name(root_id, b"f04500.txt")
            .is_some());
        assert_eq!(fs.list_directory(&root).unwrap().len(), 9000);

        // After end_bulk, normal snapshotting resumes: a duplicate create is
        // rejected and rolls back cleanly, leaving the volume fsck-clean.
        let mut empty = Cursor::new(Vec::new());
        assert!(fs
            .create_file(&root, "f00000.txt", &mut empty, 0, &options)
            .is_err());
        assert_fsck_clean(&mut fs);
    }

    /// Regression for the classic-HFS catalog B-tree scaling bug
    /// (PROMPT-hfs-catalog-btree-scaling): importing many files used to die at
    /// ~7.4k records with "disk full: no free B-tree nodes" and fsck reported
    /// widespread `IndexSiblingLinkBroken`. Two writer defects combined — the
    /// per-split index rebuild leaked index nodes past the 2048-node header
    /// bitmap (exhausting free nodes), and the incremental index split never
    /// maintained fLink/bLink sibling links. Drive the B-tree well past that
    /// boundary on a production-shaped volume (node_size 512) and assert it is
    /// fsck-clean.
    ///
    /// Uses the low-level inserter directly so the test stays fast (the
    /// higher-level `create_file` does an O(n) duplicate scan per call); the
    /// end-to-end path is covered by
    /// `test_hfs_create_file_multilevel_index_fsck_clean`.
    #[test]
    fn test_hfs_catalog_scales_past_header_bitmap_fsck_clean() {
        use crate::hfs_common::BTreeHeader;
        type Fs = HfsFilesystem<Cursor<Vec<u8>>>;
        let block_size = 32 * 1024u32;
        // Empty files cost no data blocks, so a 64 MiB volume with a generous
        // 10 MiB catalog (20,480 nodes @ 512) holds the records and forces the
        // catalog past the header bitmap's 2048-node window into map nodes.
        let img = create_blank_hfs_sized(
            64 * 1024 * 1024,
            block_size,
            "Scale20k",
            0,
            10 * 1024 * 1024,
        )
        .expect("create blank volume");
        let mut fs = Fs::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let root_id = root.location as u32;

        let n: u32 = 22_000;
        for i in 0..n {
            let name = format!("f{:05}.txt", i);
            let mut key_record = Fs::build_catalog_key(root_id, name.as_bytes());
            let file_rec = Fs::build_file_record(
                16 + i,
                0,
                0,
                0,
                0,
                0,
                0,
                &[0u8; 4],
                &[0u8; 4],
                block_size,
                None,
                0,
            );
            key_record.extend_from_slice(&file_rec);
            fs.insert_catalog_record(&key_record)
                .unwrap_or_else(|e| panic!("insert #{i} ({name}): {e}"));
        }

        // Mirror the MDB bookkeeping the create path maintains so fsck's
        // cross-checks (file_count, next_catalog_id, root valence) pass.
        fs.mdb.file_count = n;
        fs.mdb.next_catalog_id = 16 + n;
        fs.update_parent_valence(root_id, n as i32).unwrap();

        // Confirm the catalog really grew a multi-level index beyond the single
        // header bitmap — otherwise the test wouldn't exercise the bug at all.
        let header = BTreeHeader::read(fs.catalog_data());
        assert!(
            header.depth >= 3,
            "expected a multi-level index, depth = {}",
            header.depth
        );
        let used = header.total_nodes - header.free_nodes;
        assert!(
            used > 2048,
            "expected > 2048 catalog nodes in use, got {used}"
        );

        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck found {} errors after {n}-record import: {:?}",
            result.errors.len(),
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );

        // After all those splits, records must still be findable by descending
        // the index (locates the correct leaf), including across the old
        // failure point (~7386) and the map-node boundary.
        for i in [0u32, 1, 7386, 12345, n - 1] {
            let name = format!("f{:05}.txt", i);
            assert!(
                fs.find_catalog_record_by_name(root_id, name.as_bytes())
                    .is_some(),
                "record {name} not findable after bulk insert"
            );
        }
    }

    /// Per-`put`-shaped regression (PROMPT-hfs-catalog-incremental-put-packing):
    /// 20k records inserted ONE AT A TIME in non-sequential (shuffled) key
    /// order, spread across many parent directories — exactly the shape of a
    /// `rb-cli put`-driven image build — must pack the catalog nearly as tightly
    /// as a sequential bulk import and stay fsck-clean to the volume's real
    /// limit. Before the B*-style sibling rotation (leaf + index), a shuffled
    /// per-record build left leaves at the classic ~69% B-tree occupancy and the
    /// index far worse, exhausting the node budget ~2x sooner ("disk full: no
    /// free B-tree nodes") and leaving `IndexSiblingLinkBroken` at the ceiling.
    #[test]
    fn test_hfs_incremental_shuffled_multidir_packs_dense_fsck_clean() {
        use crate::hfs_common::BTreeHeader;
        type Fs = HfsFilesystem<Cursor<Vec<u8>>>;
        let block_size = 32 * 1024u32;
        // ~6 MiB catalog (12,288 nodes @ 512). With the rotation fix 20k records
        // pack into well under that; the pre-fix ~1.6 rec/node packing would have
        // needed far more leaf nodes alone and exhausted it.
        let img = create_blank_hfs_sized(
            128 * 1024 * 1024,
            block_size,
            "PutShuffle",
            0,
            6 * 1024 * 1024,
        )
        .expect("create blank volume");
        let mut fs = Fs::open(Cursor::new(img), 0).unwrap();

        // Real directories so threads / valence / counts stay fsck-correct.
        const DIRS: u32 = 200;
        let root = fs.root().unwrap();
        let mut dir_ids = Vec::with_capacity(DIRS as usize);
        for d in 0..DIRS {
            let name = format!("dir{d:03}");
            let de = fs
                .create_directory(&root, &name, &Default::default())
                .unwrap();
            dir_ids.push(de.location as u32);
        }
        let base_cnid = fs.mdb.next_catalog_id;

        // 20k files in shuffled key order (multiplicative hash is a bijection
        // mod 2^32, so names are unique and land mid-leaf, not appended),
        // sprayed across the directories.
        let n: u32 = 20_000;
        let mut per_dir = vec![0i32; DIRS as usize];
        for i in 0..n {
            let hash = i.wrapping_mul(2_654_435_761);
            let d = (hash % DIRS) as usize;
            let name = format!("f{hash:08x}");
            let mut kr = Fs::build_catalog_key(dir_ids[d], name.as_bytes());
            kr.extend_from_slice(&Fs::build_file_record(
                base_cnid + i,
                0,
                0,
                0,
                0,
                0,
                0,
                &[0u8; 4],
                &[0u8; 4],
                block_size,
                None,
                0,
            ));
            fs.insert_catalog_record(&kr)
                .unwrap_or_else(|e| panic!("insert #{i} into dir{d}: {e}"));
            per_dir[d] += 1;
        }
        // Mirror the bookkeeping the create path would have maintained so fsck's
        // cross-checks (file_count, next_catalog_id, per-dir valence) pass.
        fs.mdb.file_count += n;
        fs.mdb.next_catalog_id = base_cnid + n;
        for (d, &cnt) in per_dir.iter().enumerate() {
            fs.update_parent_valence(dir_ids[d], cnt).unwrap();
        }

        // Density: the whole catalog (leaves + index) averages well above the
        // pre-fix ~1.6 rec/node — proof the incremental build packed tight and
        // didn't run away into a sparse, over-deep tree.
        let h = BTreeHeader::read(fs.catalog_data());
        let used = h.total_nodes - h.free_nodes;
        let rec_per_node = h.leaf_records as f64 / used as f64;
        assert!(
            rec_per_node > 2.6,
            "shuffled multi-dir packing too sparse: {} records in {used} nodes ({rec_per_node:.2}/node)",
            h.leaf_records
        );

        // No IndexSiblingLinkBroken or other structural damage at the ceiling.
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck found {} errors after 20k shuffled multi-dir put: {:?}",
            result.errors.len(),
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );

        // Records remain findable by index descent across the keyspace.
        for i in [0u32, 7, 9_999, n - 1] {
            let hash = i.wrapping_mul(2_654_435_761);
            let parent = dir_ids[(hash % DIRS) as usize];
            let name = format!("f{hash:08x}");
            assert!(
                fs.find_catalog_record_by_name(parent, name.as_bytes())
                    .is_some(),
                "record {name} not findable after shuffled multi-dir insert"
            );
        }
    }

    /// The delete / fsck-repair path rebuilds the catalog index wholesale via
    /// `rebuild_index_nodes`. Its free-all-index-nodes pass used to be capped
    /// at the 2048-bit header bitmap, leaking every index node beyond it; once
    /// a catalog crosses that line a rebuild must still round-trip fsck-clean.
    #[test]
    fn test_rebuild_index_nodes_past_header_bitmap_fsck_clean() {
        use crate::hfs_common::BTreeHeader;
        type Fs = HfsFilesystem<Cursor<Vec<u8>>>;
        let block_size = 32 * 1024u32;
        let img =
            create_blank_hfs_sized(64 * 1024 * 1024, block_size, "Rebuild", 0, 10 * 1024 * 1024)
                .expect("create blank volume");
        let mut fs = Fs::open(Cursor::new(img), 0).unwrap();
        let root_id = fs.root().unwrap().location as u32;

        let n: u32 = 12_000;
        for i in 0..n {
            let name = format!("f{:05}.txt", i);
            let mut key_record = Fs::build_catalog_key(root_id, name.as_bytes());
            let file_rec = Fs::build_file_record(
                16 + i,
                0,
                0,
                0,
                0,
                0,
                0,
                &[0u8; 4],
                &[0u8; 4],
                block_size,
                None,
                0,
            );
            key_record.extend_from_slice(&file_rec);
            fs.insert_catalog_record(&key_record).unwrap();
        }
        fs.mdb.file_count = n;
        fs.mdb.next_catalog_id = 16 + n;
        fs.update_parent_valence(root_id, n as i32).unwrap();

        let node_size = BTreeHeader::read(fs.catalog_data()).node_size as usize;
        let used_before = {
            let h = BTreeHeader::read(fs.catalog_data());
            h.total_nodes - h.free_nodes
        };
        assert!(
            used_before > 2048,
            "test needs > 2048 nodes, got {used_before}"
        );

        // Force a full index rebuild and require it to succeed without leaking.
        let mut report = disk_core::fsck::RepairReport {
            fixes_applied: Vec::new(),
            fixes_failed: Vec::new(),
            unrepairable_count: 0,
        };
        crate::hfs_fsck::rebuild_index_nodes(&mut fs.catalog_data, node_size, &mut report);
        assert!(
            report.fixes_failed.is_empty(),
            "rebuild reported failures: {:?}",
            report.fixes_failed
        );

        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck after rebuild: {:?}",
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );
    }

    /// End-to-end guard through the real `create_file` API: enough files to
    /// grow a multi-level catalog index must stay fsck-clean. ~2000 files at
    /// node_size 512 yields ~500 leaves and tens of index nodes — enough to
    /// split index nodes, the exact spot the incremental inserter used to
    /// leave sibling links broken.
    #[test]
    fn test_hfs_create_file_multilevel_index_fsck_clean() {
        use crate::hfs_common::BTreeHeader;
        let block_size = 32 * 1024u32;
        let img =
            create_blank_hfs_sized(32 * 1024 * 1024, block_size, "MultiIdx", 0, 4 * 1024 * 1024)
                .expect("create blank volume");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();
        for i in 0..2000 {
            let name = format!("f{:05}.txt", i);
            let mut empty = Cursor::new(Vec::new());
            fs.create_file(&root, &name, &mut empty, 0, &options)
                .unwrap_or_else(|e| panic!("create_file #{i}: {e}"));
        }
        let header = BTreeHeader::read(fs.catalog_data());
        assert!(
            header.depth >= 2,
            "expected an index level, depth = {}",
            header.depth
        );
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck errors: {:?}",
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );
        assert_eq!(fs.mdb.file_count, 2000);
    }

    /// Lock in lossless round-tripping of filenames carrying raw control bytes
    /// (e.g. 0x7F / DEL, as in the Macintosh Garden "IPNetRouter<DEL><DEL>"
    /// title that triggered the related JSON-escaping bug downstream). Mac
    /// Roman maps bytes < 0x80 straight through, so create then list must
    /// preserve them byte-for-byte.
    #[test]
    fn deleting_a_leafs_first_record_refreshes_the_separators() {
        // fsck_hfs E_IKey: a separator must be its child's first key, not the
        // key that record had before a delete took it.
        use crate::hfs_common::{
            btree_record_range, btree_stale_index_keys, BTreeHeader, BTreeKeyFormat,
        };
        let block_size = 32 * 1024u32;
        let img = create_blank_hfs_sized(32 * 1024 * 1024, block_size, "IKey", 0, 4 * 1024 * 1024)
            .expect("create blank volume");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();
        for i in 0..2000 {
            let mut empty = Cursor::new(Vec::new());
            fs.create_file(&root, &format!("f{i:05}.txt"), &mut empty, 0, &options)
                .unwrap();
        }
        let node_size = BigEndian::read_u16(&fs.catalog_data()[32..34]) as usize;
        let header = BTreeHeader::read(fs.catalog_data());
        assert!(
            header.depth >= 2,
            "need an index level, depth {}",
            header.depth
        );

        let first = header.first_leaf_node as usize;
        let second =
            BigEndian::read_u32(&fs.catalog_data()[first * node_size..first * node_size + 4])
                as usize;
        let name = {
            let node = &fs.catalog_data()[second * node_size..(second + 1) * node_size];
            let (s, e) = btree_record_range(node, node_size, 0);
            let rec = &node[s..e];
            let name_len = rec[6] as usize;
            String::from_utf8_lossy(&rec[7..7 + name_len]).into_owned()
        };
        assert!(
            name.starts_with('f'),
            "expected a file record first, got {name:?}"
        );
        let victim = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == name)
            .expect("victim listed");
        fs.delete_entry(&root, &victim).unwrap();

        let stale = btree_stale_index_keys(
            fs.catalog_data(),
            node_size,
            &BTreeKeyFormat::CLASSIC_CATALOG,
            &HfsFilesystem::<Cursor<Vec<u8>>>::catalog_compare,
        );
        assert!(stale.is_empty(), "separators still stale: {stale:?}");
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "{:?}",
            result
                .errors
                .iter()
                .map(|e| &e.message)
                .take(4)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hfs_control_char_filename_roundtrip() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();
        let name = "IPNetRouter\u{7f}\u{7f}_154_68k";
        let mut data = Cursor::new(b"x".to_vec());
        fs.create_file(&root, name, &mut data, 1, &options)
            .expect("create_file with raw 0x7F bytes in the name");
        let entries = fs.list_directory(&root).unwrap();
        assert!(
            entries.iter().any(|e| e.name == name),
            "0x7F-laden name not preserved; got {:?}",
            entries.iter().map(|e| &e.name).collect::<Vec<_>>()
        );
        assert_fsck_clean(&mut fs);
    }

    /// A null byte in a catalog name is valid on classic HFS (only the colon is
    /// forbidden) — a leading null is an old Finder trick to sort a file to the
    /// top. Real Apple disks carry such names (3 on the MacPack boot volume), so
    /// fsck must treat them as an informational *warning*, not an error.
    #[test]
    fn test_hfs_null_byte_name_is_warning_not_error() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();
        let mut data = Cursor::new(b"x".to_vec());
        fs.create_file(&root, "\u{0}Sorts First", &mut data, 1, &options)
            .expect("create_file with a leading null byte in the name");
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "a null-byte name must not be a fsck error: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.code == "UnusualCatalogName"),
            "expected an UnusualCatalogName warning for the null-byte name"
        );
    }

    #[test]
    fn test_fsck_stress_many_files() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();

        // Create 30+ files to trigger B-tree splits
        for i in 0..35 {
            let name = format!("file_{:03}.txt", i);
            let data = format!("content of file {}", i);
            let mut reader = Cursor::new(data.as_bytes().to_vec());
            fs.create_file(&root, &name, &mut reader, data.len() as u64, &options)
                .unwrap();

            // Verify fsck passes after each creation
            assert_fsck_clean(&mut fs);
        }

        let result = fs.fsck().unwrap();
        assert!(result.is_clean());
        assert_eq!(result.stats.files_checked, 35);
        assert_eq!(result.stats.directories_checked, 1); // just root
    }

    #[test]
    fn test_fsck_clean_after_blessed_folder() {
        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let options = CreateDirectoryOptions::default();
        let sys_dir = fs.create_directory(&root, "System", &options).unwrap();
        fs.set_blessed_folder(&sys_dir).unwrap();

        assert_fsck_clean(&mut fs);
    }

    /// Verify that rebuilt index records have proper even-alignment padding
    /// between the key and the node pointer, as required by Mac OS's B-tree
    /// traversal code. Without padding, Mac OS reads misaligned node pointers
    /// and crashes during volume mount.
    #[test]
    fn unerased_free_nodes_warn_once_and_repair_zeroes_them() {
        // Classic Mac OS never erased freed nodes (issue #89's System 7.5.5 volume had 696).
        use crate::hfs_common::{btree_bitmap_test, BTreeHeader};

        let mut fs = HfsFilesystem::open(Cursor::new(make_editable_hfs_image()), 0).unwrap();
        let node_size = BTreeHeader::read(&fs.catalog_data).node_size as usize;
        let free: Vec<usize> = (1..fs.catalog_data.len() / node_size)
            .filter(|&i| !btree_bitmap_test(&fs.catalog_data, node_size, i as u32))
            .take(3)
            .collect();
        assert_eq!(free.len(), 3, "blank catalog has free nodes");
        for &i in &free {
            fs.catalog_data[i * node_size + 20] = 0xA5;
        }

        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "not an error: {:?}",
            result.errors
        );
        let warns: Vec<_> = result
            .warnings
            .iter()
            .filter(|w| w.code == "FreeNodeNotErased")
            .collect();
        assert_eq!(warns.len(), 1, "one summary per tree, not one per node");
        assert!(
            warns[0].message.contains("3 unused node(s)"),
            "{}",
            warns[0].message
        );
        assert!(result.repairable);

        let report = fs.repair().unwrap();
        assert!(
            report
                .fixes_applied
                .iter()
                .any(|f| f == "Erased 3 unused catalog B-tree node(s)"),
            "{:?}",
            report.fixes_applied
        );
        let after = fs.fsck().unwrap();
        assert!(after.warnings.iter().all(|w| w.code != "FreeNodeNotErased"));
        assert!(after.errors.is_empty(), "{:?}", after.errors);
    }

    #[test]
    fn test_repair_index_records_are_even_aligned() {
        use crate::hfs_common::{btree_record_range, BTreeHeader};

        let img = make_editable_hfs_image();
        let cursor = Cursor::new(img);
        let mut fs = HfsFilesystem::open(cursor, 0).unwrap();
        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();

        // Create files with varying name lengths (even and odd) to exercise
        // both padded and unpadded key paths in index records
        for i in 0..40 {
            let name = if i % 2 == 0 {
                format!("f{:03}.txt", i) // 8 chars -> key_len=14 (even) -> needs pad
            } else {
                format!("fi{:03}.txt", i) // 9 chars -> key_len=15 (odd) -> no pad
            };
            let data = format!("data{}", i);
            let mut reader = Cursor::new(data.as_bytes().to_vec());
            fs.create_file(&root, &name, &mut reader, data.len() as u64, &options)
                .unwrap();
        }

        // Run repair (which rebuilds index nodes)
        let report = fs.repair().unwrap();
        assert!(
            report.fixes_failed.is_empty(),
            "repair failures: {:?}",
            report.fixes_failed
        );

        // Verify every index record has correct alignment
        let cat = &fs.catalog_data;
        let header = BTreeHeader::read(cat);
        let node_size = header.node_size as usize;
        let max_nodes = cat.len() / node_size;

        let mut index_recs_checked = 0u32;
        for n in 1..max_nodes {
            let off = n * node_size;
            if off + node_size > cat.len() {
                break;
            }
            let kind = cat[off + 8] as i8;
            if kind != 0 {
                continue;
            }
            let num_recs = BigEndian::read_u16(&cat[off + 10..off + 12]) as usize;
            for r in 0..num_recs {
                let (rec_start, rec_end) =
                    btree_record_range(&cat[off..off + node_size], node_size, r);
                if rec_start >= rec_end || rec_end > node_size {
                    continue;
                }
                let key_len = cat[off + rec_start] as usize;
                let rec_len = rec_end - rec_start;

                // Mac OS forces all catalog index keys to length 0x25 (37),
                // making every record exactly 42 bytes.
                assert_eq!(
                    key_len, 0x25,
                    "Index node {} rec {}: key_len={} but expected 0x25",
                    n, r, key_len
                );
                assert_eq!(
                    rec_len, 42,
                    "Index node {} rec {}: rec_len={} but expected 42",
                    n, r, rec_len
                );
                index_recs_checked += 1;
            }
        }
        assert!(
            index_recs_checked > 0,
            "no index records found — test needs more files"
        );

        // Verify that a post-repair integrity check finds no issues
        let result = fs.fsck().unwrap();
        let error_msgs: Vec<&str> = result.errors.iter().map(|e| e.message.as_str()).collect();
        assert!(
            result.errors.is_empty(),
            "post-repair check found errors: {:?}",
            error_msgs
        );
    }

    /// Blank-volume builder round-trip: open, fsck-clean, create a file,
    /// re-open, read back. Runs across the four block sizes called out in
    /// docs/hfs_expand_block_size.md.
    #[test]
    fn test_create_blank_hfs_roundtrip() {
        // (total_size, block_size, label) — sizes chosen to stay well clear
        // of the u16 block-count ceiling for each block size.
        let cases: &[(u64, u32, &str)] = &[
            (1 * 1024 * 1024, 512, "1MB @ 512"),
            (8 * 1024 * 1024, 4096, "8MB @ 4K"),
            (64 * 1024 * 1024, 16384, "64MB @ 16K"),
            (256 * 1024 * 1024, 32768, "256MB @ 32K"),
        ];

        for (total_size, block_size, label) in cases {
            let img = create_blank_hfs(*total_size, *block_size, "Fresh")
                .unwrap_or_else(|e| panic!("{label}: create_blank_hfs failed: {e}"));

            // Primary MDB at sector 2 (byte offset 1024). drAtrb at MDB+10
            // must include kHFSVolumeUnmountedMask (0x0100) so Mac OS does
            // not flag the volume for repair on first mount.
            let atrb = BigEndian::read_u16(&img[1024 + 10..1024 + 12]);
            assert_eq!(
                atrb & 0x0100,
                0x0100,
                "{label}: drAtrb missing kHFSVolumeUnmountedMask (got 0x{atrb:04x})"
            );
            // Alt MDB at next-to-last sector mirrors the primary.
            let alt_off = img.len() - 1024;
            let alt_atrb = BigEndian::read_u16(&img[alt_off + 10..alt_off + 12]);
            assert_eq!(
                alt_atrb, atrb,
                "{label}: alt MDB drAtrb (0x{alt_atrb:04x}) does not mirror primary (0x{atrb:04x})"
            );

            // The image MUST be exactly the requested size (rounded down by
            // whole allocation blocks, plus MDB sectors). We don't enforce
            // exact equality — the builder consumes remaining bytes for the
            // alt MDB — but it must never exceed the requested size.
            assert!(
                (img.len() as u64) <= *total_size,
                "{label}: image {} exceeds requested {}",
                img.len(),
                total_size
            );

            let mut fs = HfsFilesystem::open(Cursor::new(img.clone()), 0)
                .unwrap_or_else(|e| panic!("{label}: open failed: {e}"));
            assert_eq!(fs.mdb().block_size, *block_size, "{label}: block_size");
            assert_eq!(fs.mdb().volume_name, "Fresh", "{label}: volume_name");

            let root = fs.root().unwrap();
            let entries = fs.list_directory(&root).unwrap();
            assert!(
                entries.is_empty(),
                "{label}: root not empty on fresh volume"
            );

            let result = fs.fsck().unwrap();
            assert!(
                result.errors.is_empty(),
                "{label}: fsck errors: {:?}",
                result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
            );

            // create_file + sync + re-open + read-back
            let mut backing = img;
            {
                let mut fs = HfsFilesystem::open(Cursor::new(&mut backing), 0).unwrap();
                let root = fs.root().unwrap();
                let payload = b"contents".to_vec();
                let mut src = payload.as_slice();
                fs.create_file(
                    &root,
                    "hello",
                    &mut src,
                    payload.len() as u64,
                    &CreateFileOptions::default(),
                )
                .unwrap_or_else(|e| panic!("{label}: create_file failed: {e}"));
                fs.sync_metadata()
                    .unwrap_or_else(|e| panic!("{label}: sync_metadata failed: {e}"));
            }
            let mut fs = HfsFilesystem::open(Cursor::new(&mut backing), 0).unwrap();
            let root = fs.root().unwrap();
            let entries = fs.list_directory(&root).unwrap();
            assert_eq!(entries.len(), 1, "{label}: expected 1 child after create");
            assert_eq!(entries[0].name, "hello", "{label}: child name");
            let data = fs.read_file(&entries[0], 64).unwrap();
            assert_eq!(data, b"contents", "{label}: file content round-trip");

            let result = fs.fsck().unwrap();
            assert!(
                result.errors.is_empty(),
                "{label}: post-create fsck errors: {:?}",
                result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
            );
        }
    }

    /// A 2 GB - 1 byte volume at 32 KiB block size sits right under the
    /// u16 block-count ceiling (65535 blocks). Verify the builder accepts
    /// it and produces a fsck-clean image.
    ///
    /// Gated to 64-bit: create_blank_hfs materializes the whole ~2 GiB image
    /// as a Vec, which a 32-bit address space can't allocate (this was the
    /// "memory allocation of 2147461632 bytes failed" abort on the i686 CI leg).
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn test_create_blank_hfs_near_2gb() {
        let total = 2u64 * 1024 * 1024 * 1024 - 1;
        let img = create_blank_hfs(total, 32768, "Near2GB")
            .expect("create_blank_hfs near 2GB should succeed");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        assert_eq!(fs.mdb().block_size, 32768);
        assert!(fs.mdb().total_blocks >= 65000);
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck errors: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    /// F-016: a catalog formatted with 32 nodes takes a thousand files by
    /// growing in clumps; the grown file survives a reopen, and every judge
    /// sees a clean tree before and after the files go again.
    #[test]
    fn catalog_grows_when_its_nodes_run_out() {
        let img = create_blank_hfs_sized(16 * 1024 * 1024, 4096, "Grow", 0, 16384).unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let size0 = fs.mdb.catalog_file_size;
        assert_eq!(size0, 16384);
        let root = fs.root().unwrap();
        for i in 0..1000 {
            let name = format!("f{i:04}.txt");
            fs.create_file(
                &root,
                &name,
                &mut &b"x"[..],
                1,
                &CreateFileOptions::default(),
            )
            .unwrap_or_else(|e| panic!("creating {name}: {e}"));
        }
        assert!(fs.mdb.catalog_file_size > size0, "the catalog never grew");
        // Files sit right behind the catalog, so the growth had to take fresh
        // extents: three inline, the rest as CNID 4 records in the overflow tree.
        let inline: u32 = fs
            .mdb
            .catalog_file_extents
            .iter()
            .map(|e| e.block_count as u32)
            .sum();
        let spilled: u32 = collect_fork_overflow_extents(
            fs.extents_overflow_data
                .as_ref()
                .expect("overflow tree loaded"),
            CNID_CATALOG,
            0x00,
            inline,
        )
        .iter()
        .map(|e| e.block_count as u32)
        .sum();
        assert!(spilled > 0, "no CNID 4 overflow records");
        assert_eq!(
            (inline + spilled) * 4096,
            fs.mdb.catalog_file_size,
            "extents cover the file"
        );
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        let img = fs.reader.get_ref().clone();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let kids = fs.list_directory(&root).unwrap();
        assert_eq!(kids.len(), 1000);
        for e in &kids {
            fs.delete_entry(&root, e).unwrap();
        }
        fs.create_file(
            &root,
            "last.txt",
            &mut &b"y"[..],
            1,
            &CreateFileOptions::default(),
        )
        .unwrap();
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
    }

    /// F-016: the extents-overflow tree grows too, once a fork spread over
    /// enough holes needs more records than its four nodes hold.
    #[test]
    fn extents_tree_grows_when_its_nodes_run_out() {
        let img = create_blank_hfs_sized(4 * 1024 * 1024, 512, "Frag", 2048, 0).unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let xt0 = fs.mdb.extents_file_size;
        assert_eq!(xt0, 2048);
        let root = fs.root().unwrap();
        let block = vec![0x5Au8; 512];
        for i in 0..400 {
            fs.create_file(
                &root,
                &format!("h{i:03}"),
                &mut Cursor::new(&block),
                512,
                &CreateFileOptions::default(),
            )
            .unwrap();
        }
        for e in fs.list_directory(&root).unwrap() {
            if e.name[1..].parse::<u32>().unwrap() % 2 == 1 {
                fs.delete_entry(&root, &e).unwrap();
            }
        }
        // The free tail goes to one file but for 64 blocks the trees may grow
        // into; a 200-block fork then spreads over the one-block holes.
        let tail = (fs.mdb.free_blocks - 264) as usize * 512;
        fs.create_file(
            &root,
            "tail",
            &mut Cursor::new(vec![0u8; tail]),
            tail as u64,
            &CreateFileOptions::default(),
        )
        .unwrap();
        let data: Vec<u8> = (0..200 * 512).map(|i| (i / 512) as u8).collect();
        let entry = fs
            .create_file(
                &root,
                "spread",
                &mut Cursor::new(&data),
                data.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap();
        assert!(
            fs.mdb.extents_file_size > xt0,
            "the extents tree never grew"
        );
        assert_eq!(fs.read_file(&entry, usize::MAX).unwrap(), data);
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        let img = fs.reader.get_ref().clone();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let entry = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "spread")
            .unwrap();
        assert_eq!(fs.read_file(&entry, usize::MAX).unwrap(), data);
        fs.delete_entry(&root, &entry).unwrap();
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
    }

    /// F-016: past the 2048 nodes the header node's bitmap addresses, a grow
    /// links in a map node; 9000 files at 512-byte blocks get there.
    #[test]
    fn catalog_growth_adds_a_map_node_past_the_header_bitmap() {
        let img = create_blank_hfs_sized(24 * 1024 * 1024, 512, "Map", 0, 16384).unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        for i in 0..9000 {
            let name = format!("f{i:04}");
            fs.create_file(
                &root,
                &name,
                &mut &b"x"[..],
                1,
                &CreateFileOptions::default(),
            )
            .unwrap_or_else(|e| panic!("creating {name}: {e}"));
        }
        let h = BTreeHeader::read(&fs.catalog_data);
        assert!(h.total_nodes > 2048, "{} nodes", h.total_nodes);
        assert!(
            hfs_common::btree_bitmap_segments(&fs.catalog_data, 512).len() > 1,
            "no map node"
        );
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
        let img = fs.reader.get_ref().clone();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        assert_eq!(fs.list_directory(&root).unwrap().len(), 9000);
    }

    /// A thousand files in, one more in and out, the thousand out, one in:
    /// the catalog must stay clean through every split, merge and retire.
    #[test]
    fn thousand_file_churn_keeps_the_catalog_clean() {
        let img = create_blank_hfs(64 * 1024 * 1024, 4096, "Churn").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let clean = |fs: &mut HfsFilesystem<Cursor<Vec<u8>>>, stage: &str| {
            fs.sync_metadata().unwrap();
            let r = fs.fsck().unwrap();
            assert!(r.errors.is_empty(), "{stage}: {:?}", r.errors);
        };
        let put = |fs: &mut HfsFilesystem<Cursor<Vec<u8>>>, name: &str, data: &[u8]| {
            fs.create_file(
                &root,
                name,
                &mut Cursor::new(data),
                data.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap_or_else(|e| panic!("creating {name}: {e}"))
        };
        let free0 = fs.mdb.free_blocks;
        for i in 0..1000 {
            put(
                &mut fs,
                &format!("f{i:04}.txt"),
                format!("file {i:04}").as_bytes(),
            );
        }
        clean(&mut fs, "after 1000 creates");
        let extra = put(&mut fs, "extra.bin", &[7u8; 5000]);
        clean(&mut fs, "after one more");
        fs.delete_entry(&root, &extra).unwrap();
        clean(&mut fs, "after deleting it");
        for e in fs.list_directory(&root).unwrap() {
            fs.delete_entry(&root, &e).unwrap();
        }
        assert_eq!(fs.mdb.free_blocks, free0, "every block came back");
        clean(&mut fs, "after deleting the 1000");
        put(&mut fs, "last.bin", &[9u8; 100]);
        clean(&mut fs, "after the last create");
        let names: Vec<String> = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert_eq!(names, ["last.bin"]);
    }

    /// R-058: with the partition length known, fsck reports a classic HFS
    /// volume whose allocation area stops short of the partition's alternate MDB.
    #[test]
    fn fsck_reports_a_volume_that_does_not_fill_its_partition() {
        let img = create_blank_hfs(4 * 1024 * 1024, 2048, "Short").unwrap();
        let exact = img.len() as u64;
        let mut fs = HfsFilesystem::open_sized(Cursor::new(img.clone()), 0, Some(exact)).unwrap();
        assert!(fs.partition_shortfall().is_none());
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        // A remainder shorter than one allocation block is what Mac OS's own
        // formatter leaves behind; fsck_hfs accepts it, and so does this check.
        let mut fs =
            HfsFilesystem::open_sized(Cursor::new(img.clone()), 0, Some(exact + 512)).unwrap();
        assert_eq!(fs.partition_shortfall(), Some(512));
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        let mut fs =
            HfsFilesystem::open_sized(Cursor::new(img), 0, Some(exact + 1024 * 1024)).unwrap();
        assert_eq!(fs.partition_shortfall(), Some(1024 * 1024));
        let report = fs.fsck().unwrap();
        let codes: Vec<&str> = report.errors.iter().map(|e| e.code.as_str()).collect();
        assert_eq!(codes, ["AllocationAreaEnd"], "{:?}", report.errors);
        assert!(report.errors[0].message.contains("resize --size"));
    }

    /// F-011: a fork no single free run can hold spreads over the holes, its
    /// fourth extent on lands in the overflow tree, and both forks read back.
    #[test]
    fn create_file_spreads_a_fork_over_free_runs() {
        let img = create_blank_hfs(8 * 1024 * 1024, 4096, "Runs").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let block = vec![0xA5u8; 4096];
        for i in 0..40 {
            fs.create_file(
                &root,
                &format!("f{i:02}"),
                &mut Cursor::new(block.as_slice()),
                4096,
                &CreateFileOptions::default(),
            )
            .unwrap();
        }
        // Every other one-block file goes: 20 one-block holes.
        for e in fs.list_directory(&root).unwrap() {
            if e.name[1..].parse::<u32>().unwrap() % 2 == 1 {
                fs.delete_entry(&root, &e).unwrap();
            }
        }
        // The contiguous tail goes to one file, so only the holes are left.
        let tail = (fs.mdb.free_blocks - 20) as usize;
        let tail_data = vec![0x5Au8; tail * 4096];
        fs.create_file(
            &root,
            "tail",
            &mut Cursor::new(tail_data.as_slice()),
            tail_data.len() as u64,
            &CreateFileOptions::default(),
        )
        .unwrap();
        assert_eq!(fs.mdb.free_blocks, 20);
        let free_before = fs.mdb.free_blocks;

        // Seven blocks of data over seven holes: three inline, four in overflow.
        let data: Vec<u8> = (0..7 * 4096).map(|i| (i / 4096) as u8 + 1).collect();
        let rsrc: Vec<u8> = (0..5 * 4096).map(|i| 0x80 | (i / 4096) as u8).collect();
        let opts = CreateFileOptions {
            resource_fork: Some(disk_core::filesystem::ResourceForkSource::Data(
                rsrc.clone(),
            )),
            ..Default::default()
        };
        let entry = fs
            .create_file(
                &root,
                "frag",
                &mut Cursor::new(data.as_slice()),
                data.len() as u64,
                &opts,
            )
            .unwrap();
        let cnid = entry.location as u32;
        assert_eq!(fs.mdb.free_blocks, free_before - 12);
        let (dsize, dext, rsize, rext) = fs.find_file_by_id(cnid).unwrap();
        assert_eq!((dsize as usize, rsize as usize), (data.len(), rsrc.len()));
        assert!(dext.iter().all(|e| e.block_count == 1) && rext.iter().all(|e| e.block_count == 1));
        let tree = fs
            .extents_overflow_data
            .as_ref()
            .expect("overflow tree loaded");
        assert_eq!(collect_fork_overflow_extents(tree, cnid, 0x00, 0).len(), 4);
        assert_eq!(collect_fork_overflow_extents(tree, cnid, 0xFF, 0).len(), 2);
        assert_eq!(fs.read_file(&entry, usize::MAX).unwrap(), data);
        let mut got = Vec::new();
        fs.write_resource_fork_to(&entry, &mut got).unwrap();
        assert_eq!(got, rsrc);

        // setrsrc over it: the old runs come back, the new fork spreads again.
        let rsrc2: Vec<u8> = (0..4 * 4096).map(|i| 0xC0 | (i / 4096) as u8).collect();
        fs.write_resource_fork(
            &entry,
            &mut Cursor::new(rsrc2.as_slice()),
            rsrc2.len() as u64,
        )
        .unwrap();
        assert_eq!(fs.mdb.free_blocks, free_before - 11);
        let tree = fs.extents_overflow_data.as_ref().unwrap();
        assert_eq!(collect_fork_overflow_extents(tree, cnid, 0xFF, 0).len(), 1);
        let mut got = Vec::new();
        fs.write_resource_fork_to(&entry, &mut got).unwrap();
        assert_eq!(got, rsrc2);

        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        // Reopen from disk: the overflow records were written back.
        let img = fs.reader.get_ref().clone();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let entry = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "frag")
            .unwrap();
        assert_eq!(fs.read_file(&entry, usize::MAX).unwrap(), data);
        fs.delete_entry(&root, &entry).unwrap();
        assert_eq!(fs.mdb.free_blocks, free_before);
        let tree = fs.extents_overflow_data.as_ref().unwrap();
        assert!(collect_fork_overflow_extents(tree, cnid, 0x00, 0).is_empty());
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
    }

    /// A fork fragmented past its three inline extents keeps the rest in the
    /// extents-overflow tree; delete used to leak those blocks and records.
    #[test]
    fn delete_frees_overflow_extents_and_their_records() {
        use crate::hfs_common::{
            bitmap_test_bit_be, btree_alloc_node, BTreeHeader, BTREE_LEAF_NODE,
        };
        // A formatted volume: the hand-built test image has no extents file.
        let img = create_blank_hfs(8 * 1024 * 1024, 4096, "Overflow").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        assert!(fs.mdb.extents_file_size > 0);
        let root = fs.root().unwrap();
        let free_at_start = fs.mdb.free_blocks;
        let data = b"inline extent contents";
        fs.create_file(
            &root,
            "frag.bin",
            &mut Cursor::new(data.as_slice()),
            data.len() as u64,
            &CreateFileOptions::default(),
        )
        .unwrap();
        let entry = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "frag.bin")
            .unwrap();
        let cnid = entry.location as u32;

        // Give the data fork a fourth extent: two blocks described only by an
        // overflow record, in a leaf the blank tree does not have yet.
        let start = fs.allocate_blocks(2).unwrap();
        fs.ensure_extents_overflow().unwrap();
        {
            let tree = fs.extents_overflow_data.as_mut().expect("extents tree");
            let mut h = BTreeHeader::read(tree);
            let node_size = h.node_size as usize;
            let leaf = btree_alloc_node(tree, node_size, h.total_nodes).unwrap();
            h.root_node = leaf;
            h.first_leaf_node = leaf;
            h.last_leaf_node = leaf;
            h.depth = 1;
            h.leaf_records = 1;
            h.free_nodes -= 1;
            h.write(tree);
            let off = leaf as usize * node_size;
            let node = &mut tree[off..off + node_size];
            node[8] = BTREE_LEAF_NODE as u8;
            node[9] = 1;
            BigEndian::write_u16(&mut node[10..12], 1);
            // Key: keyLen 7, data fork, this file, from its second block.
            node[14] = 7;
            node[15] = 0x00;
            BigEndian::write_u32(&mut node[16..20], cnid);
            BigEndian::write_u16(&mut node[20..22], 1);
            BigEndian::write_u16(&mut node[22..24], start as u16);
            BigEndian::write_u16(&mut node[24..26], 2);
            BigEndian::write_u16(&mut node[node_size - 2..], 14);
            BigEndian::write_u16(&mut node[node_size - 4..node_size - 2], 34);
        }
        let tree = fs.extents_overflow_data.as_ref().unwrap();
        assert_eq!(collect_fork_overflow_extents(tree, cnid, 0x00, 0).len(), 1);

        fs.delete_entry(&root, &entry).unwrap();

        let tree = fs.extents_overflow_data.as_ref().unwrap();
        assert!(collect_fork_overflow_extents(tree, cnid, 0x00, 0).is_empty());
        let h = BTreeHeader::read(tree);
        assert_eq!((h.leaf_records, h.root_node, h.depth), (0, 0, 0));
        // Apple's fsck rejects a lone empty leaf; the retired tree has none.
        assert!(
            crate::hfs_common::btree_lonely_empty_leaves(tree, h.node_size as usize).is_empty()
        );
        let bitmap = fs.bitmap.as_ref().unwrap();
        assert!(!bitmap_test_bit_be(bitmap, start) && !bitmap_test_bit_be(bitmap, start + 1));
        assert_eq!(fs.mdb.free_blocks, free_at_start, "every block came back");
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
    }

    /// Synthesize a one-leaf extents-overflow B-tree blob and verify the
    /// collector returns the expected (start_block, block_count) sequence
    /// for the matching (file_id, fork_type), filtering by start_block.
    #[test]
    fn test_collect_fork_overflow_extents() {
        let node_size = 512usize;
        // 3 nodes: 0=header, 1=leaf, 2=unused.
        let total_nodes = 3u32;
        let mut buf = vec![0u8; node_size * total_nodes as usize];

        // Header node.
        buf[8] = hfs_common::BTREE_HEADER_NODE as u8;
        BigEndian::write_u16(&mut buf[10..12], 3); // numRecords
        BigEndian::write_u16(&mut buf[14..16], 1); // depth
        BigEndian::write_u32(&mut buf[16..20], 1); // rootNode
        BigEndian::write_u32(&mut buf[20..24], 1); // leafRecords (approx)
        BigEndian::write_u32(&mut buf[24..28], 1); // firstLeafNode
        BigEndian::write_u32(&mut buf[28..32], 1); // lastLeafNode
        BigEndian::write_u16(&mut buf[32..34], node_size as u16);
        BigEndian::write_u16(&mut buf[34..36], 7);
        BigEndian::write_u32(&mut buf[36..40], total_nodes);
        BigEndian::write_u32(&mut buf[40..44], total_nodes - 2);
        // Mark nodes 0 and 1 allocated in the header-node bitmap (rec at 248).
        buf[248] = 0b11000000;

        // Leaf node at index 1.
        let leaf_off = node_size;
        let leaf = &mut buf[leaf_off..leaf_off + node_size];
        leaf[8] = hfs_common::BTREE_LEAF_NODE as u8;
        BigEndian::write_u16(&mut leaf[10..12], 1); // one record

        // Record: key_len(1)=7, fork_type(1)=0x00, file_id(4)=0x100, start_block(2)=3
        let rec_off = 14usize;
        leaf[rec_off] = 7;
        leaf[rec_off + 1] = 0x00;
        BigEndian::write_u32(&mut leaf[rec_off + 2..rec_off + 6], 0x100);
        BigEndian::write_u16(&mut leaf[rec_off + 6..rec_off + 8], 3);
        // 3 extent descriptors (4 bytes each) immediately after key (already even).
        let data_off = rec_off + 8;
        BigEndian::write_u16(&mut leaf[data_off..data_off + 2], 50); // start
        BigEndian::write_u16(&mut leaf[data_off + 2..data_off + 4], 2); // count
        BigEndian::write_u16(&mut leaf[data_off + 4..data_off + 6], 60);
        BigEndian::write_u16(&mut leaf[data_off + 6..data_off + 8], 1);
        BigEndian::write_u16(&mut leaf[data_off + 8..data_off + 10], 0); // unused
        BigEndian::write_u16(&mut leaf[data_off + 10..data_off + 12], 0);

        // Record offset table: rec0 starts at 14, free at 14+8+12=34.
        let nr = 1usize;
        BigEndian::write_u16(&mut leaf[node_size - 2..], 14);
        BigEndian::write_u16(&mut leaf[node_size - 4..node_size - 2], 34);
        let _ = nr;

        // Match: same file, data fork, start_block >= 3.
        let got = collect_fork_overflow_extents(&buf, 0x100, 0x00, 3);
        assert_eq!(got.len(), 2, "expected 2 non-empty extents, got {got:?}");
        assert_eq!((got[0].start_block, got[0].block_count), (50, 2));
        assert_eq!((got[1].start_block, got[1].block_count), (60, 1));

        // Filter by min_start_block: skip record whose key startBlock < 4.
        let none = collect_fork_overflow_extents(&buf, 0x100, 0x00, 4);
        assert!(
            none.is_empty(),
            "expected empty when filtered, got {none:?}"
        );

        // Wrong fork_type returns nothing.
        let rsrc = collect_fork_overflow_extents(&buf, 0x100, 0xFF, 0);
        assert!(rsrc.is_empty());

        // Wrong file_id returns nothing.
        let other = collect_fork_overflow_extents(&buf, 0x101, 0x00, 0);
        assert!(other.is_empty());
    }

    /// `create_blank_hfs_sized` with non-default catalog/extents sizes
    /// produces an fsck-clean image that opens with the requested B-tree
    /// sizes (rounded up to the next allocation block).
    #[test]
    fn test_create_blank_hfs_sized_custom_btree_sizes() {
        let block_size = 32 * 1024u32;
        // Ask for 256 KiB catalog and 64 KiB extents-overflow.
        let img =
            create_blank_hfs_sized(64 * 1024 * 1024, block_size, "Sized", 64 * 1024, 256 * 1024)
                .expect("create_blank_hfs_sized");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).expect("open");
        // 64 KiB / 32 KiB = 2 blocks -> bumped to 4 (default floor).
        assert_eq!(fs.mdb().extents_file_size, 4 * block_size);
        // 256 KiB / 32 KiB = 8 blocks.
        assert_eq!(fs.mdb().catalog_file_size, 8 * block_size);
        let result = fs.fsck().expect("fsck");
        assert!(
            result.errors.is_empty(),
            "unexpected fsck errors: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    /// `pick_btree_node_size` always returns 512 — classic Mac OS rejects
    /// larger node sizes (Quadra ROM produces error -127). Map nodes are
    /// the long-term answer for >1 MiB B-tree files; until they exist we
    /// just pin the node size and rely on callers to clamp file sizes.
    #[test]
    fn test_pick_btree_node_size_thresholds() {
        assert_eq!(pick_btree_node_size(512 * 2048), 512);
        assert_eq!(pick_btree_node_size(512 * 2049), 512);
        assert_eq!(pick_btree_node_size(1024 * 6144), 512);
        assert_eq!(pick_btree_node_size(u32::MAX as u64), 512);
    }

    /// Even when the caller asks for a B-tree size above the 1 MiB header-
    /// bitmap budget, the produced volume still uses node_size=512. The
    /// caller is responsible for clamping; the builder keeps Mac-OS-friendly
    /// nodes and produces a fsck-clean image.
    #[test]
    fn test_create_blank_hfs_sized_large_catalog() {
        let block_size = 32 * 1024u32;
        let img = create_blank_hfs_sized(
            128 * 1024 * 1024,
            block_size,
            "Big",
            0,
            HFS_MAX_BTREE_FILE_SIZE,
        )
        .expect("create_blank_hfs_sized big catalog");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).expect("open big");
        let cat = fs.catalog_data();
        let node_size = BigEndian::read_u16(&cat[32..34]);
        assert_eq!(
            node_size, 512,
            "node_size must stay at 512 for Mac OS compat"
        );
        let result = fs.fsck().expect("fsck big");
        assert!(
            result.errors.is_empty(),
            "unexpected fsck errors: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    /// Catalog larger than the header bitmap's 2048-node capacity must
    /// allocate map nodes (BTNodeKind=2). Verify the chain is set up
    /// correctly, fsck is clean, and we can allocate nodes beyond bit 2048.
    #[test]
    fn test_create_blank_hfs_with_map_nodes() {
        // Request a 2 MiB catalog (4096 nodes at node_size=512). This needs
        // ceil((4096-2048)/3952) = 1 map node.
        let img =
            create_blank_hfs_sized(64 * 1024 * 1024, 32 * 1024, "MapNodes", 0, 2 * 1024 * 1024)
                .expect("create_blank_hfs_sized 2 MiB cat");
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).expect("open");
        let cat = fs.catalog_data().to_vec();

        // Header.fLink must point to the first map node (node 2).
        let header_flink = BigEndian::read_u32(&cat[0..4]);
        assert_eq!(header_flink, 2, "header.fLink should point to map node 2");

        // Node 2 must be a map node (kind=2) with one record and fLink=0
        // (only one map node needed for 4096-node capacity).
        let map = &cat[1024..1536];
        assert_eq!(map[8] as i8, 2, "node 2 should be a map node");
        assert_eq!(BigEndian::read_u16(&map[10..12]), 1);
        assert_eq!(
            BigEndian::read_u32(&map[0..4]),
            0,
            "single map node, fLink=0"
        );

        // Total nodes 4096, used 3 (header, leaf, map). free = 4093.
        let header = hfs_common::BTreeHeader::read(&cat);
        assert_eq!(header.total_nodes, 4096);
        assert_eq!(header.free_nodes, 4093);

        // Walk the segment iterator — should yield 2 segments covering
        // 256 + 494 = 750 bytes = 6000 bits ≥ 4096 nodes.
        let segs = hfs_common::btree_bitmap_segments(&cat, 512);
        assert_eq!(segs.len(), 2);
        assert_eq!(segs[0].base_bit, 0);
        assert_eq!(segs[1].base_bit, 2048);
        assert!(
            (segs[0].len + segs[1].len) * 8 >= 4096,
            "bitmap chain must address all 4096 nodes"
        );

        // fsck should be clean.
        let result = fs.fsck().expect("fsck");
        assert!(
            result.errors.is_empty(),
            "unexpected fsck errors: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    /// Block sizes that aren't positive multiples of 512 must be rejected.
    #[test]
    fn test_create_blank_hfs_rejects_bad_block_size() {
        assert!(create_blank_hfs(1 << 20, 0, "X").is_err());
        assert!(create_blank_hfs(1 << 20, 500, "X").is_err());
        assert!(create_blank_hfs(1 << 20, 513, "X").is_err());
    }

    // --- Step 4: Finder-metadata setter round-trip tests ---

    /// Create a file on the test image and return (fs, file_entry).
    fn make_fs_with_file() -> (HfsFilesystem<Cursor<Vec<u8>>>, FileEntry) {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let data = b"hello";
        let mut r = Cursor::new(data.as_slice());
        let fe = fs
            .create_file(
                &root,
                "thing.bin",
                &mut r,
                data.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap();
        (fs, fe)
    }

    #[test]
    fn test_hfs_set_finder_info_round_trip() {
        let (mut fs, fe) = make_fs_with_file();
        let mut finfo = [0u8; 16];
        finfo[0..4].copy_from_slice(b"APPL");
        finfo[4..8].copy_from_slice(b"MACS");
        BigEndian::write_u16(&mut finfo[8..10], 0x4000); // fdFlags kHasBeenInited
        BigEndian::write_i16(&mut finfo[10..12], 100); // fdLocation.v
        BigEndian::write_i16(&mut finfo[12..14], 200); // fdLocation.h
        BigEndian::write_u16(&mut finfo[14..16], 0x1234); // fdFldr
        let mut fxinfo = [0u8; 16];
        BigEndian::write_u16(&mut fxinfo[0..2], 0xABCD); // fdIconID
        fxinfo[8] = 0x55; // fdScript
        BigEndian::write_u32(&mut fxinfo[12..16], 0xDEADBEEF); // fdPutAway

        fs.set_finder_info(&fe, finfo, fxinfo).unwrap();

        let rec = fs.locate_record_data(fe.location as u32).unwrap();
        assert_eq!(&fs.catalog_data[rec + 4..rec + 20], &finfo);
        assert_eq!(&fs.catalog_data[rec + 56..rec + 72], &fxinfo);

        // The read path must surface fdFlags on FileEntry so get-binhex / cp
        // preserve them (docs/bug_binhex_finder_flags.md).
        let root = fs.root().unwrap();
        let listed = fs.list_directory(&root).unwrap();
        let entry = listed.iter().find(|e| e.name == "thing.bin").unwrap();
        assert_eq!(entry.finder_flags, Some(0x4000));
    }

    /// Regression for the dropped-Finder-flags bug: a file with hasBundle
    /// (0x2000) set must report `finder_flags == Some(0x2000)` on read, which
    /// is the value get-binhex now encodes into the .hqx header.
    #[test]
    fn test_hfs_read_surfaces_has_bundle_flag() {
        let (mut fs, fe) = make_fs_with_file();
        let mut finfo = [0u8; 16];
        finfo[0..4].copy_from_slice(b"APPL");
        finfo[4..8].copy_from_slice(b"Po.P");
        BigEndian::write_u16(&mut finfo[8..10], 0x2000); // fdFlags hasBundle
        fs.set_finder_info(&fe, finfo, [0u8; 16]).unwrap();

        let root = fs.root().unwrap();
        let listed = fs.list_directory(&root).unwrap();
        let entry = listed.iter().find(|e| e.name == "thing.bin").unwrap();
        assert_eq!(entry.finder_flags, Some(0x2000));
    }

    #[test]
    fn test_hfs_set_finder_info_rejects_directory() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let dir = fs
            .create_directory(&root, "Dir", &CreateDirectoryOptions::default())
            .unwrap();
        let err = fs.set_finder_info(&dir, [0u8; 16], [0u8; 16]).unwrap_err();
        assert!(matches!(err, FilesystemError::InvalidData(_)));
    }

    #[test]
    fn test_hfs_set_directory_finder_info_round_trip() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let dir = fs
            .create_directory(&root, "Apps", &CreateDirectoryOptions::default())
            .unwrap();

        let mut dinfo = [0u8; 16];
        BigEndian::write_i16(&mut dinfo[0..2], 10); // frRect top
        BigEndian::write_i16(&mut dinfo[2..4], 20); // frRect left
        BigEndian::write_i16(&mut dinfo[4..6], 300); // frRect bottom
        BigEndian::write_i16(&mut dinfo[6..8], 400); // frRect right
        BigEndian::write_u16(&mut dinfo[8..10], 0x0100); // frFlags
        let mut dxinfo = [0u8; 16];
        BigEndian::write_i16(&mut dxinfo[0..2], -5); // frScroll.v
        BigEndian::write_i16(&mut dxinfo[2..4], -7); // frScroll.h
        BigEndian::write_u32(&mut dxinfo[4..8], 0xCAFEBABE); // frOpenChain

        fs.set_directory_finder_info(&dir, dinfo, dxinfo).unwrap();

        let rec = fs.locate_record_data(dir.location as u32).unwrap();
        assert_eq!(&fs.catalog_data[rec + 22..rec + 38], &dinfo);
        assert_eq!(&fs.catalog_data[rec + 38..rec + 54], &dxinfo);
    }

    #[test]
    fn test_hfs_set_directory_finder_info_rejects_file() {
        let (mut fs, fe) = make_fs_with_file();
        let err = fs
            .set_directory_finder_info(&fe, [0u8; 16], [0u8; 16])
            .unwrap_err();
        assert!(matches!(err, FilesystemError::InvalidData(_)));
    }

    #[test]
    fn test_hfs_set_dates_file() {
        let (mut fs, fe) = make_fs_with_file();
        let create = 0x1000_0001u32;
        let modify = 0x2000_0002u32;
        let backup = 0x3000_0003u32;
        fs.set_dates(&fe, create, modify, backup).unwrap();

        let rec = fs.locate_record_data(fe.location as u32).unwrap();
        assert_eq!(
            BigEndian::read_u32(&fs.catalog_data[rec + 44..rec + 48]),
            create
        );
        assert_eq!(
            BigEndian::read_u32(&fs.catalog_data[rec + 48..rec + 52]),
            modify
        );
        assert_eq!(
            BigEndian::read_u32(&fs.catalog_data[rec + 52..rec + 56]),
            backup
        );
    }

    #[test]
    fn test_hfs_set_dates_directory() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let dir = fs
            .create_directory(&root, "D", &CreateDirectoryOptions::default())
            .unwrap();

        let create = 0xAAAAu32;
        let modify = 0xBBBBu32;
        let backup = 0xCCCCu32;
        fs.set_dates(&dir, create, modify, backup).unwrap();

        let rec = fs.locate_record_data(dir.location as u32).unwrap();
        assert_eq!(
            BigEndian::read_u32(&fs.catalog_data[rec + 10..rec + 14]),
            create
        );
        assert_eq!(
            BigEndian::read_u32(&fs.catalog_data[rec + 14..rec + 18]),
            modify
        );
        assert_eq!(
            BigEndian::read_u32(&fs.catalog_data[rec + 18..rec + 22]),
            backup
        );
    }

    #[test]
    fn test_hfs_set_file_locked_toggle() {
        let (mut fs, fe) = make_fs_with_file();
        let rec = fs.locate_record_data(fe.location as u32).unwrap();
        let initial = fs.catalog_data[rec + 2];
        assert_eq!(initial & 0x01, 0);

        fs.set_file_locked(&fe, true).unwrap();
        let rec = fs.locate_record_data(fe.location as u32).unwrap();
        assert_eq!(fs.catalog_data[rec + 2] & 0x01, 0x01);

        fs.set_file_locked(&fe, false).unwrap();
        let rec = fs.locate_record_data(fe.location as u32).unwrap();
        assert_eq!(fs.catalog_data[rec + 2] & 0x01, 0);
    }

    #[test]
    fn test_hfs_set_file_locked_rejects_directory() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let root = fs.root().unwrap();
        let dir = fs
            .create_directory(&root, "Dir", &CreateDirectoryOptions::default())
            .unwrap();
        let err = fs.set_file_locked(&dir, true).unwrap_err();
        assert!(matches!(err, FilesystemError::InvalidData(_)));
    }

    #[test]
    fn test_hfs_set_volume_dates_persists_through_sync() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();

        let create = 0x4242_4242u32;
        let modify = 0x5151_5151u32;
        let backup = 0x6060_6060u32;
        fs.set_volume_dates(create, modify, backup);
        fs.sync_metadata().unwrap();

        assert_eq!(fs.mdb.create_date, create);
        assert_eq!(fs.mdb.modify_date, modify);
        assert_eq!(BigEndian::read_u32(&fs.mdb.raw_sector[64..68]), backup);

        // Round-trip through disk: the on-disk MDB must preserve these bytes.
        let bytes = fs.reader.get_ref().clone();
        let mut fs2 = HfsFilesystem::open(Cursor::new(bytes), 0).unwrap();
        assert_eq!(fs2.mdb.create_date, create);
        assert_eq!(fs2.mdb.modify_date, modify);
        assert_eq!(BigEndian::read_u32(&fs2.mdb.raw_sector[64..68]), backup);

        // No pending dates -> sync stamps modify_date to hfs_now (different from `modify`).
        fs2.sync_metadata().unwrap();
        assert_ne!(fs2.mdb.modify_date, modify);
    }

    #[test]
    fn test_hfs_set_boot_blocks_written_on_sync() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let mut bb = [0u8; 1024];
        bb[0] = 0x4C; // 'LK' HFS boot signature
        bb[1] = 0x4B;
        for (i, slot) in bb.iter_mut().enumerate().skip(2).take(200) {
            *slot = (i & 0xFF) as u8;
        }
        fs.set_boot_blocks(&bb);
        fs.sync_metadata().unwrap();

        let read_back = fs.read_boot_blocks().unwrap();
        assert_eq!(&read_back[..], &bb[..]);
    }

    #[test]
    fn test_hfs_set_volume_finder_info_round_trip() {
        let img = make_editable_hfs_image();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();

        let mut fi = [0u8; 32];
        BigEndian::write_u32(&mut fi[0..4], 100); // blessed folder CNID
        BigEndian::write_u32(&mut fi[12..16], 200); // OS folder CNID (drFndrInfo[3])
        BigEndian::write_u32(&mut fi[20..24], 300); // drFndrInfo[5]
        fs.set_volume_finder_info(&fi);
        assert_eq!(fs.mdb.finder_info[0], 100);
        assert_eq!(fs.mdb.finder_info[3], 200);
        assert_eq!(fs.mdb.finder_info[5], 300);

        fs.sync_metadata().unwrap();
        let bytes = fs.reader.get_ref().clone();
        let fs2 = HfsFilesystem::open(Cursor::new(bytes), 0).unwrap();
        assert_eq!(fs2.mdb.finder_info[0], 100);
        assert_eq!(fs2.mdb.finder_info[3], 200);
        assert_eq!(fs2.mdb.finder_info[5], 300);
    }

    #[test]
    fn test_default_btree_sizes_scale_and_floor() {
        // Small volume: both sizes hit the 24-block floor.
        let (cat, ext) = default_btree_sizes(1 * 1024 * 1024, 512);
        let floor = 24 * 512;
        assert_eq!(cat, floor, "small-volume catalog should hit floor");
        assert_eq!(ext, floor, "small-volume extents should hit floor");

        // 20 MB @ 512 (the hformat reference volume): catalog should be a
        // healthy fraction of the volume (well above the 2 KB old default),
        // extents ~half. Both clump-aligned (4 * block_size = 2048).
        let (cat, ext) = default_btree_sizes(20 * 1024 * 1024, 512);
        assert!(cat >= 100 * 1024, "20MB catalog too small: {cat}");
        assert_eq!(cat % 2048, 0, "catalog not clump-aligned");
        assert_eq!(ext % 2048, 0, "extents not clump-aligned");
        assert!(ext <= cat, "extents should not exceed catalog");
        assert!(ext * 2 >= cat - 2048, "extents should be ~half catalog");

        // Larger volume scales further up.
        let (cat_big, _) = default_btree_sizes(200 * 1024 * 1024, 4096);
        assert!(cat_big > cat, "larger volume should get a larger catalog");

        // A volume formatted with the default sizing must be buildable +
        // fsck-clean (the catalog can't exceed available blocks).
        let (c, e) = default_btree_sizes(20 * 1024 * 1024, 4096);
        let img = create_blank_hfs_sized(20 * 1024 * 1024, 4096, "Ref20", e, c).unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck errors on default-sized volume: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_clone_target_btree_sizes_floors_at_blank_default() {
        // Regression: a densely-packed source catalog reports a small byte size
        // (here 2 MiB), but 1.5x that (3 MiB) undersized a 2046 MiB expand/HFV
        // target and exhausted it mid-clone ("no free B-tree nodes"). The clone
        // target must floor at the blank-format default for its own size.
        let target = 2046 * 1024 * 1024;
        let (default_cat, _) = default_btree_sizes(target, 32768);
        let (cat, _ext) = clone_target_btree_sizes(target, 32768, 2 * 1024 * 1024, 1024 * 1024);
        assert_eq!(
            cat, default_cat,
            "large target must floor catalog at the blank default, not 1.5x source"
        );
        assert!(
            cat > 2 * 1024 * 1024 * 3 / 2,
            "floor must exceed 1.5x source"
        );

        // When 1.5x source exceeds the volume default (small target, big
        // source catalog), the source-derived value wins.
        let small_target = 40 * 1024 * 1024;
        let (cat2, _) = clone_target_btree_sizes(small_target, 4096, 4 * 1024 * 1024, 256 * 1024);
        assert_eq!(
            cat2,
            4 * 1024 * 1024 * 3 / 2,
            "source-derived value should win"
        );

        // Never exceeds the HFS B-tree file ceiling.
        let (cat3, ext3) = clone_target_btree_sizes(target, 32768, u32::MAX, u32::MAX);
        assert!(cat3 <= HFS_MAX_BTREE_FILE_SIZE);
        assert!(ext3 <= HFS_MAX_BTREE_FILE_SIZE);
    }

    #[test]
    fn test_hfs_set_volume_name_roundtrip() {
        // Build a blank volume, rename, re-open, verify drVN + catalog
        // key + root thread record all carry the new name and fsck is clean.
        let img = create_blank_hfs(8 * 1024 * 1024, 4096, "OldName").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();

        fs.set_volume_name("NewName").unwrap();
        assert_eq!(fs.mdb.volume_name, "NewName");
        fs.sync_metadata().unwrap();

        let bytes = fs.reader.get_ref().clone();
        let mut fs2 = HfsFilesystem::open(Cursor::new(bytes.clone()), 0).unwrap();
        assert_eq!(fs2.mdb.volume_name, "NewName");

        // Root dir record key must now be (parent=1, "NewName") — otherwise
        // Mac OS rejects the volume with -127 at mount.
        let new_raw = b"NewName".to_vec();
        assert!(
            fs2.find_catalog_record_by_name(1, &new_raw).is_some(),
            "root dir record not re-keyed to new name"
        );
        assert!(
            fs2.find_catalog_record_by_name(1, b"OldName").is_none(),
            "old root dir key still present"
        );

        // Root thread record (parent=2, name="") must carry new thdCName.
        let (_n, _r, key_abs) = fs2.find_catalog_record_by_cnid(2).unwrap();
        let key_len = fs2.catalog_data[key_abs] as usize;
        let mut data_off = key_abs + 1 + key_len;
        if !data_off.is_multiple_of(2) {
            data_off += 1;
        }
        let thd_len = fs2.catalog_data[data_off + 14] as usize;
        assert_eq!(thd_len, new_raw.len(), "thdCName length not updated");
        assert_eq!(
            &fs2.catalog_data[data_off + 15..data_off + 15 + thd_len],
            new_raw.as_slice(),
            "thdCName bytes not updated"
        );

        // MDB drVN at raw_sector +36 should mirror.
        let mdb_off = 1024 + 36;
        assert_eq!(bytes[mdb_off] as usize, new_raw.len());
        assert_eq!(
            &bytes[mdb_off + 1..mdb_off + 1 + new_raw.len()],
            new_raw.as_slice()
        );

        let result = fs2.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck errors after rename: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_drallocptr_advances_with_allocations() {
        // Fresh volume: drAllocPtr should be 0. After a put it should
        // advance past the allocated run so subsequent allocations start
        // where the last one ended — matches hformat behavior.
        let img = create_blank_hfs(4 * 1024 * 1024, 512, "AllocPtr").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        assert_eq!(
            BigEndian::read_u16(&fs.mdb.raw_sector[16..18]),
            0,
            "fresh volume drAllocPtr should be 0"
        );

        let root = fs.root().unwrap();
        let payload = vec![0xABu8; 8 * 1024]; // forces 16 blocks @ 512
        let mut src = payload.as_slice();
        fs.create_file(
            &root,
            "ptr",
            &mut src,
            payload.len() as u64,
            &CreateFileOptions::default(),
        )
        .unwrap();
        let after = BigEndian::read_u16(&fs.mdb.raw_sector[16..18]);
        assert!(after > 0, "drAllocPtr should advance after allocation");
    }

    #[test]
    fn test_hfs_set_volume_name_rejects_invalid() {
        let img = create_blank_hfs(1 * 1024 * 1024, 512, "X").unwrap();
        let mut fs = HfsFilesystem::open(Cursor::new(img), 0).unwrap();
        assert!(
            fs.set_volume_name("").is_err(),
            "empty name must be rejected"
        );
        let too_long = "A".repeat(28);
        assert!(
            fs.set_volume_name(&too_long).is_err(),
            ">27 byte name must be rejected"
        );
        // Original name must still be intact after rollback.
        assert_eq!(fs.mdb.volume_name, "X");
    }

    #[test]
    fn test_hfs_finder_info_setters_survive_fsck() {
        // Ensure setters don't produce structural corruption.
        let (mut fs, fe) = make_fs_with_file();
        fs.set_finder_info(&fe, [0x11; 16], [0x22; 16]).unwrap();
        fs.set_dates(&fe, 1, 2, 3).unwrap();
        fs.set_file_locked(&fe, true).unwrap();
        fs.set_volume_dates(10, 20, 30);
        fs.set_volume_finder_info(&[0x33; 32]);
        fs.sync_metadata().unwrap();
        let result = fs.fsck().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck errors: {:?}",
            result.errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }
}