fs-mac 0.1.3

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
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
use byteorder::{BigEndian, ByteOrder};
#[cfg(feature = "rust173-polyfill")]
use disk_core::rust173::IntIsMultipleOf as _;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::io::{Read, Seek, SeekFrom, Write};

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

const HFS_PLUS_SIGNATURE: u16 = 0x482B;
const HFSX_SIGNATURE: u16 = 0x4858;

/// HFS+ reserved CNIDs (Inside Macintosh: Files / TN1150).
const HFSPLUS_EXTENTS_FILE_ID: u32 = 3;
const HFSPLUS_CATALOG_FILE_ID: u32 = 4;
const HFSPLUS_ALLOCATION_FILE_ID: u32 = 6;
const HFSPLUS_ATTRIBUTES_FILE_ID: u32 = 8;

/// Which special-file B-tree a grow-on-full operation targets. Each is
/// backed by a `ForkData` in the volume header and an in-memory tree buffer
/// (`catalog_data` / `extents_overflow_data` / `attributes_data`).
/// See `grow_btree_fork` and `docs/todo_hfsplus_fork_growth.md` §4b.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum BTreeFork {
    Catalog,
    Extents,
    Attributes,
}

impl BTreeFork {
    /// Reserved CNID of the special file backing this B-tree — the key under
    /// which its own overflow extents are recorded in the extents-overflow
    /// B-tree (Phase B).
    fn file_id(self) -> u32 {
        match self {
            BTreeFork::Catalog => HFSPLUS_CATALOG_FILE_ID,
            BTreeFork::Extents => HFSPLUS_EXTENTS_FILE_ID,
            BTreeFork::Attributes => HFSPLUS_ATTRIBUTES_FILE_ID,
        }
    }

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

/// Volume attribute bit (`vh.attributes`) set when the volume carries a
/// journal. We refuse to enter edit mode on these volumes until journal
/// replay is implemented — see Step 4 of `docs/hfsplus_enhancements.md`.
pub(crate) const HFSPLUS_VOLUME_JOURNALED_BIT: u32 = 0x2000;

/// `kHFSVolumeUnmountedBit` — set in `vh.attributes` to mark a cleanly-
/// unmounted volume. Mac OS refuses to mount volumes without this bit
/// (it triggers a "needs scavenging" path).
pub(crate) const HFSPLUS_VOLUME_UNMOUNTED_BIT: u32 = 0x100;

/// `kHFSBootVolumeInconsistentBit` — set by Mac OS while a volume is
/// mounted; cleared on clean unmount. Must be cleared on sync so the
/// volume isn't flagged for repair on next mount.
pub(crate) const HFSPLUS_BOOT_VOLUME_INCONSISTENT_BIT: u32 = 0x800;

/// `kHFSVolumeInconsistentBit` — newer companion to the boot-inconsistent
/// bit; Mac OS sets it when the volume is in a transient inconsistent
/// state (mid-mount, mid-write). Must be cleared on sync so Disk Utility
/// doesn't refuse to mount the volume.
pub(crate) const HFSPLUS_VOLUME_INCONSISTENT_BIT: u32 = 0x4000;

/// HFS+ B-tree `keyCompareType` byte values (BTHeaderRec offset 37 in
/// node 0). Plain HFS+ uses case-folding NFD compare; HFSX with the
/// case-sensitive attribute uses binary compare.
const KEY_COMPARE_CASE_FOLDING: u8 = 0xCF;
const KEY_COMPARE_BINARY: u8 = 0xBC;

/// Fork-type byte used in extents-overflow keys.
const HFSPLUS_FORK_DATA: u8 = 0x00;
#[allow(dead_code)]
const HFSPLUS_FORK_RESOURCE: u8 = 0xFF;

/// Attributes B-tree record types (per Apple TN1150 / `hfs_format.h`).
pub(crate) const HFSPLUS_ATTR_INLINE_DATA: u32 = 0x10;
#[allow(dead_code)] // matched by Step 13 (xattr writes); kept for completeness
const HFSPLUS_ATTR_FORK_DATA: u32 = 0x20;
#[allow(dead_code)]
const HFSPLUS_ATTR_EXTENTS: u32 = 0x30;

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

impl ExtentDescriptor {
    fn parse(data: &[u8]) -> Self {
        ExtentDescriptor {
            start_block: BigEndian::read_u32(&data[0..4]),
            block_count: BigEndian::read_u32(&data[4..8]),
        }
    }

    fn is_empty(&self) -> bool {
        self.block_count == 0
    }

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

/// HFS+ fork data (80 bytes).
#[derive(Debug, Clone)]
pub(crate) struct ForkData {
    pub(crate) logical_size: u64,
    // Preserved for VH round-trip; HFS+ on-disk fork data has a clump_size
    // slot at bytes [8..12]. We never tune it, but parsing/emitting the
    // named field keeps the serializer symmetric with the parser.
    #[allow(dead_code)]
    pub(crate) clump_size: u32,
    pub(crate) total_blocks: u32,
    pub(crate) extents: [ExtentDescriptor; 8],
}

impl ForkData {
    fn parse(data: &[u8]) -> Self {
        let mut extents = [ExtentDescriptor {
            start_block: 0,
            block_count: 0,
        }; 8];
        for i in 0..8 {
            extents[i] = ExtentDescriptor::parse(&data[16 + i * 8..24 + i * 8]);
        }
        ForkData {
            logical_size: BigEndian::read_u64(&data[0..8]),
            clump_size: BigEndian::read_u32(&data[8..12]),
            total_blocks: BigEndian::read_u32(&data[12..16]),
            extents,
        }
    }

    fn serialize(&self, out: &mut [u8]) {
        BigEndian::write_u64(&mut out[0..8], self.logical_size);
        BigEndian::write_u32(&mut out[8..12], self.clump_size);
        BigEndian::write_u32(&mut out[12..16], self.total_blocks);
        for i in 0..8 {
            self.extents[i].serialize(&mut out[16 + i * 8..24 + i * 8]);
        }
    }

    pub(crate) fn empty() -> Self {
        ForkData {
            logical_size: 0,
            clump_size: 0,
            total_blocks: 0,
            extents: [ExtentDescriptor {
                start_block: 0,
                block_count: 0,
            }; 8],
        }
    }
}

/// One extended-attribute record decoded from the attributes B-tree.
///
/// The HFS+ attributes file stores xattrs keyed by `(fileID, startBlock, name)`;
/// inline records carry their value byte-for-byte, fork records carry a fork
/// header pointing at a separate xattr fork (read on demand), and extents
/// records carry continuation extents for forks larger than 8 inline extents.
#[derive(Debug, Clone)]
#[allow(dead_code)] // accessor fields are read in upcoming Step 13/14 callers
pub(crate) struct XattrRecord {
    pub name: String,
    /// Starting block of the value within an attribute fork. `0` for inline
    /// records and the first segment of fork-style records; nonzero for
    /// `Extents` continuation records.
    pub start_block: u32,
    pub kind: XattrKind,
}

#[derive(Debug, Clone)]
#[allow(dead_code)] // Fork/Extents variants are surfaced once xattr writes ship
pub(crate) enum XattrKind {
    /// Value stored directly in the B-tree record (the common case for
    /// `com.apple.FinderInfo` and most `com.apple.*` keys).
    Inline(Vec<u8>),
    /// Value stored in its own fork; the inline 8 extents in `ForkData`
    /// cover the value (or anchor a chain of `Extents` records).
    Fork(ForkData),
    /// Continuation extents for a fork-style xattr that needed more than
    /// 8 extents.
    Extents(Vec<ExtentDescriptor>),
}

/// HFS+ Volume Header (512 bytes at partition_offset + 1024).
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct HfsPlusVolumeHeader {
    signature: u16,
    version: u16,
    attributes: u32,
    last_mounted_version: u32,
    journal_info_block: u32,
    create_date: u32,
    modify_date: u32,
    backup_date: u32,
    checked_date: u32,
    file_count: u32,
    folder_count: u32,
    block_size: u32,
    total_blocks: u32,
    free_blocks: u32,
    next_allocation: u32,
    rsrc_clump_size: u32,
    data_clump_size: u32,
    next_catalog_id: u32,
    write_count: u32,
    encodings_bitmap: u64,
    finder_info: [u32; 8],
    allocation_file: ForkData,
    extents_file: ForkData,
    catalog_file: ForkData,
    attributes_file: ForkData,
    startup_file: ForkData,
}

impl HfsPlusVolumeHeader {
    fn parse(data: &[u8]) -> Result<Self, FilesystemError> {
        if data.len() < 512 {
            return Err(FilesystemError::Parse("volume header too short".into()));
        }
        let sig = BigEndian::read_u16(&data[0..2]);
        if sig != HFS_PLUS_SIGNATURE && sig != HFSX_SIGNATURE {
            return Err(FilesystemError::Parse(format!(
                "bad HFS+ volume header signature: 0x{sig:04X}"
            )));
        }

        let mut finder_info = [0u32; 8];
        for i in 0..8 {
            finder_info[i] = BigEndian::read_u32(&data[80 + i * 4..84 + i * 4]);
        }

        Ok(HfsPlusVolumeHeader {
            signature: sig,
            version: BigEndian::read_u16(&data[2..4]),
            attributes: BigEndian::read_u32(&data[4..8]),
            last_mounted_version: BigEndian::read_u32(&data[8..12]),
            journal_info_block: BigEndian::read_u32(&data[12..16]),
            create_date: BigEndian::read_u32(&data[16..20]),
            modify_date: BigEndian::read_u32(&data[20..24]),
            backup_date: BigEndian::read_u32(&data[24..28]),
            checked_date: BigEndian::read_u32(&data[28..32]),
            file_count: BigEndian::read_u32(&data[32..36]),
            folder_count: BigEndian::read_u32(&data[36..40]),
            block_size: BigEndian::read_u32(&data[40..44]),
            total_blocks: BigEndian::read_u32(&data[44..48]),
            free_blocks: BigEndian::read_u32(&data[48..52]),
            next_allocation: BigEndian::read_u32(&data[52..56]),
            rsrc_clump_size: BigEndian::read_u32(&data[56..60]),
            data_clump_size: BigEndian::read_u32(&data[60..64]),
            next_catalog_id: BigEndian::read_u32(&data[64..68]),
            write_count: BigEndian::read_u32(&data[68..72]),
            encodings_bitmap: BigEndian::read_u64(&data[72..80]),
            finder_info,
            allocation_file: ForkData::parse(&data[112..192]),
            extents_file: ForkData::parse(&data[192..272]),
            catalog_file: ForkData::parse(&data[272..352]),
            attributes_file: ForkData::parse(&data[352..432]),
            startup_file: ForkData::parse(&data[432..512]),
        })
    }

    fn serialize(&self) -> [u8; 512] {
        let mut out = [0u8; 512];
        BigEndian::write_u16(&mut out[0..2], self.signature);
        BigEndian::write_u16(&mut out[2..4], self.version);
        BigEndian::write_u32(&mut out[4..8], self.attributes);
        BigEndian::write_u32(&mut out[8..12], self.last_mounted_version);
        BigEndian::write_u32(&mut out[12..16], self.journal_info_block);
        BigEndian::write_u32(&mut out[16..20], self.create_date);
        BigEndian::write_u32(&mut out[20..24], self.modify_date);
        BigEndian::write_u32(&mut out[24..28], self.backup_date);
        BigEndian::write_u32(&mut out[28..32], self.checked_date);
        BigEndian::write_u32(&mut out[32..36], self.file_count);
        BigEndian::write_u32(&mut out[36..40], self.folder_count);
        BigEndian::write_u32(&mut out[40..44], self.block_size);
        BigEndian::write_u32(&mut out[44..48], self.total_blocks);
        BigEndian::write_u32(&mut out[48..52], self.free_blocks);
        BigEndian::write_u32(&mut out[52..56], self.next_allocation);
        BigEndian::write_u32(&mut out[56..60], self.rsrc_clump_size);
        BigEndian::write_u32(&mut out[60..64], self.data_clump_size);
        BigEndian::write_u32(&mut out[64..68], self.next_catalog_id);
        BigEndian::write_u32(&mut out[68..72], self.write_count);
        BigEndian::write_u64(&mut out[72..80], self.encodings_bitmap);
        for i in 0..8 {
            BigEndian::write_u32(&mut out[80 + i * 4..84 + i * 4], self.finder_info[i]);
        }
        self.allocation_file.serialize(&mut out[112..192]);
        self.extents_file.serialize(&mut out[192..272]);
        self.catalog_file.serialize(&mut out[272..352]);
        self.attributes_file.serialize(&mut out[352..432]);
        self.startup_file.serialize(&mut out[432..512]);
        out
    }

    fn is_hfsx(&self) -> bool {
        self.signature == HFSX_SIGNATURE
    }
}

/// B-tree node descriptor (14 bytes).
#[derive(Debug)]
struct BTreeNodeDescriptor {
    next: u32,
    #[allow(dead_code)]
    prev: u32,
    kind: i8,
    #[allow(dead_code)]
    height: u8,
    num_records: u16,
}

impl BTreeNodeDescriptor {
    fn parse(data: &[u8]) -> Self {
        BTreeNodeDescriptor {
            next: BigEndian::read_u32(&data[0..4]),
            prev: BigEndian::read_u32(&data[4..8]),
            kind: data[8] as i8,
            height: data[9],
            num_records: BigEndian::read_u16(&data[10..12]),
        }
    }
}

/// B-tree header record (after the node descriptor in node 0).
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct BTreeHeaderRecord {
    depth: u16,
    root_node: u32,
    leaf_records: u32,
    first_leaf_node: u32,
    last_leaf_node: u32,
    node_size: u16,
    max_key_len: u16,
    total_nodes: u32,
    free_nodes: u32,
    /// `keyCompareType` byte (BTHeaderRec offset 37): `0xCF` =
    /// case-folding NFD, `0xBC` = binary (HFSX case-sensitive). Older /
    /// hand-built B-trees may leave this zero — callers should treat any
    /// value other than `0xBC` as case-folding to stay compatible with
    /// non-HFSX volumes.
    key_compare_type: u8,
}

impl BTreeHeaderRecord {
    fn parse(data: &[u8]) -> Self {
        // The keyCompareType byte sits 7 bytes past the freeNodes field,
        // i.e. at offset 37 of the BTHeaderRec. The 106-byte slice handed
        // to us is large enough to cover it; older callers that only had
        // 30 bytes get treated as case-folding.
        let key_compare_type = if data.len() >= 38 { data[37] } else { 0 };
        BTreeHeaderRecord {
            depth: BigEndian::read_u16(&data[0..2]),
            root_node: BigEndian::read_u32(&data[2..6]),
            leaf_records: BigEndian::read_u32(&data[6..10]),
            first_leaf_node: BigEndian::read_u32(&data[10..14]),
            last_leaf_node: BigEndian::read_u32(&data[14..18]),
            node_size: BigEndian::read_u16(&data[18..20]),
            max_key_len: BigEndian::read_u16(&data[20..22]),
            total_nodes: BigEndian::read_u32(&data[22..26]),
            free_nodes: BigEndian::read_u32(&data[26..30]),
            key_compare_type,
        }
    }
}

/// Catalog record types.
const CATALOG_FOLDER: i16 = 1;
const CATALOG_FILE: i16 = 2;

/// Validate a name for a new file or directory on an HFS+/HFSX volume.
fn validate_hfsplus_create_name(name: &str) -> Result<(), 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 utf16_len = fs_mac_unicode::hfs_unicode::decompose_str(name).len();
    if utf16_len > 255 {
        return Err(FilesystemError::InvalidData(format!(
            "filename is too long ({utf16_len} UTF-16 units); HFS+ allows up to 255 — \
             shorten the name (note: some emoji and rare characters count as 2 units)"
        )));
    }
    Ok(())
}
#[allow(dead_code)]
const CATALOG_FOLDER_THREAD: i16 = 3;
#[allow(dead_code)]
const CATALOG_FILE_THREAD: i16 = 4;

/// `HFSPlusBSDInfo` — the POSIX block every catalog file and folder record
/// carries at record offset 32.
///
/// This is how OS X does Unix permissions on HFS+: `ownerID` / `groupID` /
/// `fileMode` are the real uid, gid and mode (type bits included), and the
/// kernel honours them whenever the volume is mounted with ownership
/// enabled. A volume that has never been touched by OS X — one formatted by
/// Classic Mac OS, or by a tool that leaves the block zeroed — carries
/// `fileMode == 0`, which means "no POSIX info recorded" rather than
/// "mode 0000". [`Self::is_set`] is that distinction; surfacing a zero mode
/// as `Some(0)` would render every file as `----------`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct HfsPlusBsdInfo {
    pub(crate) owner_id: u32,
    pub(crate) group_id: u32,
    pub(crate) file_mode: u16,
}

impl HfsPlusBsdInfo {
    /// Record-body offset of the `HFSPlusBSDInfo` block.
    pub(crate) const OFFSET: usize = 32;

    /// Parse from a catalog record body. Short records read as unset.
    fn parse(rec: &[u8]) -> Self {
        if rec.len() < Self::OFFSET + 16 {
            return Self::default();
        }
        Self {
            owner_id: BigEndian::read_u32(&rec[Self::OFFSET..Self::OFFSET + 4]),
            group_id: BigEndian::read_u32(&rec[Self::OFFSET + 4..Self::OFFSET + 8]),
            // adminFlags @+8 and ownerFlags @+9 sit between; fileMode is
            // a u16 at +10 and `special` a u32 at +12.
            file_mode: BigEndian::read_u16(&rec[Self::OFFSET + 10..Self::OFFSET + 12]),
        }
    }

    /// Whether this record actually carries POSIX info.
    fn is_set(&self) -> bool {
        self.file_mode != 0
    }

    /// Stamp `mode`, `uid` and `gid` onto a `FileEntry`, but only when the
    /// record has POSIX info to report.
    fn apply_to(&self, fe: &mut FileEntry) {
        if !self.is_set() {
            return;
        }
        fe.mode = Some(self.file_mode as u32);
        fe.uid = Some(self.owner_id);
        fe.gid = Some(self.group_id);
    }
}

/// A parsed HFS+ catalog entry.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)] // catalog entries are short-lived per-record buffers; boxing adds heap churn
enum CatalogEntry {
    Folder {
        folder_id: u32,
        name: String,
        /// Mac-epoch seconds — the "modification date" the browser and
        /// `tar_export` surface.
        content_mod_date: u32,
        bsd: HfsPlusBsdInfo,
    },
    File {
        file_id: u32,
        name: String,
        data_size: u64,
        data_fork: ForkData,
        rsrc_size: u64,
        rsrc_fork: ForkData,
        /// 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 (userInfo.fdFlags) — bit 0x8000 is `kIsAlias`.
        finder_flags: u16,
        /// HFS+ file hardlink target inode number (`bsdInfo.special` u32).
        /// `Some` only when the FInfo type/creator are `hlnk`/`hfs+`. The
        /// inode itself lives at `iNode<N>` inside the volume's
        /// `HFS+ Private Data` directory.
        link_inode_num: Option<u32>,
        /// HFS+ directory hardlink target inode number. `Some` only when
        /// the FInfo type/creator are `fdrp`/`MACS`. The directory inode
        /// lives at `dir_<N>` inside the volume's
        /// `.HFS+ Private Directory Data\r` directory and replaces the
        /// stub when surfaced through `list_directory`.
        dir_link_inode_num: Option<u32>,
        /// Mac-epoch seconds — the "modification date" the browser and
        /// `tar_export` surface.
        content_mod_date: u32,
        bsd: HfsPlusBsdInfo,
    },
}

/// Magic 4-byte type code on file hardlink stubs (`fdType`).
const HFSPLUS_HARDLINK_FILE_TYPE: &[u8; 4] = b"hlnk";
/// Magic 4-byte creator code on file hardlink stubs (`fdCreator`).
const HFSPLUS_HARDLINK_FILE_CREATOR: &[u8; 4] = b"hfs+";
/// Magic 4-byte type code on directory hardlink stubs (10.5+).
const HFSPLUS_HARDLINK_DIR_TYPE: &[u8; 4] = b"fdrp";
/// Magic 4-byte creator code on directory hardlink stubs.
const HFSPLUS_HARDLINK_DIR_CREATOR: &[u8; 4] = b"MACS";

/// Free-function form of `HfsPlusFilesystem::catalog_compare`, callable
/// from sibling modules (e.g. `hfsplus_fsck`) that only have the raw
/// catalog bytes and no `<R>`-typed filesystem instance.
pub(crate) fn catalog_compare_keys(a: &[u8], b: &[u8], case_sensitive: bool) -> Ordering {
    if a.len() < 8 || b.len() < 8 {
        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 = BigEndian::read_u16(&a[6..8]) as usize;
    let name_len_b = BigEndian::read_u16(&b[6..8]) as usize;
    let name_a: Vec<u16> = a[8..8 + name_len_a.min((a.len() - 8) / 2) * 2]
        .chunks_exact(2)
        .map(BigEndian::read_u16)
        .collect();
    let name_b: Vec<u16> = b[8..8 + name_len_b.min((b.len() - 8) / 2) * 2]
        .chunks_exact(2)
        .map(BigEndian::read_u16)
        .collect();
    hfs_common::compare_hfsplus_keys(parent_a, &name_a, parent_b, &name_b, case_sensitive)
}

/// Name of the hidden directory at the volume root that stores HFS+ file
/// hardlink inodes (TN1150). Four NUL bytes followed by ASCII text — the
/// nulls keep the directory invisible to clients that ignore zero-byte
/// filename units.
fn hfsplus_private_dir_name() -> String {
    let mut s = String::with_capacity(4 + 17);
    for _ in 0..4 {
        s.push('\u{0}');
    }
    s.push_str("HFS+ Private Data");
    s
}

/// Name of the hidden directory at the volume root that stores directory
/// hardlink inodes (10.5+). The trailing carriage return keeps the
/// directory hidden from clients that disallow `\r` in filenames.
fn hfsplus_dir_private_dir_name() -> String {
    let mut s = String::with_capacity(28 + 1);
    s.push_str(".HFS+ Private Directory Data");
    s.push('\u{D}');
    s
}

/// HFS+ filesystem implementation.
pub struct HfsPlusFilesystem<R: Read + Seek> {
    reader: R,
    partition_offset: u64,
    /// Partition length when the caller knows it; the alternate volume header
    /// sits 1024 bytes before the partition end, not before total_blocks * bs.
    partition_size: Option<u64>,
    vh: HfsPlusVolumeHeader,
    /// Cached catalog B-tree file data.
    catalog_data: Vec<u8>,
    /// B-tree header for the catalog file.
    catalog_header: BTreeHeaderRecord,
    /// Volume label (from catalog root folder thread).
    label: String,
    /// Cached allocation bitmap (loaded on first write operation).
    bitmap: Option<Vec<u8>>,
    /// Cached extents-overflow B-tree file data (None until first fragmented
    /// fork forces it to load; stays None on volumes with no overflow file).
    extents_overflow_data: Option<Vec<u8>>,
    /// Cached attributes B-tree file data. `None` until Phase 5 (xattr
    /// write path) populates it; included in the snapshot now so
    /// rollback semantics are forward-compatible.
    attributes_data: Option<Vec<u8>>,
    /// Set of CNIDs that own at least one record in the attributes B-tree
    /// (extended attributes). Populated only by `prepare_for_edit` — `None`
    /// for read-only opens. Until the xattr write path lands (Phase 5 of
    /// `docs/hfsplus_enhancements.md`), `delete_entry` refuses any CNID in
    /// this set so we don't silently leave dangling attribute records.
    xattr_cnids: Option<HashSet<u32>>,
    /// File hardlink resolution map (iNodeNum -> real inode CNID). Populated
    /// lazily the first time a `list_directory` / `read_file` call needs to
    /// follow a hardlink stub. `None` until consulted; `Some(map)` after the
    /// first lookup, with `map` empty on volumes with no hardlinks. Cleared
    /// by snapshot rollback so writes that move the private dir don't leave
    /// a stale map behind.
    hardlink_inode_map: Option<HashMap<u32, u32>>,
    /// Directory hardlink resolution map (dir-inode iNodeNum -> directory
    /// CNID). Same lazy/snapshot semantics as `hardlink_inode_map`.
    dir_hardlink_inode_map: Option<HashMap<u32, u32>>,
    /// Boot blocks staged via `set_boot_blocks` and flushed by
    /// `do_sync_metadata`. Used by the clone path (Step 21) to carry the
    /// source's first 1024 bytes onto the freshly-built target verbatim.
    /// Not part of the snapshot — clone stages once at the end and only
    /// the final `sync_metadata` writes to disk.
    pending_boot_blocks: Option<Box<[u8; 1024]>>,
}

/// Snapshot of every byte/value an HFS+ mutation can touch — taken at the
/// start of each `EditableFilesystem` method so a mid-flight failure can
/// rewind to byte-identical pre-call state instead of leaving the catalog
/// half-applied.
///
/// Forward-compatible with Phase 5 (attributes B-tree write side) — the
/// `attributes_data` slot is captured today even though it's always `None`
/// until xattr writes ship.
#[derive(Debug, Clone)]
pub struct HfsPlusSnapshot {
    vh: HfsPlusVolumeHeader,
    catalog_data: Vec<u8>,
    catalog_header: BTreeHeaderRecord,
    bitmap: Option<Vec<u8>>,
    extents_overflow_data: Option<Vec<u8>>,
    attributes_data: Option<Vec<u8>>,
    xattr_cnids: Option<HashSet<u32>>,
    hardlink_inode_map: Option<HashMap<u32, u32>>,
    dir_hardlink_inode_map: Option<HashMap<u32, u32>>,
}

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

    /// [`open`](Self::open) with the partition length, so the alternate volume
    /// header is written where Apple's tools look for it.
    pub fn open_sized(
        mut reader: R,
        partition_offset: u64,
        partition_size: Option<u64>,
    ) -> Result<Self, FilesystemError> {
        // Read volume header at offset + 1024
        reader.seek(SeekFrom::Start(partition_offset + 1024))?;
        let mut vh_buf = [0u8; 512];
        reader.read_exact(&mut vh_buf)?;
        let vh = HfsPlusVolumeHeader::parse(&vh_buf)?;

        if vh.block_size == 0 || !vh.block_size.is_power_of_two() {
            return Err(FilesystemError::Parse(format!(
                "invalid block size: {}",
                vh.block_size
            )));
        }

        // Sanity bound: the catalog and extents-overflow forks must fit
        // within the volume. A corrupt logical_size that says "50 GiB" on a
        // 58 GiB volume would otherwise drive `Vec::with_capacity` into swap.
        let volume_bytes = vh.total_blocks as u64 * vh.block_size as u64;
        if vh.catalog_file.logical_size > volume_bytes {
            return Err(FilesystemError::Parse(format!(
                "catalog file logical_size {} exceeds volume size {}",
                vh.catalog_file.logical_size, volume_bytes
            )));
        }
        if vh.extents_file.logical_size > volume_bytes {
            return Err(FilesystemError::Parse(format!(
                "extents-overflow file logical_size {} exceeds volume size {}",
                vh.extents_file.logical_size, volume_bytes
            )));
        }

        log::debug!(
            "[HFS+ open @ {partition_offset}] vh ok: block_size={}, total_blocks={} ({} bytes), \
             catalog={} bytes, extents_file={} bytes, alloc_file={} bytes",
            vh.block_size,
            vh.total_blocks,
            volume_bytes,
            vh.catalog_file.logical_size,
            vh.extents_file.logical_size,
            vh.allocation_file.logical_size,
        );

        // Eagerly load the extents-overflow B-tree (its own 8 inline extents
        // are authoritative — the overflow file can't have overflow records),
        // then read the catalog with overflow support. Volumes with hundreds
        // of thousands of files can have catalog forks that exceed 8 inline
        // extents; reading inline-only would silently truncate and lead to
        // corrupt walks (and, with no cycle detection, hangs).
        log::debug!("[HFS+ open] reading extents-overflow file...");
        let extents_overflow_data = if vh.extents_file.logical_size > 0 {
            Some(read_fork(
                &mut reader,
                partition_offset,
                vh.block_size,
                &vh.extents_file,
            )?)
        } else {
            None
        };
        log::debug!(
            "[HFS+ open] extents-overflow loaded: {} bytes",
            extents_overflow_data.as_ref().map(|d| d.len()).unwrap_or(0)
        );

        log::debug!("[HFS+ open] reading catalog file...");
        let catalog_data = read_fork_with_overflow(
            &mut reader,
            partition_offset,
            vh.block_size,
            &vh.catalog_file,
            HFSPLUS_CATALOG_FILE_ID,
            HFSPLUS_FORK_DATA,
            extents_overflow_data.as_deref(),
        )?;
        log::debug!("[HFS+ open] catalog loaded: {} bytes", catalog_data.len());

        // Parse B-tree header from node 0
        if catalog_data.len() < 14 + 106 {
            return Err(FilesystemError::Parse(
                "catalog file too small for B-tree header".into(),
            ));
        }
        let catalog_header = BTreeHeaderRecord::parse(&catalog_data[14..14 + 106]);
        log::debug!(
            "[HFS+ open] catalog btree: depth={}, root_node={}, first_leaf={}, last_leaf={}, \
             node_size={}, total_nodes={}, free_nodes={}",
            catalog_header.depth,
            catalog_header.root_node,
            catalog_header.first_leaf_node,
            catalog_header.last_leaf_node,
            catalog_header.node_size,
            catalog_header.total_nodes,
            catalog_header.free_nodes,
        );

        // Try to find the volume label from the root folder thread.
        log::debug!("[HFS+ open] scanning catalog for volume label...");
        let label = find_volume_label(&catalog_data, &catalog_header);
        log::debug!("[HFS+ open] volume label: {:?}", label);

        Ok(HfsPlusFilesystem {
            reader,
            partition_offset,
            partition_size,
            vh,
            catalog_data,
            catalog_header,
            label,
            bitmap: None,
            extents_overflow_data,
            attributes_data: None,
            xattr_cnids: None,
            hardlink_inode_map: None,
            dir_hardlink_inode_map: None,
            pending_boot_blocks: None,
        })
    }

    // ---- Accessors for `hfsplus_clone` (Step 10 of
    //      docs/hfsplus_enhancements.md). The clone module captures source
    //      metadata without taking a reference to the private VH/ForkData
    //      types — these helpers expose primitives + raw fork bytes.

    #[allow(dead_code)] // used in later HFS+ clone steps
    pub(crate) fn partition_offset(&self) -> u64 {
        self.partition_offset
    }

    pub fn block_size(&self) -> u32 {
        self.vh.block_size
    }

    pub(crate) fn total_blocks(&self) -> u32 {
        self.vh.total_blocks
    }

    pub(crate) fn signature(&self) -> u16 {
        self.vh.signature
    }

    pub(crate) fn vh_attributes(&self) -> u32 {
        self.vh.attributes
    }

    /// True when the volume header's journaled bit is set.
    pub fn is_journaled(&self) -> bool {
        self.vh.attributes & HFSPLUS_VOLUME_JOURNALED_BIT != 0
    }

    /// Locate, parse, and summarize the journal without applying any state.
    /// Returns `Ok(None)` when the volume is not journaled. The summaries walk
    /// `start -> end`; the walk stops early (and `partial` is set) on the first
    /// corrupt or short transaction, mirroring how macOS replay behaves.
    ///
    /// See `docs/hfsplus_enhancements.md` Phase 9, Step 24.
    /// Locate and parse the JIB + journal header. `Ok(None)` when the volume
    /// is not journaled. Shared by `read_journal` and `journal_detail`.
    fn locate_journal(
        &mut self,
    ) -> Result<
        Option<(
            crate::hfsplus_journal::JournalInfoBlock,
            crate::hfsplus_journal::JournalHeader,
        )>,
        FilesystemError,
    > {
        use crate::hfsplus_journal::{JournalHeader, JournalInfoBlock};

        if !self.is_journaled() {
            return Ok(None);
        }
        let to_fs = |e: crate::hfsplus_journal::JournalError| {
            FilesystemError::InvalidData(format!("journal: {e}"))
        };

        // JIB lives at allocation block `journal_info_block`.
        let jib_byte =
            self.partition_offset + self.vh.journal_info_block as u64 * self.vh.block_size as u64;
        self.reader.seek(SeekFrom::Start(jib_byte))?;
        let mut jib_buf = vec![0u8; 512];
        self.reader.read_exact(&mut jib_buf)?;
        let jib = JournalInfoBlock::parse(&jib_buf).map_err(to_fs)?;

        // The journal header's fixed fields live in the first 512 bytes.
        self.reader
            .seek(SeekFrom::Start(self.partition_offset + jib.offset))?;
        let mut jh_buf = vec![0u8; 512];
        self.reader.read_exact(&mut jh_buf)?;
        let header = JournalHeader::parse(&jh_buf).map_err(to_fs)?;
        Ok(Some((jib, header)))
    }

    /// Byte ranges (relative to the partition) of the volume's metadata
    /// structures, for classifying which subsystem a journaled block targets.
    fn metadata_regions(&self) -> Vec<crate::hfsplus_journal::MetadataRegion> {
        use crate::hfsplus_journal::MetadataRegion;
        let bs = self.vh.block_size as u64;
        let mut regions = vec![MetadataRegion {
            name: "volume header",
            start: 1024,
            end: 1536,
        }];
        let fork = |name: &'static str, fork: &ForkData| -> Option<MetadataRegion> {
            let first = fork.extents.iter().find(|e| !e.is_empty())?;
            let start = first.start_block as u64 * bs;
            let bytes = fork.total_blocks as u64 * bs;
            Some(MetadataRegion {
                name,
                start,
                end: start + bytes,
            })
        };
        for (name, f) in [
            ("allocation bitmap", &self.vh.allocation_file),
            ("extents btree", &self.vh.extents_file),
            ("catalog btree", &self.vh.catalog_file),
            ("attributes btree", &self.vh.attributes_file),
            ("startup file", &self.vh.startup_file),
        ] {
            if let Some(r) = fork(name, f) {
                regions.push(r);
            }
        }
        regions
    }

    /// Decode the journal into per-transaction, per-block detail for the GUI
    /// history viewer (Step 29). Block previews are capped; classification is
    /// against [`metadata_regions`]. `Ok(None)` when not journaled.
    pub fn journal_detail(
        &mut self,
    ) -> Result<Option<crate::hfsplus_journal::JournalDetail>, FilesystemError> {
        let Some((jib, header)) = self.locate_journal()? else {
            return Ok(None);
        };
        let regions = self.metadata_regions();
        let detail = crate::hfsplus_journal::read_journal_detail(
            &mut self.reader,
            self.partition_offset,
            jib,
            header,
            regions,
        );
        Ok(Some(detail))
    }

    pub fn read_journal(
        &mut self,
    ) -> Result<Option<crate::hfsplus_journal::JournalState>, FilesystemError> {
        use crate::hfsplus_journal::JournalWalker;

        let Some((jib, header)) = self.locate_journal()? else {
            return Ok(None);
        };

        let mut transactions = Vec::new();
        let mut partial = false;
        let mut checksum_mismatch = None;
        let mut sequence_jumps = Vec::new();
        {
            let mut walker =
                JournalWalker::new(&mut self.reader, self.partition_offset, &jib, &header);
            let mut prev_seq: Option<u32> = None;
            while let Some(item) = walker.next() {
                match item {
                    Ok(view) => {
                        let seq = view.sequence_num;
                        if let Some(prev) = prev_seq {
                            // macOS expects each transaction's sequence to be
                            // prev or prev+1; anything else is a jump.
                            if seq != prev && seq != prev.wrapping_add(1) {
                                sequence_jumps.push((prev, seq));
                            }
                        }
                        prev_seq = Some(seq);
                        transactions.push(view.summary());
                    }
                    Err(crate::hfsplus_journal::JournalError::CorruptTransaction {
                        sequence_num,
                    }) => {
                        checksum_mismatch = Some(sequence_num);
                        partial = true;
                        break;
                    }
                    Err(_) => {
                        partial = true;
                        break;
                    }
                }
            }
        }

        Ok(Some(crate::hfsplus_journal::JournalState {
            info: jib,
            header,
            transactions,
            partial,
            checksum_mismatch,
            sequence_jumps,
        }))
    }

    pub(crate) fn vh_create_date(&self) -> u32 {
        self.vh.create_date
    }

    pub(crate) fn vh_modify_date(&self) -> u32 {
        self.vh.modify_date
    }

    pub(crate) fn vh_backup_date(&self) -> u32 {
        self.vh.backup_date
    }

    pub(crate) fn vh_checked_date(&self) -> u32 {
        self.vh.checked_date
    }

    pub(crate) fn vh_file_count(&self) -> u32 {
        self.vh.file_count
    }

    pub(crate) fn vh_folder_count(&self) -> u32 {
        self.vh.folder_count
    }

    pub(crate) fn vh_finder_info(&self) -> [u32; 8] {
        self.vh.finder_info
    }

    pub(crate) fn vh_free_blocks(&self) -> u32 {
        self.vh.free_blocks
    }

    #[allow(dead_code)] // used in later HFS+ clone steps
    pub(crate) fn vh_next_catalog_id(&self) -> u32 {
        self.vh.next_catalog_id
    }

    /// Read and return the allocation-file bitmap. Routes through the
    /// extents-overflow-aware fork reader, so volumes whose allocation file
    /// spills past 8 inline extents work correctly.
    pub(crate) fn read_allocation_bitmap_for_fsck(&mut self) -> Result<Vec<u8>, FilesystemError> {
        self.read_allocation_bitmap()
    }

    /// `total_blocks` field of the source's catalog file fork. Used by the
    /// streamed defrag planner to size the target's catalog B-tree (with
    /// a small safety margin) so it has enough free nodes to host every
    /// inserted record without running out of B-tree node slots.
    pub(crate) fn vh_catalog_total_blocks(&self) -> u32 {
        self.vh.catalog_file.total_blocks
    }

    /// `total_blocks` field of the source's extents-overflow file fork.
    /// Most defrag targets pack files contiguously and need little or no
    /// overflow capacity, but matching source size is a safe ceiling.
    pub(crate) fn vh_extents_total_blocks(&self) -> u32 {
        self.vh.extents_file.total_blocks
    }

    /// `total_blocks` field of the source's attributes file fork. Zero on
    /// volumes without xattrs.
    pub(crate) fn vh_attributes_total_blocks(&self) -> u32 {
        self.vh.attributes_file.total_blocks
    }

    pub(crate) fn label(&self) -> &str {
        &self.label
    }

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

    pub(crate) fn catalog_node_size(&self) -> usize {
        self.catalog_header.node_size as usize
    }

    pub(crate) fn catalog_first_leaf(&self) -> u32 {
        self.catalog_header.first_leaf_node
    }

    /// The extents-overflow B-tree as read from disk, for fsck.
    pub(crate) fn extents_overflow_data(&self) -> Option<&[u8]> {
        self.extents_overflow_data.as_deref()
    }

    /// Partition length when the opener knew it; where the alternate header lives.
    pub(crate) fn partition_size(&self) -> Option<u64> {
        self.partition_size
    }

    /// The attributes B-tree, loaded on first use, for fsck.
    pub(crate) fn attributes_data_for_fsck(&mut self) -> Result<Option<&[u8]>, FilesystemError> {
        if self.vh.attributes_file.logical_size == 0 {
            return Ok(None);
        }
        self.ensure_attributes_loaded()?;
        Ok(self.attributes_data.as_deref())
    }

    pub(crate) fn case_sensitive_catalog(&self) -> bool {
        self.case_sensitive()
    }

    /// Read the first 1024 bytes of the partition (HFS+ "boot blocks" —
    /// always zero on macOS-formatted volumes but copied verbatim by clone).
    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)
    }

    /// Open a streaming `Read` over a user fork without buffering its bytes.
    /// Used by the clone pipeline (Step 21+) so a 38 GiB volume's data
    /// forks don't have to materialise in RAM. The returned reader borrows
    /// `self`'s underlying I/O for its lifetime — drop it before issuing
    /// any other read against this filesystem.
    pub(crate) fn fork_stream_reader(
        &mut self,
        file_id: u32,
        fork_type: u8,
        fork_record: &[u8; 80],
    ) -> Result<ForkStreamReader<'_, R>, FilesystemError> {
        let fork = ForkData::parse(fork_record);
        let logical_size = fork.logical_size;

        // Resolve every extent (inline + overflow) into device-offset / length
        // pairs once at construction. The extents-overflow B-tree was already
        // loaded eagerly during `open`; consulting it again here is O(records).
        let block_size = self.vh.block_size as u64;
        let mut extents: Vec<(u64, u64)> = Vec::new();
        let mut covered: u64 = 0;
        for ext in fork.extents.iter() {
            if ext.block_count == 0 {
                continue;
            }
            let off = self.partition_offset + ext.start_block as u64 * block_size;
            let len = ext.block_count as u64 * block_size;
            extents.push((off, len));
            covered += len;
        }
        if covered < logical_size {
            let inline_blocks: u32 = fork.extents.iter().map(|e| e.block_count).sum();
            let overflow = match self.extents_overflow_data.as_deref() {
                Some(data) => {
                    collect_hfsplus_overflow_extents(data, file_id, fork_type, inline_blocks)
                }
                None => {
                    return Err(FilesystemError::InvalidData(format!(
                        "file {file_id} fork {fork_type:#x}: {} bytes requested but only \
                         {} bytes in inline extents and no extents-overflow B-tree available",
                        logical_size, covered
                    )));
                }
            };
            for ext in overflow {
                if ext.block_count == 0 {
                    continue;
                }
                let off = self.partition_offset + ext.start_block as u64 * block_size;
                let len = ext.block_count as u64 * block_size;
                extents.push((off, len));
                covered += len;
                if covered >= logical_size {
                    break;
                }
            }
            if covered < logical_size {
                return Err(FilesystemError::InvalidData(format!(
                    "file {file_id} fork {fork_type:#x}: extents (inline + overflow) \
                     cover {covered} of {logical_size} bytes"
                )));
            }
        }

        Ok(ForkStreamReader {
            reader: &mut self.reader,
            extents,
            logical_size,
            pos: 0,
            cur_extent: 0,
            cur_extent_consumed: 0,
        })
    }

    /// Capture the full mutable state for snapshot/rollback. Cheap on the
    /// scale of a single mutation: catalog + bitmap clone is O(volume
    /// metadata size), not O(volume size).
    pub fn snapshot(&self) -> HfsPlusSnapshot {
        HfsPlusSnapshot {
            vh: self.vh.clone(),
            catalog_data: self.catalog_data.clone(),
            catalog_header: self.catalog_header.clone(),
            bitmap: self.bitmap.clone(),
            extents_overflow_data: self.extents_overflow_data.clone(),
            attributes_data: self.attributes_data.clone(),
            xattr_cnids: self.xattr_cnids.clone(),
            hardlink_inode_map: self.hardlink_inode_map.clone(),
            dir_hardlink_inode_map: self.dir_hardlink_inode_map.clone(),
        }
    }

    /// Restore previously captured state. Used by the snapshot guard
    /// around every `EditableFilesystem` mutation when the body returns
    /// `Err`.
    pub fn restore_snapshot(&mut self, snap: HfsPlusSnapshot) {
        self.vh = snap.vh;
        self.catalog_data = snap.catalog_data;
        self.catalog_header = snap.catalog_header;
        self.bitmap = snap.bitmap;
        self.extents_overflow_data = snap.extents_overflow_data;
        self.attributes_data = snap.attributes_data;
        self.xattr_cnids = snap.xattr_cnids;
        self.hardlink_inode_map = snap.hardlink_inode_map;
        self.dir_hardlink_inode_map = snap.dir_hardlink_inode_map;
    }

    /// Sanity-check the volume for edit-mode compatibility and pre-load the
    /// attributes-B-tree CNID set. Called by `open_editable_filesystem` —
    /// not by read-only opens, so the cost is paid only when we're about
    /// to mutate.
    ///
    /// Journaled volumes are accepted only when the journal is *clean* (empty,
    /// `start == end`) — the cleanly-unmounted case. A clean journal has no
    /// pending state, so editing the catalog in place and leaving the journal
    /// empty keeps the volume valid for macOS (it replays nothing on mount).
    /// A *dirty* journal carries metadata the catalog hasn't absorbed yet;
    /// editing on top of that stale catalog would lose the journaled changes,
    /// so we still refuse it here. In-place transactional writes that journal
    /// our own mutations and recover dirty volumes are the remaining half of
    /// Step 27 (`docs/hfsplus_enhancements.md`) and are not yet wired in.
    ///
    /// xattr-bearing volumes succeed but later `delete_entry` calls against any
    /// of the cached CNIDs are refused at the source until Phase 5 lands.
    pub fn prepare_for_edit(&mut self) -> Result<(), FilesystemError> {
        if self.vh.attributes & HFSPLUS_VOLUME_JOURNALED_BIT != 0 {
            match self.locate_journal() {
                Ok(Some((_jib, header))) if !header.is_empty() => {
                    return Err(FilesystemError::Unsupported(
                        "dirty journaled HFS+ volume — mount and cleanly unmount it in macOS \
                         to flush the journal, then retry (or open read-only)"
                            .into(),
                    ));
                }
                Ok(_) => {
                    // Clean journal (or, defensively, none) — safe to edit in
                    // place; the journal stays empty and valid.
                }
                Err(e) => {
                    return Err(FilesystemError::Unsupported(format!(
                        "journaled HFS+ volume with an unreadable journal ({e}) — \
                         open read-only"
                    )));
                }
            }
        }

        // No attributes file → nothing to scan, leave the set as `None`
        // (delete_entry treats it as "no xattr-bearing CNIDs known").
        if self.vh.attributes_file.logical_size == 0 {
            self.xattr_cnids = Some(HashSet::new());
            return Ok(());
        }

        // Load the attributes B-tree fork (with overflow extents if needed)
        // and walk its leaves to harvest fileIDs from each record key.
        let (attr_data, attr_header) = self
            .ensure_attributes_loaded()?
            .expect("attributes_file.logical_size > 0 must produce a header (checked just above)");
        let node_size = attr_header.node_size as usize;
        let mut cnids: HashSet<u32> = HashSet::new();
        hfs_common::walk_leaf_records::<(), _>(
            attr_data,
            attr_header.first_leaf_node,
            node_size,
            |_node_idx, _rec_idx, _abs_off, rec_bytes| {
                if rec_bytes.len() < 2 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec_bytes[0..2]) as usize;
                // key body must hold at least pad(2) + fileID(4)
                if key_len < 6 || 2 + 6 > rec_bytes.len() {
                    return None;
                }
                let file_id = BigEndian::read_u32(&rec_bytes[4..8]);
                cnids.insert(file_id);
                None
            },
        );
        log::debug!(
            "[HFS+ open_editable] attributes B-tree carries records for {} CNIDs",
            cnids.len()
        );
        self.xattr_cnids = Some(cnids);
        Ok(())
    }

    /// Lazy-load the attributes B-tree file into `self.attributes_data`. Returns
    /// `Ok(None)` if the volume has no attributes file (`logical_size == 0`),
    /// otherwise `Ok(Some((&[u8], header)))`.
    ///
    /// Subsequent calls reuse the cached buffer, so xattr lookups across many
    /// CNIDs cost one fork read total.
    fn ensure_attributes_loaded(
        &mut self,
    ) -> Result<Option<(&[u8], BTreeHeaderRecord)>, FilesystemError> {
        if self.vh.attributes_file.logical_size == 0 {
            return Ok(None);
        }
        if self.attributes_data.is_none() {
            let data = read_fork_with_overflow(
                &mut self.reader,
                self.partition_offset,
                self.vh.block_size,
                &self.vh.attributes_file,
                HFSPLUS_ATTRIBUTES_FILE_ID,
                HFSPLUS_FORK_DATA,
                self.extents_overflow_data.as_deref(),
            )?;
            if data.len() < 14 + 106 {
                return Err(FilesystemError::Parse(
                    "attributes file too small for B-tree header".into(),
                ));
            }
            self.attributes_data = Some(data);
        }
        let data = self.attributes_data.as_deref().expect("just populated");
        let header = BTreeHeaderRecord::parse(&data[14..14 + 106]);
        Ok(Some((data, header)))
    }

    /// Return every extended-attribute record attached to `cnid`, decoded into
    /// [`XattrRecord`]. Returns an empty vec if the volume has no attributes
    /// file or `cnid` owns no xattrs.
    ///
    /// Inline payloads are decoded eagerly (the common case for
    /// `com.apple.FinderInfo` and the rest of the `com.apple.*` namespace).
    /// Fork/extents records are returned with their on-disk metadata; the
    /// actual fork bytes are read on demand by Step 13's xattr write/read
    /// path, not here.
    ///
    /// HFS+ attribute key layout (after the 2-byte keyLength prefix):
    ///   pad (2) | fileID (4) | startBlock (4) | nameLen (2) | name (UTF-16BE)
    /// Records are 2-byte aligned; data follows the key at the next even
    /// offset and starts with a u32 record type (`HFSPLUS_ATTR_*`).
    #[allow(dead_code)] // first user lands in Step 13/14 (xattr writes + clone replay)
    pub(crate) fn list_xattrs(&mut self, cnid: u32) -> Result<Vec<XattrRecord>, FilesystemError> {
        let Some((data, header)) = self.ensure_attributes_loaded()? else {
            return Ok(Vec::new());
        };
        let node_size = header.node_size as usize;
        let first_leaf = header.first_leaf_node;
        let mut out: Vec<XattrRecord> = Vec::new();
        hfs_common::walk_leaf_records::<(), _>(
            data,
            first_leaf,
            node_size,
            |_node_idx, _rec_idx, _abs_off, rec_bytes| {
                if rec_bytes.len() < 2 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec_bytes[0..2]) as usize;
                // key body must hold pad(2) + fileID(4) + startBlock(4) + nameLen(2)
                if key_len < 12 || 2 + key_len > rec_bytes.len() {
                    return None;
                }
                let file_id = BigEndian::read_u32(&rec_bytes[4..8]);
                if file_id != cnid {
                    return None;
                }
                let start_block = BigEndian::read_u32(&rec_bytes[8..12]);
                let name_len = BigEndian::read_u16(&rec_bytes[12..14]) as usize;
                let name_bytes_end = 14 + name_len * 2;
                if name_bytes_end > 2 + key_len {
                    return None;
                }
                let name = decode_utf16be(&rec_bytes[14..name_bytes_end]);

                // Record data starts at next even offset after the key (the
                // key body is always an even number of bytes — pad+id+sb+nl
                // is 12 plus 2*name_len — so data immediately follows).
                let data_off = 2 + key_len;
                if data_off + 4 > rec_bytes.len() {
                    return None;
                }
                let record_type = BigEndian::read_u32(&rec_bytes[data_off..data_off + 4]);
                let kind = match record_type {
                    HFSPLUS_ATTR_INLINE_DATA => {
                        // recordType(4) + reserved[2](8) + attrSize(4) + attrData[attrSize]
                        let header_end = data_off + 4 + 8 + 4;
                        if header_end > rec_bytes.len() {
                            return None;
                        }
                        let attr_size =
                            BigEndian::read_u32(&rec_bytes[header_end - 4..header_end]) as usize;
                        if header_end + attr_size > rec_bytes.len() {
                            return None;
                        }
                        XattrKind::Inline(rec_bytes[header_end..header_end + attr_size].to_vec())
                    }
                    HFSPLUS_ATTR_FORK_DATA => {
                        // recordType(4) + reserved(4) + HFSPlusForkData(80)
                        let fork_off = data_off + 4 + 4;
                        if fork_off + 80 > rec_bytes.len() {
                            return None;
                        }
                        XattrKind::Fork(ForkData::parse(&rec_bytes[fork_off..fork_off + 80]))
                    }
                    HFSPLUS_ATTR_EXTENTS => {
                        // recordType(4) + reserved(4) + 8 × ExtentDescriptor(8) = 64
                        let ext_off = data_off + 4 + 4;
                        if ext_off + 64 > rec_bytes.len() {
                            return None;
                        }
                        let mut extents = Vec::with_capacity(8);
                        for i in 0..8 {
                            let e = ExtentDescriptor::parse(
                                &rec_bytes[ext_off + i * 8..ext_off + (i + 1) * 8],
                            );
                            extents.push(e);
                        }
                        XattrKind::Extents(extents)
                    }
                    _ => {
                        log::warn!(
                            "[HFS+ list_xattrs] unknown attribute record type 0x{:x} \
                             on cnid={} name={:?}; skipping",
                            record_type,
                            cnid,
                            name
                        );
                        return None;
                    }
                };
                out.push(XattrRecord {
                    name,
                    start_block,
                    kind,
                });
                None
            },
        );
        Ok(out)
    }

    /// List all children of a given parent CNID.
    ///
    /// HFS+ catalog records are ordered by (parent_id, name), so all children
    /// of a given parent occupy a contiguous run in the leaf chain. We stop
    /// the walk as soon as we encounter a record with parent_id > target —
    /// otherwise listing the root of a 500k-file volume would scan every
    /// leaf node in the catalog. The `visited` set guards against cycles
    /// from corrupt `next` pointers.
    fn list_children(&self, parent_cnid: u32) -> Result<Vec<CatalogEntry>, FilesystemError> {
        let node_size = self.catalog_header.node_size as usize;
        if node_size == 0 {
            return Ok(vec![]);
        }

        let mut results = Vec::new();
        // Descend the catalog B-tree to find the leaf that would contain the
        // smallest key for this parent_cnid (i.e. (parent_cnid, "")). Walking
        // forward from there skips the leaves that hold smaller parent_cnids
        // — for high-CNID parents on a 24k-node catalog, that's the difference
        // between O(node_count) per call and O(depth + matches).
        let header = hfs_common::BTreeHeader::read(&self.catalog_data);
        let search_key = Self::build_catalog_key(parent_cnid, "");
        let cs = self.case_sensitive();
        let cmp = |a: &[u8], b: &[u8]| Self::catalog_compare(a, b, cs);
        let (start_leaf, _chain) =
            hfs_common::btree_find_insert_leaf(&self.catalog_data, &header, &search_key, &cmp);
        let mut node_idx = if start_leaf != 0 {
            start_leaf
        } else {
            self.catalog_header.first_leaf_node
        };
        let mut visited: std::collections::HashSet<u32> = std::collections::HashSet::new();
        let mut seen_target = false;

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

            let desc = BTreeNodeDescriptor::parse(node);
            // kind -1 = leaf node
            if desc.kind != -1 {
                node_idx = desc.next;
                continue;
            }

            for i in 0..desc.num_records as usize {
                // Record offsets are stored at end of node, growing backward
                let offset_pos = node_size - 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 = BigEndian::read_u16(&node[rec_offset..rec_offset + 2]) as usize;
                if key_len < 6 || rec_offset + 2 + key_len > node.len() {
                    continue;
                }
                let key_data = &node[rec_offset + 2..rec_offset + 2 + key_len];

                // Key: parent_id (4) + name_length (2) + name (UTF-16BE)
                let key_parent_id = BigEndian::read_u32(&key_data[0..4]);
                if key_parent_id == parent_cnid {
                    seen_target = true;
                } else if key_parent_id > parent_cnid {
                    // Catalog is sorted by (parent_id, name). Once we pass
                    // the target, no further records will match. If we
                    // already collected matches we're done; if not, the
                    // target may still appear in a later leaf only if we
                    // somehow started past it (shouldn't happen). Either
                    // way, stop scanning.
                    break 'outer;
                } else {
                    // key_parent_id < parent_cnid: not yet at the target.
                    if seen_target {
                        // (defensive) records out of order — bail.
                        break 'outer;
                    }
                    continue;
                }

                let name_length = BigEndian::read_u16(&key_data[4..6]) as usize;
                let name = if name_length > 0 && 6 + name_length * 2 <= key_data.len() {
                    decode_utf16be(&key_data[6..6 + name_length * 2])
                } else {
                    String::new()
                };

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

                let record_type = BigEndian::read_i16(&node[rec_data_start..rec_data_start + 2]);
                let rec = &node[rec_data_start..];

                match record_type {
                    CATALOG_FOLDER => {
                        if rec.len() < 88 {
                            continue;
                        }
                        let folder_id = BigEndian::read_u32(&rec[8..12]);
                        // Content modification date lives at record offset
                        // 20 (Mac-epoch u32); the write path uses the same
                        // offset (see set_catalog_dates around line 4413).
                        let content_mod_date = BigEndian::read_u32(&rec[20..24]);
                        results.push(CatalogEntry::Folder {
                            folder_id,
                            name,
                            content_mod_date,
                            bsd: HfsPlusBsdInfo::parse(rec),
                        });
                    }
                    CATALOG_FILE => {
                        if rec.len() < 248 {
                            continue;
                        }
                        let file_id = BigEndian::read_u32(&rec[8..12]);
                        // FileInfo at offset 48: fdType(4) + fdCreator(4) + fdFlags(2)
                        let type_code: [u8; 4] = rec[48..52].try_into().unwrap();
                        let creator_code: [u8; 4] = rec[52..56].try_into().unwrap();
                        let finder_flags = BigEndian::read_u16(&rec[56..58]);
                        // BSD info at offset 32 (16 bytes); the `special` u32
                        // at byte 12 of that block (offset 44 of the record)
                        // is `iNodeNum` on hardlink stubs and the link
                        // count on inodes — we only consume the former.
                        let link_inode_num = if &rec[48..52] == HFSPLUS_HARDLINK_FILE_TYPE
                            && &rec[52..56] == HFSPLUS_HARDLINK_FILE_CREATOR
                        {
                            Some(BigEndian::read_u32(&rec[44..48]))
                        } else {
                            None
                        };
                        let dir_link_inode_num = if &rec[48..52] == HFSPLUS_HARDLINK_DIR_TYPE
                            && &rec[52..56] == HFSPLUS_HARDLINK_DIR_CREATOR
                        {
                            Some(BigEndian::read_u32(&rec[44..48]))
                        } else {
                            None
                        };
                        // Data fork at offset 88 (80 bytes)
                        let data_fork = ForkData::parse(&rec[88..168]);
                        // Resource fork at offset 168 (80 bytes)
                        let rsrc_fork = ForkData::parse(&rec[168..248]);
                        // HFS+ file record content-mod-date at offset 20
                        // (Mac-epoch u32) — same slot the folder record uses.
                        let content_mod_date = BigEndian::read_u32(&rec[20..24]);
                        results.push(CatalogEntry::File {
                            file_id,
                            name,
                            data_size: data_fork.logical_size,
                            data_fork,
                            rsrc_size: rsrc_fork.logical_size,
                            rsrc_fork,
                            type_code,
                            creator_code,
                            finder_flags,
                            link_inode_num,
                            dir_link_inode_num,
                            content_mod_date,
                            bsd: HfsPlusBsdInfo::parse(rec),
                        });
                    }
                    _ => {}
                }
            }

            node_idx = desc.next;
        }

        Ok(results)
    }

    /// Lazily build (and cache) the iNodeNum -> inode-CNID map by scanning
    /// the children of the volume's `HFS+ Private Data` directory. Returns
    /// `Ok(())` whether or not the directory exists; volumes without
    /// hardlinks end up with an empty map and the lookup short-circuits.
    fn ensure_hardlink_inode_map(&mut self) -> Result<(), FilesystemError> {
        if self.hardlink_inode_map.is_some() {
            return Ok(());
        }
        let mut map: HashMap<u32, u32> = HashMap::new();
        let private_name = hfsplus_private_dir_name();
        let private_cnid = self.list_children(2)?.into_iter().find_map(|c| match c {
            CatalogEntry::Folder {
                folder_id, name, ..
            } if name == private_name => Some(folder_id),
            _ => None,
        });
        if let Some(cnid) = private_cnid {
            for child in self.list_children(cnid)? {
                if let CatalogEntry::File { file_id, name, .. } = child {
                    if let Some(rest) = name.strip_prefix("iNode") {
                        if let Ok(inode_num) = rest.parse::<u32>() {
                            map.insert(inode_num, file_id);
                        }
                    }
                }
            }
        }
        self.hardlink_inode_map = Some(map);
        Ok(())
    }

    /// Resolve a file hardlink stub's iNodeNum to its inode CNID. Returns
    /// `None` when the volume has no `HFS+ Private Data` directory or the
    /// inode is missing — callers fall back to treating the entry as an
    /// ordinary file.
    fn resolve_hardlink_inode(&mut self, inode_num: u32) -> Result<Option<u32>, FilesystemError> {
        self.ensure_hardlink_inode_map()?;
        Ok(self
            .hardlink_inode_map
            .as_ref()
            .and_then(|m| m.get(&inode_num).copied()))
    }

    /// CNID of the volume's `HFS+ Private Data` directory, if present.
    /// Lookup is O(root.children); cheap enough that we don't cache.
    fn find_private_dir_cnid(&self) -> Result<Option<u32>, FilesystemError> {
        let private_name = hfsplus_private_dir_name();
        Ok(self.list_children(2)?.into_iter().find_map(|c| match c {
            CatalogEntry::Folder {
                folder_id, name, ..
            } if name == private_name => Some(folder_id),
            _ => None,
        }))
    }

    /// CNID of the volume's `.HFS+ Private Directory Data\r` directory, if
    /// present. Same cost profile as `find_private_dir_cnid`.
    fn find_dir_private_dir_cnid(&self) -> Result<Option<u32>, FilesystemError> {
        let dir_private_name = hfsplus_dir_private_dir_name();
        Ok(self.list_children(2)?.into_iter().find_map(|c| match c {
            CatalogEntry::Folder {
                folder_id, name, ..
            } if name == dir_private_name => Some(folder_id),
            _ => None,
        }))
    }

    /// Lazily build (and cache) the dir-hardlink iNodeNum -> directory-inode
    /// CNID map. Mirrors `ensure_hardlink_inode_map` but scans children of
    /// the directory-hardlink private dir for `dir_<N>` folders.
    fn ensure_dir_hardlink_inode_map(&mut self) -> Result<(), FilesystemError> {
        if self.dir_hardlink_inode_map.is_some() {
            return Ok(());
        }
        let mut map: HashMap<u32, u32> = HashMap::new();
        if let Some(cnid) = self.find_dir_private_dir_cnid()? {
            for child in self.list_children(cnid)? {
                if let CatalogEntry::Folder {
                    folder_id, name, ..
                } = child
                {
                    if let Some(rest) = name.strip_prefix("dir_") {
                        if let Ok(inode_num) = rest.parse::<u32>() {
                            map.insert(inode_num, folder_id);
                        }
                    }
                }
            }
        }
        self.dir_hardlink_inode_map = Some(map);
        Ok(())
    }

    /// Resolve a dir-hardlink stub's iNodeNum to the dir-inode CNID.
    fn resolve_dir_hardlink_inode(
        &mut self,
        inode_num: u32,
    ) -> Result<Option<u32>, FilesystemError> {
        self.ensure_dir_hardlink_inode_map()?;
        Ok(self
            .dir_hardlink_inode_map
            .as_ref()
            .and_then(|m| m.get(&inode_num).copied()))
    }

    /// If the catalog record at `(parent_cnid, name)` is a file hardlink stub
    /// (`fdType='hlnk' fdCreator='hfs+'`), return its target iNodeNum from
    /// `bsdInfo.special`. `Ok(None)` for ordinary files / folders / missing
    /// records — callers treat that as "not a hardlink".
    fn read_file_record_link_inode_num(
        &self,
        parent_cnid: u32,
        name: &str,
    ) -> Result<Option<u32>, FilesystemError> {
        let Some((_, _, abs_off)) = self.find_catalog_record(parent_cnid, name) else {
            return Ok(None);
        };
        if abs_off + 2 > self.catalog_data.len() {
            return Ok(None);
        }
        let key_len = BigEndian::read_u16(&self.catalog_data[abs_off..abs_off + 2]) as usize;
        let mut body_start = abs_off + 2 + key_len;
        if !body_start.is_multiple_of(2) {
            body_start += 1;
        }
        if body_start + 56 > self.catalog_data.len() {
            return Ok(None);
        }
        let record_type = BigEndian::read_i16(&self.catalog_data[body_start..body_start + 2]);
        if record_type != CATALOG_FILE {
            return Ok(None);
        }
        if &self.catalog_data[body_start + 48..body_start + 52] != HFSPLUS_HARDLINK_FILE_TYPE
            || &self.catalog_data[body_start + 52..body_start + 56] != HFSPLUS_HARDLINK_FILE_CREATOR
        {
            return Ok(None);
        }
        Ok(Some(BigEndian::read_u32(
            &self.catalog_data[body_start + 44..body_start + 48],
        )))
    }

    /// Find a file record by its file_id (CNID) in the catalog B-tree.
    /// Returns (data_fork, resource_fork).
    fn find_file_by_id(&self, file_id: u32) -> Option<(ForkData, ForkData)> {
        let node_size = self.catalog_header.node_size as usize;
        let first_leaf = self.catalog_header.first_leaf_node;

        hfs_common::walk_leaf_records(
            &self.catalog_data,
            first_leaf,
            node_size,
            |_node_idx, _rec_idx, _abs_off, rec| {
                if rec.len() < 8 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
                if key_len < 6 || 2 + key_len > rec.len() {
                    return None;
                }
                let mut data_rel = 2 + key_len;
                if !data_rel.is_multiple_of(2) {
                    data_rel += 1;
                }
                if data_rel + 2 > rec.len() {
                    return None;
                }
                let record_type = BigEndian::read_i16(&rec[data_rel..data_rel + 2]);
                if record_type != CATALOG_FILE {
                    return None;
                }
                let body = &rec[data_rel..];
                if body.len() < 248 {
                    return None;
                }
                let rec_file_id = BigEndian::read_u32(&body[8..12]);
                if rec_file_id != file_id {
                    return None;
                }
                Some((
                    ForkData::parse(&body[88..168]),
                    ForkData::parse(&body[168..248]),
                ))
            },
        )
    }

    /// Read the allocation bitmap and return it.
    fn read_allocation_bitmap(&mut self) -> Result<Vec<u8>, FilesystemError> {
        // Allocation files on large volumes can run beyond 8 inline extents;
        // route through the overflow-aware reader.
        read_fork_with_overflow(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            &self.vh.allocation_file,
            HFSPLUS_ALLOCATION_FILE_ID,
            HFSPLUS_FORK_DATA,
            self.extents_overflow_data.as_deref(),
        )
    }

    /// Read a user fork (data or resource) belonging to `file_id`, consulting
    /// the extents-overflow B-tree when the inline 8 extents are insufficient.
    fn read_user_fork(
        &mut self,
        file_id: u32,
        fork_type: u8,
        fork: &ForkData,
    ) -> Result<Vec<u8>, FilesystemError> {
        read_fork_with_overflow(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            fork,
            file_id,
            fork_type,
            self.extents_overflow_data.as_deref(),
        )
    }

    /// Ensure the allocation bitmap is cached in memory.
    fn ensure_bitmap(&mut self) -> Result<(), FilesystemError> {
        if self.bitmap.is_none() {
            self.bitmap = Some(self.read_allocation_bitmap()?);
        }
        Ok(())
    }

    /// Build HFS+ catalog key bytes: key_len(2) + parent_id(4) + name_length(2) + name(UTF-16BE NFD).
    pub(crate) fn build_catalog_key(parent_cnid: u32, name: &str) -> Vec<u8> {
        let utf16: Vec<u16> = fs_mac_unicode::hfs_unicode::decompose_str(name);
        let key_len = 4 + 2 + utf16.len() * 2;
        let mut key = Vec::with_capacity(2 + key_len);
        let mut buf = [0u8; 2];
        BigEndian::write_u16(&mut buf, key_len as u16);
        key.extend_from_slice(&buf);
        let mut buf4 = [0u8; 4];
        BigEndian::write_u32(&mut buf4, parent_cnid);
        key.extend_from_slice(&buf4);
        BigEndian::write_u16(&mut buf, utf16.len() as u16);
        key.extend_from_slice(&buf);
        for &ch in &utf16 {
            BigEndian::write_u16(&mut buf, ch);
            key.extend_from_slice(&buf);
        }
        key
    }

    /// Compare function for catalog B-tree records (compares key portion only).
    /// `true` on HFSX volumes whose catalog B-tree advertises binary (case-
    /// sensitive) key compare. Plain HFS+ and HFSX-with-case-folding both
    /// return `false`. Driven by the catalog header `keyCompareType` byte
    /// rather than the volume signature alone — Apple's spec explicitly
    /// allows an `H+` filesystem to declare itself HFSX-shaped.
    pub(crate) fn case_sensitive(&self) -> bool {
        self.catalog_header.key_compare_type == KEY_COMPARE_BINARY
    }

    fn catalog_compare(a: &[u8], b: &[u8], case_sensitive: bool) -> Ordering {
        // Both records start with: key_len(2) + parent_id(4) + name_len(2) + name(UTF-16BE)
        if a.len() < 8 || b.len() < 8 {
            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 = BigEndian::read_u16(&a[6..8]) as usize;
        let name_len_b = BigEndian::read_u16(&b[6..8]) as usize;
        let name_a: Vec<u16> = a[8..8 + name_len_a.min((a.len() - 8) / 2) * 2]
            .chunks_exact(2)
            .map(BigEndian::read_u16)
            .collect();
        let name_b: Vec<u16> = b[8..8 + name_len_b.min((b.len() - 8) / 2) * 2]
            .chunks_exact(2)
            .map(BigEndian::read_u16)
            .collect();
        hfs_common::compare_hfsplus_keys(parent_a, &name_a, parent_b, &name_b, case_sensitive)
    }

    /// Find a catalog record by (parent_cnid, name).
    /// Returns Some((node_idx, rec_idx, absolute_offset_in_catalog_data)) if found.
    /// Scans leaf nodes linearly (correct for all catalog sizes we encounter).
    fn find_catalog_record(&self, parent_cnid: u32, name: &str) -> Option<(u32, usize, usize)> {
        let search_key = Self::build_catalog_key(parent_cnid, name);
        let node_size = self.catalog_header.node_size as usize;
        let first_leaf = self.catalog_header.first_leaf_node;
        let cs = self.case_sensitive();

        hfs_common::walk_leaf_records(
            &self.catalog_data,
            first_leaf,
            node_size,
            |node_idx, rec_idx, abs_off, rec| {
                if rec.len() < 8 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
                let key_portion = &rec[..2 + key_len.min(rec.len() - 2)];
                if Self::catalog_compare(key_portion, &search_key, cs) == Ordering::Equal {
                    Some((node_idx, rec_idx, abs_off))
                } else {
                    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(cnid, "")
    }

    /// Update parent folder valence (child count) by delta.
    fn update_parent_valence(
        &mut self,
        parent_cnid: u32,
        delta: i32,
    ) -> Result<(), FilesystemError> {
        // Find parent's thread record to get its actual parent + name
        let (node_idx, _rec_idx, _offset) = self
            .find_catalog_record_by_cnid(parent_cnid)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("thread record for CNID {parent_cnid} not found"))
            })?;

        // Now scan for the actual folder record (not thread) with this CNID.
        let node_size = self.catalog_header.node_size as usize;
        let first_leaf = self.catalog_header.first_leaf_node;
        let val_offset = hfs_common::walk_leaf_records(
            &self.catalog_data,
            first_leaf,
            node_size,
            |_node_idx, _rec_idx, abs_off, rec| {
                if rec.len() < 8 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
                let mut data_off = abs_off + 2 + key_len;
                if !data_off.is_multiple_of(2) {
                    data_off += 1;
                }
                let abs_end = abs_off + rec.len();
                if data_off + 12 > abs_end {
                    return None;
                }
                let record_type = BigEndian::read_i16(&self.catalog_data[data_off..data_off + 2]);
                if record_type != CATALOG_FOLDER {
                    return None;
                }
                let folder_id =
                    BigEndian::read_u32(&self.catalog_data[data_off + 8..data_off + 12]);
                if folder_id == parent_cnid {
                    Some(data_off + 4)
                } else {
                    None
                }
            },
        );
        let val_offset = val_offset.ok_or_else(|| {
            FilesystemError::NotFound(format!(
                "folder record for parent CNID {parent_cnid} not found in catalog"
            ))
        })?;
        let old_val = BigEndian::read_u32(&self.catalog_data[val_offset..val_offset + 4]);
        let new_val = (old_val as i64 + delta as i64).max(0) as u32;
        BigEndian::write_u32(&mut self.catalog_data[val_offset..val_offset + 4], new_val);
        let _ = node_idx; // suppress warning
        Ok(())
    }

    /// Insert a catalog record into the B-tree, handling splits and growth.
    ///
    /// Delegates to the shared `btree_insert_full`, which — for a non-sequential
    /// (per-`put`) insert into a full leaf — first tries a B*-style rotation into
    /// an adjacent sibling before splitting, lifting random-insert leaf occupancy
    /// from the ~69% a plain split leaves to ~88% (docs/hfsplus_btree_growth_plan.md
    /// §4d). `BTreeKeyFormat::HFSPLUS_CATALOG` drives the 2-byte / variable-length
    /// index keys. This is the same path classic HFS's `insert_catalog_record`
    /// uses; the previous hand-rolled split dance here packed less densely because
    /// it never rotated.
    fn insert_catalog_record(&mut self, key_record: &[u8]) -> Result<(), FilesystemError>
    where
        R: std::io::Write,
    {
        let cs = self.case_sensitive();
        // Insert; if the catalog runs out of free B-tree nodes, grow the fork
        // and retry once (docs/todo_hfsplus_fork_growth.md §4b). `btree_insert_full`
        // returns a *clean* DiskFull (no partial split) when it can't cover the
        // worst-case cascade, so the retry can't duplicate the record. A second
        // DiskFull means the volume itself is full — propagate it.
        let mut grown = false;
        loop {
            let cmp = |a: &[u8], b: &[u8]| Self::catalog_compare(a, b, cs);
            match hfs_common::btree_insert_full(
                &mut self.catalog_data,
                key_record,
                &BTreeKeyFormat::HFSPLUS_CATALOG,
                &cmp,
            ) {
                Ok(()) => break,
                Err(FilesystemError::DiskFull(_)) if !grown => {
                    self.grow_btree_fork(BTreeFork::Catalog)?;
                    grown = true;
                }
                Err(e) => return Err(e),
            }
        }
        self.catalog_header = BTreeHeaderRecord::parse(&self.catalog_data[14..14 + 106]);
        Ok(())
    }

    /// Remove a catalog record by (node_idx, rec_idx).
    fn remove_catalog_record(
        &mut self,
        node_idx: u32,
        rec_idx: usize,
    ) -> Result<(), FilesystemError> {
        let node_size = self.catalog_header.node_size as usize;
        let offset = node_idx as usize * node_size;
        let cs = self.case_sensitive();
        let cmp = |a: &[u8], b: &[u8]| Self::catalog_compare(a, b, cs);
        btree_remove_record(
            &mut self.catalog_data[offset..offset + node_size],
            node_size,
            rec_idx,
        );

        // Check if leaf is now empty
        let num = BigEndian::read_u16(&self.catalog_data[offset + 10..offset + 12]);
        if num > 0 && rec_idx == 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::HFSPLUS_CATALOG,
                &cmp,
            )?;
        }
        if num == 0 {
            // Free the node and update prev/next links
            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;
                BigEndian::write_u32(&mut self.catalog_data[prev_off..prev_off + 4], next);
            }
            if next != 0 {
                let next_off = next as usize * node_size;
                BigEndian::write_u32(&mut self.catalog_data[next_off + 4..next_off + 8], prev);
            }
            btree_free_node(&mut self.catalog_data, node_size, node_idx);

            let mut h = BTreeHeader::read(&self.catalog_data);
            h.free_nodes += 1;
            if h.first_leaf_node == node_idx {
                h.first_leaf_node = next;
            }
            if h.last_leaf_node == node_idx {
                h.last_leaf_node = prev;
            }
            h.write(&mut self.catalog_data);
            // The parent still pointed at the freed leaf; a later insert landed
            // there and the next split zeroed it.
            btree_detach_freed_node_and_refresh(
                &mut self.catalog_data,
                node_size,
                node_idx,
                &BTreeKeyFormat::HFSPLUS_CATALOG,
                &cmp,
            )?;
        }

        // Update header leaf_records
        let mut h = BTreeHeader::read(&self.catalog_data);
        h.leaf_records = h.leaf_records.saturating_sub(1);
        h.write(&mut self.catalog_data);
        self.catalog_header = BTreeHeaderRecord::parse(&self.catalog_data[14..14 + 106]);
        Ok(())
    }
}

// --- Extents-overflow B-tree helpers (read+write side) ---

impl<R: Read + Seek> HfsPlusFilesystem<R> {
    /// Compare two extents-overflow records by key. Per TN1150 the canonical
    /// order is fileID, then forkType, then startBlock — even though the on-
    /// disk byte layout puts forkType first.
    ///
    /// Both arguments are full record bytes (or trimmed index records); the
    /// 2-byte key_len prefix lives at offset 0..2 and the key body at 2..12.
    pub(crate) fn extents_compare(a: &[u8], b: &[u8]) -> Ordering {
        if a.len() < 12 || b.len() < 12 {
            return a.len().cmp(&b.len());
        }
        let a_file = BigEndian::read_u32(&a[4..8]);
        let b_file = BigEndian::read_u32(&b[4..8]);
        a_file.cmp(&b_file).then(a[2].cmp(&b[2])).then_with(|| {
            let a_sb = BigEndian::read_u32(&a[8..12]);
            let b_sb = BigEndian::read_u32(&b[8..12]);
            a_sb.cmp(&b_sb)
        })
    }

    /// Build a full extents-overflow record as it lives on disk:
    /// `[key_len_u16=10, forkType, pad=0, fileID(BE), startBlock(BE),
    ///   8 × HFSPlusExtentDescriptor]` = 76 bytes total.
    ///
    /// `chunk` may hold fewer than 8 entries; remaining slots are written as
    /// empty descriptors (start=0, count=0) — same convention as `ForkData`.
    fn build_extents_overflow_record(
        file_id: u32,
        fork_type: u8,
        file_rel_start: u32,
        chunk: &[ExtentDescriptor],
    ) -> Vec<u8> {
        let mut rec = vec![0u8; 2 + 10 + 64];
        BigEndian::write_u16(&mut rec[0..2], 10); // key_len
        rec[2] = fork_type;
        rec[3] = 0; // pad
        BigEndian::write_u32(&mut rec[4..8], file_id);
        BigEndian::write_u32(&mut rec[8..12], file_rel_start);
        for (i, ext) in chunk.iter().take(8).enumerate() {
            ext.serialize(&mut rec[12 + i * 8..12 + i * 8 + 8]);
        }
        rec
    }
}

impl<R: Read + Write + Seek> HfsPlusFilesystem<R> {
    /// Insert a record into the extents-overflow B-tree, splitting the leaf and
    /// growing the root when the target leaf is full — mirroring
    /// `insert_catalog_record` / `insert_xattr_record`.
    ///
    /// The extents-overflow tree uses 2-byte ("big") keys with *fixed*-length
    /// index separators (`kBTBigKeysMask` set, `kBTVariableIndexKeysMask` clear),
    /// padded to the 10-byte `maxKeyLength`. `BTreeKeyFormat::HFSPLUS_EXTENTS`
    /// drives that; before P1's key-format descriptor the shared growth helpers
    /// forced the classic 1-byte/0x25 shape, which is why this path was pinned to
    /// a single leaf level (docs/hfsplus_btree_growth_plan.md §4a/P3).
    fn insert_extents_overflow_record(&mut self, key_record: &[u8]) -> Result<(), FilesystemError> {
        {
            let data = self.extents_overflow_data.as_ref().ok_or_else(|| {
                FilesystemError::Unsupported(
                    "volume has no extents-overflow B-tree — fragmented files cannot be created"
                        .into(),
                )
            })?;
            if BTreeHeader::read(data).node_size == 0 {
                return Err(FilesystemError::InvalidData(
                    "extents-overflow B-tree has zero node_size".into(),
                ));
            }
        }
        // Insert; grow the extents-overflow fork and retry once on a clean
        // node-exhaustion DiskFull (see `insert_catalog_record`).
        let mut grown = false;
        loop {
            let data = self.extents_overflow_data.as_mut().unwrap();
            match hfs_common::btree_insert_full(
                data,
                key_record,
                &BTreeKeyFormat::HFSPLUS_EXTENTS,
                &Self::extents_compare,
            ) {
                Ok(()) => return Ok(()),
                Err(FilesystemError::DiskFull(_)) if !grown => {
                    self.grow_btree_fork(BTreeFork::Extents)?;
                    grown = true;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Remove every overflow record belonging to `(file_id, fork_type)`.
    /// Used by `delete_entry_inner` to clean up overflow records before the
    /// catalog row is removed.
    fn remove_extents_overflow_records_for(
        &mut self,
        file_id: u32,
        fork_type: u8,
    ) -> Result<(), FilesystemError> {
        let Some(ref data) = self.extents_overflow_data else {
            return Ok(());
        };
        let header = BTreeHeader::read(data);
        let node_size = header.node_size as usize;
        if node_size == 0 {
            return Ok(());
        }

        // Collect (node_idx, rec_idx) pairs first — mutating during a walk
        // would invalidate offsets.
        let mut victims: Vec<(u32, usize)> = Vec::new();
        hfs_common::walk_leaf_records::<(), _>(
            data,
            header.first_leaf_node,
            node_size,
            |node_idx, rec_idx, _abs_off, rec| {
                if rec.len() < 12 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
                if key_len < 10 {
                    return None;
                }
                let rec_fork = rec[2];
                let rec_file = BigEndian::read_u32(&rec[4..8]);
                if rec_fork == fork_type && rec_file == file_id {
                    victims.push((node_idx, rec_idx));
                }
                None
            },
        );
        if victims.is_empty() {
            return Ok(());
        }

        // Remove highest rec_idx first per node so earlier indices stay
        // stable.
        let data = self.extents_overflow_data.as_mut().unwrap();
        victims.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
        let mut removed: u32 = 0;
        for &(node_idx, rec_idx) in &victims {
            let off = node_idx as usize * node_size;
            btree_remove_record(&mut data[off..off + node_size], node_size, rec_idx);
            removed += 1;
        }
        let mut h = BTreeHeader::read(data);
        h.leaf_records = h.leaf_records.saturating_sub(removed);
        h.write(data);
        // An emptied leaf leaves the tree; one whose first key changed needs
        // the separators above it redone.
        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;
            let kf = BTreeKeyFormat::HFSPLUS_EXTENTS;
            if BigEndian::read_u16(&data[off + 10..off + 12]) == 0 {
                btree_retire_empty_leaf(data, node_size, node_idx, &kf, &Self::extents_compare)?;
            } else if victims.iter().any(|&(n, r)| n == node_idx && r == 0) {
                btree_refresh_index_keys(data, node_size, node_idx, &kf, &Self::extents_compare)?;
            }
        }
        Ok(())
    }
}

// --- Attributes B-tree helpers (write side) ---

impl<R: Read + Seek> HfsPlusFilesystem<R> {
    /// Compare two attribute records by key. Per TN1150 the canonical order is
    /// fileID, then attrName as UTF-16BE codepoints, then startBlock — even
    /// though the on-disk byte layout puts startBlock before the name.
    ///
    /// Both arguments are full record bytes (or trimmed index records); the
    /// 2-byte key_len prefix lives at offset 0..2 and the key body at 2..2+keyLen.
    /// Key body layout: pad(2) + fileID(4) + startBlock(4) + nameLen(2) + name(UTF-16BE).
    pub(crate) fn attr_compare(a: &[u8], b: &[u8]) -> Ordering {
        if a.len() < 14 || b.len() < 14 {
            return a.len().cmp(&b.len());
        }
        let af = BigEndian::read_u32(&a[4..8]);
        let bf = BigEndian::read_u32(&b[4..8]);
        if af != bf {
            return af.cmp(&bf);
        }
        let an_len = BigEndian::read_u16(&a[12..14]) as usize;
        let bn_len = BigEndian::read_u16(&b[12..14]) as usize;
        let a_name_end = (14 + an_len * 2).min(a.len());
        let b_name_end = (14 + bn_len * 2).min(b.len());
        // UTF-16BE codepoint comparison via raw byte compare: high byte first
        // makes byte-lexicographic ordering equal to u16-codepoint ordering.
        let cmp = a[14..a_name_end].cmp(&b[14..b_name_end]);
        if cmp != Ordering::Equal {
            return cmp;
        }
        let asb = BigEndian::read_u32(&a[8..12]);
        let bsb = BigEndian::read_u32(&b[8..12]);
        asb.cmp(&bsb)
    }

    /// Build a complete inline attribute record:
    /// `[key_len_u16, pad=0, fileID, startBlock=0, nameLen, name(UTF-16BE),
    ///   recordType=HFSPLUS_ATTR_INLINE_DATA, reserved[2]=0, attrSize, attrData]`.
    ///
    /// Caller is expected to have already NFD-normalized `name` if needed; we
    /// re-normalize defensively so on-disk keys stay canonical.
    pub(crate) fn build_inline_attr_record(cnid: u32, name: &str, value: &[u8]) -> Vec<u8> {
        let utf16: Vec<u16> = fs_mac_unicode::hfs_unicode::decompose_str(name);
        let key_body_len = 12 + utf16.len() * 2;
        let data_section_len = 4 + 8 + 4 + value.len();
        let mut rec = vec![0u8; 2 + key_body_len + data_section_len];
        BigEndian::write_u16(&mut rec[0..2], key_body_len as u16);
        // pad already zero at [2..4]
        BigEndian::write_u32(&mut rec[4..8], cnid);
        BigEndian::write_u32(&mut rec[8..12], 0); // startBlock = 0 for inline
        BigEndian::write_u16(&mut rec[12..14], utf16.len() as u16);
        for (i, ch) in utf16.iter().enumerate() {
            BigEndian::write_u16(&mut rec[14 + i * 2..16 + i * 2], *ch);
        }
        let data_off = 2 + key_body_len;
        BigEndian::write_u32(&mut rec[data_off..data_off + 4], HFSPLUS_ATTR_INLINE_DATA);
        // reserved[2] (8 bytes) at [data_off+4..data_off+12] already zero
        BigEndian::write_u32(&mut rec[data_off + 12..data_off + 16], value.len() as u32);
        rec[data_off + 16..data_off + 16 + value.len()].copy_from_slice(value);
        rec
    }
}

impl<R: Read + Write + Seek> HfsPlusFilesystem<R> {
    /// Insert a record into the attributes B-tree. Splits the leaf and grows
    /// the root if the target leaf is full, mirroring `insert_catalog_record`.
    fn insert_xattr_record(&mut self, key_record: &[u8]) -> Result<(), FilesystemError> {
        if self.vh.attributes_file.logical_size == 0 {
            return Err(FilesystemError::Unsupported(
                "volume has no attributes B-tree — extended attribute writes \
                 require an existing attributes file"
                    .into(),
            ));
        }
        self.ensure_attributes_loaded()?;
        let data = self
            .attributes_data
            .as_mut()
            .expect("ensure_attributes_loaded populated the buffer");
        let header = BTreeHeader::read(data);
        let node_size = header.node_size as usize;
        if node_size == 0 {
            return Err(FilesystemError::InvalidData(
                "attributes B-tree has zero node_size".into(),
            ));
        }
        // Reject records that can't fit in any leaf node — node has 14 bytes
        // of descriptor + a 2-byte free-space slot in the offset table.
        if key_record.len() + 2 > node_size.saturating_sub(14 + 2) {
            return Err(FilesystemError::XattrTooLarge(format!(
                "xattr record of {} bytes exceeds attributes node capacity ({} bytes); \
                 fork-style attribute writes are not yet implemented",
                key_record.len(),
                node_size,
            )));
        }
        // The attributes B-tree, like the catalog, uses 2-byte big keys and
        // variable-length index separators, so it threads HFSPLUS_ATTRIBUTES
        // through the shared insert (which also rotates before splitting).
        // Insert; grow the attributes fork and retry once on a clean
        // node-exhaustion DiskFull (see `insert_catalog_record`).
        let mut grown = false;
        loop {
            let data = self
                .attributes_data
                .as_mut()
                .expect("ensure_attributes_loaded populated the buffer");
            match hfs_common::btree_insert_full(
                data,
                key_record,
                &BTreeKeyFormat::HFSPLUS_ATTRIBUTES,
                &Self::attr_compare,
            ) {
                Ok(()) => return Ok(()),
                Err(FilesystemError::DiskFull(_)) if !grown => {
                    self.grow_btree_fork(BTreeFork::Attributes)?;
                    grown = true;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Remove every attribute record matching `(cnid, name)`. Returns the
    /// number of records removed (0 on a no-attributes-file volume or when no
    /// records match). Used by both `remove_xattr` (caller-driven) and
    /// `delete_entry` (cleanup, with `name == None` to drop all xattrs on the
    /// CNID).
    fn remove_xattr_records(
        &mut self,
        cnid: u32,
        name: Option<&str>,
    ) -> Result<u32, FilesystemError> {
        if self.vh.attributes_file.logical_size == 0 {
            return Ok(0);
        }
        self.ensure_attributes_loaded()?;
        let data = self
            .attributes_data
            .as_mut()
            .expect("ensure_attributes_loaded populated the buffer");
        let header = BTreeHeader::read(data);
        let node_size = header.node_size as usize;
        if node_size == 0 {
            return Ok(0);
        }
        let target_utf16: Option<Vec<u16>> = name.map(fs_mac_unicode::hfs_unicode::decompose_str);

        let mut victims: Vec<(u32, usize)> = Vec::new();
        hfs_common::walk_leaf_records::<(), _>(
            data,
            header.first_leaf_node,
            node_size,
            |node_idx, rec_idx, _abs_off, rec| {
                if rec.len() < 14 {
                    return None;
                }
                let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
                if key_len < 12 || 2 + key_len > rec.len() {
                    return None;
                }
                let file_id = BigEndian::read_u32(&rec[4..8]);
                if file_id != cnid {
                    return None;
                }
                if let Some(target) = target_utf16.as_ref() {
                    let nl = BigEndian::read_u16(&rec[12..14]) as usize;
                    if nl != target.len() {
                        return None;
                    }
                    if 14 + nl * 2 > 2 + key_len {
                        return None;
                    }
                    for (i, ch) in target.iter().enumerate() {
                        let off = 14 + i * 2;
                        if BigEndian::read_u16(&rec[off..off + 2]) != *ch {
                            return None;
                        }
                    }
                }
                victims.push((node_idx, rec_idx));
                None
            },
        );
        if victims.is_empty() {
            return Ok(0);
        }
        // Highest (node, rec) first so earlier indices stay stable.
        victims.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
        let mut removed: u32 = 0;
        for (node_idx, rec_idx) in &victims {
            let off = *node_idx as usize * node_size;
            btree_remove_record(&mut data[off..off + node_size], node_size, *rec_idx);
            removed += 1;
        }
        let mut h = BTreeHeader::read(data);
        h.leaf_records = h.leaf_records.saturating_sub(removed);
        h.write(data);
        // An emptied leaf leaves the tree; one whose first key changed needs
        // the separators above it redone.
        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;
            let kf = BTreeKeyFormat::HFSPLUS_ATTRIBUTES;
            if BigEndian::read_u16(&data[off + 10..off + 12]) == 0 {
                btree_retire_empty_leaf(data, node_size, node_idx, &kf, &Self::attr_compare)?;
            } else if victims.iter().any(|&(n, r)| n == node_idx && r == 0) {
                btree_refresh_index_keys(data, node_size, node_idx, &kf, &Self::attr_compare)?;
            }
        }
        Ok(removed)
    }
}

// --- Write helpers (require R: Read + Write + Seek) ---

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

    /// Write the volume header to both primary (offset+1024) and backup (offset+total_size-1024).
    fn write_volume_header(&mut self) -> Result<(), FilesystemError> {
        let vh_bytes = self.vh.serialize();
        // Primary
        self.reader
            .seek(SeekFrom::Start(self.partition_offset + 1024))?;
        self.reader.write_all(&vh_bytes)?;
        // Backup: 1024 bytes before the partition end when the length is
        // known, else before the end of the last allocation block.
        let volume_end = self
            .partition_size
            .filter(|&s| s >= 2048)
            .unwrap_or(self.vh.total_blocks as u64 * self.vh.block_size as u64);
        if volume_end > 1024 {
            self.reader
                .seek(SeekFrom::Start(self.partition_offset + volume_end - 1024))?;
            self.reader.write_all(&vh_bytes)?;
        }
        Ok(())
    }

    /// Write the extents-overflow B-tree data back to disk through the
    /// extents_file fork extents. No-op on volumes without an overflow file
    /// or when the cached buffer hasn't been touched.
    fn write_extents_overflow(&mut self) -> Result<(), FilesystemError> {
        if self.vh.extents_file.logical_size == 0 {
            return Ok(());
        }
        let Some(ref data) = self.extents_overflow_data else {
            return Ok(());
        };
        write_fork_data(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            &self.vh.extents_file,
            data,
        )
    }

    /// Write the attributes B-tree data back to disk through the
    /// attributes_file fork extents. No-op on volumes without an attributes
    /// file or when the cached buffer hasn't been touched.
    fn write_attributes(&mut self) -> Result<(), FilesystemError> {
        if self.vh.attributes_file.logical_size == 0 {
            return Ok(());
        }
        if self.attributes_data.is_none() {
            return Ok(());
        }
        write_fork_data_with_overflow(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            &self.vh.attributes_file,
            HFSPLUS_ATTRIBUTES_FILE_ID,
            0,
            self.extents_overflow_data.as_deref(),
            self.attributes_data.as_deref().unwrap(),
        )
    }

    /// Write the catalog B-tree data back to disk through the catalog_file
    /// fork extents — including any overflow extents past the 8 inline slots
    /// that §4b growth may have added.
    fn write_catalog(&mut self) -> Result<(), FilesystemError> {
        write_fork_data_with_overflow(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            &self.vh.catalog_file,
            HFSPLUS_CATALOG_FILE_ID,
            0,
            self.extents_overflow_data.as_deref(),
            &self.catalog_data,
        )
    }

    /// Write the allocation bitmap back to disk.
    fn write_allocation_bitmap(&mut self) -> Result<(), FilesystemError> {
        if let Some(ref bm) = self.bitmap {
            write_fork_data(
                &mut self.reader,
                self.partition_offset,
                self.vh.block_size,
                &self.vh.allocation_file,
                bm,
            )?;
        }
        Ok(())
    }

    /// Allocate `blocks_needed` blocks from the allocation bitmap, possibly
    /// across multiple non-contiguous extents.
    ///
    /// Strategy: greedy largest-run-first — collect every clear run, sort by
    /// length descending, take a prefix of each run until the request is
    /// satisfied. This avoids `DiskFull` on volumes that have plenty of free
    /// space but no contiguous run large enough for the whole request.
    ///
    /// On success the bitmap is updated, `vh.free_blocks` is decremented,
    /// and `vh.next_allocation` is set to the byte just past the last
    /// extent so the next allocation starts looking forward instead of
    /// re-scanning the same area.
    fn allocate_extents(
        &mut self,
        blocks_needed: u32,
    ) -> Result<Vec<ExtentDescriptor>, FilesystemError> {
        if blocks_needed == 0 {
            return Ok(Vec::new());
        }
        self.ensure_bitmap()?;
        let total_blocks = self.vh.total_blocks;
        let bitmap = self.bitmap.as_mut().unwrap();

        // Quick total-free check before any scan: if free_blocks < requested
        // we cannot possibly satisfy the request, regardless of layout.
        if self.vh.free_blocks < blocks_needed {
            return Err(FilesystemError::DiskFull(format!(
                "{} blocks free, {} requested",
                self.vh.free_blocks, blocks_needed
            )));
        }

        let mut runs = bitmap_collect_clear_runs_be(bitmap, total_blocks);
        // Largest run first, ties broken by lower start (deterministic).
        runs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));

        let mut extents: Vec<ExtentDescriptor> = Vec::new();
        let mut remaining = blocks_needed;
        let mut last_end = 0u32;
        for (start, len) in runs {
            if remaining == 0 {
                break;
            }
            let take = len.min(remaining);
            extents.push(ExtentDescriptor {
                start_block: start,
                block_count: take,
            });
            for i in 0..take {
                bitmap_set_bit_be(bitmap, start + i);
            }
            remaining -= take;
            last_end = start + take;
        }

        if remaining > 0 {
            // Roll back any partial allocation before reporting failure so
            // the bitmap stays consistent for the snapshot guard.
            for ext in &extents {
                for i in 0..ext.block_count {
                    bitmap_clear_bit_be(bitmap, ext.start_block + i);
                }
            }
            return Err(FilesystemError::DiskFull(format!(
                "needed {blocks_needed} blocks, short by {remaining} after gathering all free runs"
            )));
        }

        self.vh.free_blocks -= blocks_needed;
        self.vh.next_allocation = last_end;
        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.vh.free_blocks += count;
    }

    /// Free all blocks referenced by a fork (inline extents only).
    fn free_fork_blocks(&mut self, fork: &ForkData) {
        for ext in &fork.extents {
            if ext.is_empty() {
                break;
            }
            self.free_blocks(ext.start_block, ext.block_count);
        }
    }

    /// Free every block referenced by a fork's *overflow* extents (the
    /// extras living in the extents-overflow B-tree, beyond the 8 inline
    /// `ForkData.extents`). The record removal is a separate call —
    /// `remove_extents_overflow_records_for` — so callers can sequence
    /// "free blocks" and "remove records" independently.
    fn free_fork_overflow_extents(&mut self, file_id: u32, fork_type: u8, fork: &ForkData) {
        let Some(ref ext_data) = self.extents_overflow_data else {
            return;
        };
        let inline_blocks: u32 = fork.extents.iter().map(|e| e.block_count).sum();
        let overflow =
            collect_hfsplus_overflow_extents(ext_data, file_id, fork_type, inline_blocks);
        for ext in overflow {
            if ext.block_count == 0 {
                continue;
            }
            self.free_blocks(ext.start_block, ext.block_count);
        }
    }

    // --- B-tree fork grow-on-full (docs/todo_hfsplus_fork_growth.md §4b) ---

    /// Mutable handle to the in-memory tree buffer for `kind`. Errors if the
    /// volume has no such B-tree (e.g. growing the extents-overflow tree on a
    /// volume that never built one).
    fn tree_buf_mut(&mut self, kind: BTreeFork) -> Result<&mut Vec<u8>, FilesystemError> {
        match kind {
            BTreeFork::Catalog => Ok(&mut self.catalog_data),
            BTreeFork::Extents => self.extents_overflow_data.as_mut().ok_or_else(|| {
                FilesystemError::Unsupported("volume has no extents-overflow B-tree".into())
            }),
            BTreeFork::Attributes => self.attributes_data.as_mut().ok_or_else(|| {
                FilesystemError::Unsupported("volume has no attributes B-tree".into())
            }),
        }
    }

    /// The volume-header `ForkData` backing `kind`.
    fn fork_mut(&mut self, kind: BTreeFork) -> &mut ForkData {
        match kind {
            BTreeFork::Catalog => &mut self.vh.catalog_file,
            BTreeFork::Extents => &mut self.vh.extents_file,
            BTreeFork::Attributes => &mut self.vh.attributes_file,
        }
    }

    /// First volume block immediately *after* the fork's last inline extent —
    /// the candidate start for a contiguous tail growth. Returns 0 (never a
    /// valid data block) when the fork has no extents. Overflow extents are
    /// intentionally not consulted: if the true tail lies in an overflow
    /// extent, `allocate_contiguous_after` simply finds the candidate block
    /// busy and the caller falls back to the general allocator — correct, just
    /// not optimally contiguous.
    fn fork_last_inline_block(&self, kind: BTreeFork) -> u32 {
        let fork = match kind {
            BTreeFork::Catalog => &self.vh.catalog_file,
            BTreeFork::Extents => &self.vh.extents_file,
            BTreeFork::Attributes => &self.vh.attributes_file,
        };
        let mut last = 0u32;
        for e in &fork.extents {
            if e.block_count == 0 {
                break;
            }
            last = e.start_block + e.block_count;
        }
        last
    }

    /// Try to claim `blocks` free volume blocks *immediately following*
    /// `after_block`, so the fork's last extent simply gets longer (extent
    /// count unchanged — the fragmentation-free common case). Returns the new
    /// extent on success, or `None` if `after_block` is 0, the run would run
    /// past the volume, or any block in it is already allocated. Updates the
    /// bitmap, `free_blocks`, and `next_allocation` exactly like
    /// `allocate_extents`.
    fn allocate_contiguous_after(
        &mut self,
        after_block: u32,
        blocks: u32,
    ) -> Option<ExtentDescriptor> {
        if blocks == 0 || after_block == 0 {
            return None;
        }
        self.ensure_bitmap().ok()?;
        if after_block.checked_add(blocks)? > self.vh.total_blocks {
            return None;
        }
        if self.vh.free_blocks < blocks {
            return None;
        }
        let bitmap = self.bitmap.as_mut()?;
        for i in 0..blocks {
            if bitmap_test_bit_be(bitmap, after_block + i) {
                return None; // tail is not free — caller falls back
            }
        }
        for i in 0..blocks {
            bitmap_set_bit_be(bitmap, after_block + i);
        }
        self.vh.free_blocks -= blocks;
        self.vh.next_allocation = (after_block + blocks).max(self.vh.next_allocation);
        Some(ExtentDescriptor {
            start_block: after_block,
            block_count: blocks,
        })
    }

    /// Attach freshly-allocated `new_extents` to the fork backing `kind`,
    /// merging the first one into the fork's last inline extent when they are
    /// physically contiguous (so a contiguous tail grow keeps the extent count
    /// unchanged), dropping the rest into free inline slots, and spilling any
    /// remainder past the 8 inline slots into the extents-overflow B-tree
    /// (Phase B). Bumps the fork's `total_blocks` / `logical_size`.
    fn attach_extents_to_fork(
        &mut self,
        kind: BTreeFork,
        new_extents: &[ExtentDescriptor],
    ) -> Result<(), FilesystemError> {
        let block_size = self.vh.block_size as u64;
        let fork = self.fork_mut(kind);
        let mut added_blocks = 0u32;
        let mut overflow: Vec<ExtentDescriptor> = Vec::new();
        for ext in new_extents {
            if ext.block_count == 0 {
                continue;
            }
            added_blocks += ext.block_count;
            // Index of the last non-empty inline slot, if any.
            let last_idx = (0..8)
                .take_while(|&i| fork.extents[i].block_count != 0)
                .last();
            let mut placed = false;
            if let Some(i) = last_idx {
                let le = fork.extents[i];
                if le.start_block + le.block_count == ext.start_block {
                    fork.extents[i].block_count += ext.block_count;
                    placed = true;
                }
            }
            if !placed {
                if let Some(i) = (0..8).find(|&i| fork.extents[i].block_count == 0) {
                    fork.extents[i] = *ext;
                    placed = true;
                }
            }
            if !placed {
                overflow.push(*ext);
            }
        }
        fork.total_blocks += added_blocks;
        fork.logical_size += added_blocks as u64 * block_size;
        if !overflow.is_empty() {
            self.spill_fork_extents_to_overflow(kind, &overflow)?;
        }
        Ok(())
    }

    /// Phase B: record fork `extents` that overflowed the 8 inline slots into
    /// the extents-overflow B-tree, keyed by the special file's reserved CNID
    /// (fork type 0). These append after the fork's existing inline + overflow
    /// blocks, so their file-relative start is `inline_blocks +
    /// existing_overflow_blocks`. The write side (`write_fork_data_with_overflow`)
    /// and read side (`read_fork_with_overflow`) both consult these records.
    fn spill_fork_extents_to_overflow(
        &mut self,
        kind: BTreeFork,
        extents: &[ExtentDescriptor],
    ) -> Result<(), FilesystemError> {
        // The extents-overflow file cannot store its *own* overflow extents
        // (it would have to contain a record describing where it lives) — HFS+
        // limits it to 8 inline extents. In practice it stays tiny, so this is
        // a hard error if it ever happens, and the recursion guard that keeps
        // a catalog/attributes spill (which grows the extents fork) from
        // re-entering here for the extents fork itself.
        if kind == BTreeFork::Extents {
            return Err(FilesystemError::DiskFull(
                "extents-overflow B-tree fork exceeded its 8 inline extents".into(),
            ));
        }
        let file_id = kind.file_id();
        let fork = match kind {
            BTreeFork::Catalog => &self.vh.catalog_file,
            BTreeFork::Attributes => &self.vh.attributes_file,
            BTreeFork::Extents => unreachable!(),
        };
        let inline_blocks: u32 = fork.extents.iter().map(|e| e.block_count).sum();
        let existing_overflow: u32 = match self.extents_overflow_data.as_deref() {
            Some(ed) => collect_hfsplus_overflow_extents(ed, file_id, 0, inline_blocks)
                .iter()
                .map(|e| e.block_count)
                .sum(),
            None => 0,
        };
        let mut file_rel = inline_blocks + existing_overflow;
        // HFS+ extents-overflow records hold up to 8 extent descriptors each.
        for chunk in extents.chunks(8) {
            let rec = Self::build_extents_overflow_record(file_id, 0, file_rel, chunk);
            self.insert_extents_overflow_record(&rec)?;
            file_rel += chunk.iter().map(|e| e.block_count).sum::<u32>();
        }
        Ok(())
    }

    /// Grow the B-tree fork backing `kind` by at least one clump of nodes so a
    /// subsequent `btree_insert_full` has free nodes to allocate. Allocates
    /// volume blocks (preferring a contiguous tail extension), attaches them to
    /// the fork, extends the in-memory tree buffer, and publishes the new nodes
    /// to the tree header (`total_nodes` / `free_nodes`). The node-allocation
    /// bitmap bits for the new nodes already read as 0 (free) inside the header
    /// node's capacity; past that, a map node is appended to the bitmap chain
    /// (§4b Phase C).
    fn grow_btree_fork(&mut self, kind: BTreeFork) -> Result<(), FilesystemError> {
        let block_size = self.vh.block_size;

        let (node_size, total_nodes) = {
            let buf = self.tree_buf_mut(kind)?;
            let h = BTreeHeader::read(buf);
            (h.node_size as usize, h.total_nodes)
        };
        if node_size == 0 || node_size < 256 {
            return Err(FilesystemError::InvalidData(format!(
                "{} B-tree has invalid node_size {node_size}",
                kind.label()
            )));
        }

        // Grow by at least 8 nodes, rounded up to the fork's clump, to amortise
        // the work and keep per-`put` workloads from re-entering grow on every
        // insert (which would fragment the fork and defeat the contiguous-tail
        // strategy).
        let clump_nodes = (self.vh.data_clump_size as usize)
            .div_ceil(node_size)
            .max(1) as u32;
        let grow_nodes = clump_nodes.max(8);

        // The header node's bitmap addresses (node_size - 256) * 8 node bits;
        // each map node (BTNodeKind=2) chained off the header adds
        // map_node_bitmap_bytes*8 more. When a grow would push the node count
        // past the current addressable range, we must append one map node so
        // the new node indices have bitmap bits (§4b Phase C). A single map
        // node covers far more nodes than one grow adds, so at most one new map
        // node is ever needed per grow.
        let header_cap = ((node_size - 256) * 8) as u32;
        let per_map = (hfs_common::map_node_bitmap_bytes(node_size) * 8) as u32;
        let existing_map = {
            let buf = self.tree_buf_mut(kind)?;
            (hfs_common::btree_bitmap_segments(buf, node_size).len() as u32).saturating_sub(1)
        };
        let current_capacity = header_cap + existing_map * per_map;
        let need_map = total_nodes + grow_nodes > current_capacity;
        if need_map && per_map == 0 {
            return Err(FilesystemError::DiskFull(format!(
                "{} B-tree node bitmap full and node size too small for map nodes",
                kind.label()
            )));
        }
        let add_slots = grow_nodes + u32::from(need_map);
        let grow_blocks = btree_grow_blocks(total_nodes, add_slots, node_size, block_size);
        // Allocate volume blocks, preferring a contiguous tail extension so the
        // fork's last extent just gets longer.
        if grow_blocks > 0 {
            let last_block = self.fork_last_inline_block(kind);
            let new_extents = match self.allocate_contiguous_after(last_block, grow_blocks) {
                Some(e) => vec![e],
                None => self.allocate_extents(grow_blocks)?,
            };
            self.attach_extents_to_fork(kind, &new_extents)?;
        }

        // Extend the in-memory tree buffer and publish the new nodes. The added
        // bytes are zero, so the new node-bitmap bits read as free and
        // `btree_alloc_node` will hand them out.
        {
            let buf = self.tree_buf_mut(kind)?;
            buf.resize(buf.len() + add_slots as usize * node_size, 0);

            if need_map {
                // The new map node takes the first new slot; the free data
                // nodes follow it. Its own index is still inside the *existing*
                // bitmap capacity (one grow adds far fewer nodes than the
                // header/last-map-node segment can address), so we can mark it
                // used after linking it into the chain.
                let map_idx = total_nodes;
                let tail = btree_map_chain_tail(buf, node_size); // 0 => link via header node 0
                hfs_common::init_map_node(buf, node_size, map_idx, tail, 0);
                let linker_off = tail as usize * node_size; // node 0 is the header
                BigEndian::write_u32(&mut buf[linker_off..linker_off + 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 += grow_nodes; // the map node is allocated, not free
            h.write(buf);
        }
        self.vh.write_count = self.vh.write_count.wrapping_add(1);
        if kind == BTreeFork::Catalog {
            self.catalog_header = BTreeHeaderRecord::parse(&self.catalog_data[14..14 + 106]);
        }
        Ok(())
    }

    /// Write file data to allocated blocks. Returns the ForkData describing
    /// the allocation.
    ///
    /// Allocates via `allocate_extents`. The first 8 extents land in the
    /// inline `ForkData.extents` slots; the remainder is grouped into
    /// 8-extent chunks and inserted into the extents-overflow B-tree as
    /// records keyed by `(forkType, fileID, file-relative startBlock)`.
    ///
    /// `file_id` and `fork_type` are required so overflow records carry
    /// the correct key. Pass `HFSPLUS_FORK_DATA` for the data fork and
    /// `HFSPLUS_FORK_RESOURCE` for the resource fork.
    fn write_data_to_blocks(
        &mut self,
        data: &mut dyn std::io::Read,
        data_len: u64,
        file_id: u32,
        fork_type: u8,
    ) -> Result<ForkData, FilesystemError> {
        if data_len == 0 {
            return Ok(ForkData::empty());
        }
        let block_size = self.vh.block_size as u64;
        let blocks_needed = data_len.div_ceil(block_size) as u32;
        let extents = self.allocate_extents(blocks_needed)?;

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

        // Build the inline ForkData from the first 8 extents.
        let mut fork = ForkData::empty();
        fork.logical_size = data_len;
        fork.total_blocks = blocks_needed;
        for (slot, ext) in fork.extents.iter_mut().zip(extents.iter().take(8)) {
            *slot = *ext;
        }

        // For each 8-extent chunk past the inline capacity, build and
        // insert one overflow record. The key's startBlock is the file-
        // relative block index where the chunk's first extent begins.
        if extents.len() > 8 {
            let inline_blocks: u32 = extents.iter().take(8).map(|e| e.block_count).sum();
            let mut file_rel_start = inline_blocks;
            for chunk in extents[8..].chunks(8) {
                let rec =
                    Self::build_extents_overflow_record(file_id, fork_type, file_rel_start, chunk);
                self.insert_extents_overflow_record(&rec)?;
                file_rel_start += chunk.iter().map(|e| e.block_count).sum::<u32>();
            }
        }

        Ok(fork)
    }

    /// Build a complete HFS+ file catalog record (248 bytes).
    /// `mtime_secs = Some(secs)` stamps that Unix time into all four date
    /// fields (a cross-fs copy carrying the source mtime through); `None`
    /// stamps `now`. The after-create `set_dates` Commander path still
    /// overrides all four.
    fn build_file_record_with_dates(
        file_id: u32,
        data_fork: &ForkData,
        rsrc_fork: &ForkData,
        type_code: &[u8; 4],
        creator_code: &[u8; 4],
        mtime_secs: Option<u64>,
        finder_flags: u16,
    ) -> [u8; 248] {
        let mut rec = [0u8; 248];
        let now = match mtime_secs {
            Some(s) => disk_core::times::unix_to_mac_epoch(s),
            None => hfs_common::hfs_now(),
        };
        BigEndian::write_i16(&mut rec[0..2], CATALOG_FILE);
        BigEndian::write_u32(&mut rec[8..12], file_id);
        BigEndian::write_u32(&mut rec[12..16], now); // createDate
        BigEndian::write_u32(&mut rec[16..20], now); // contentModDate
        BigEndian::write_u32(&mut rec[20..24], now); // attributeModDate
        BigEndian::write_u32(&mut rec[24..28], now); // accessDate
                                                     // FileInfo (userInfo): fdType at offset 48, fdCreator at offset 52
        rec[48..52].copy_from_slice(type_code);
        rec[52..56].copy_from_slice(creator_code);
        BigEndian::write_u16(&mut rec[56..58], finder_flags); // fdFlags
                                                              // dataFork at offset 88
        data_fork.serialize(&mut rec[88..168]);
        // resourceFork at offset 168
        rsrc_fork.serialize(&mut rec[168..248]);
        rec
    }

    /// Stamp the per-record date fields. `frec_start` is the absolute byte
    /// offset of the catalog record's data section (i.e. just past the
    /// `recordType` field at offset 0 of the record body). At the standard
    /// HFS+ file/folder record offsets:
    ///   contentModDate @ +16, attributeModDate @ +20, accessDate @ +24.
    ///
    /// Pass `update_content = true` when the operation changed file content
    /// (fork rewrite). Attribute-only changes (type/creator, finder flags,
    /// blessed-folder) leave contentModDate alone.
    fn stamp_record_dates(&mut self, frec_start: usize, update_content: bool) {
        let now = hfs_common::hfs_now();
        if update_content {
            BigEndian::write_u32(
                &mut self.catalog_data[frec_start + 16..frec_start + 20],
                now,
            );
        }
        BigEndian::write_u32(
            &mut self.catalog_data[frec_start + 20..frec_start + 24],
            now,
        );
        BigEndian::write_u32(
            &mut self.catalog_data[frec_start + 24..frec_start + 28],
            now,
        );
    }

    /// Build a complete HFS+ folder catalog record (88 bytes).
    /// `mtime_secs = Some(secs)` stamps that Unix time into the four date
    /// fields (a cross-fs copy carrying the source mtime through); `None`
    /// stamps `now`. The after-create Commander `set_dates` path still
    /// overrides.
    fn build_folder_record_with_dates(folder_id: u32, mtime_secs: Option<u64>) -> [u8; 88] {
        let mut rec = [0u8; 88];
        let now = match mtime_secs {
            Some(s) => disk_core::times::unix_to_mac_epoch(s),
            None => hfs_common::hfs_now(),
        };
        BigEndian::write_i16(&mut rec[0..2], CATALOG_FOLDER);
        // valence = 0 (offset 4)
        BigEndian::write_u32(&mut rec[8..12], folder_id);
        BigEndian::write_u32(&mut rec[12..16], now);
        BigEndian::write_u32(&mut rec[16..20], now);
        BigEndian::write_u32(&mut rec[20..24], now);
        BigEndian::write_u32(&mut rec[24..28], now);
        rec
    }

    /// Build a thread record. Thread key: (cnid, ""). Thread data: type(2) + reserved(2) + parentID(4) + name.
    fn build_thread_record(record_type: i16, parent_cnid: u32, name: &str) -> (Vec<u8>, Vec<u8>) {
        // Thread key: parent_id = cnid, name = empty
        // Actually, thread records are keyed by (cnid, "")
        // We need to build key + record separately

        // Key
        let key = Self::build_catalog_key(parent_cnid, "");
        // But wait — for thread records, the key uses the CNID as parent_id and empty name.
        // The parent_cnid here is actually the target CNID, not the actual parent.
        // Let me re-read: Thread key: key_len(2) + parent_id(4, =CNID) + name_len(2, =0)

        // Record data: type(2) + reserved(2) + parentID(4) + name_len(2) + name(UTF-16BE)
        let utf16: Vec<u16> = fs_mac_unicode::hfs_unicode::decompose_str(name);
        let mut rec = Vec::with_capacity(10 + utf16.len() * 2);
        let mut buf2 = [0u8; 2];
        let mut buf4 = [0u8; 4];
        BigEndian::write_i16(&mut buf2, record_type);
        rec.extend_from_slice(&buf2); // type
        rec.extend_from_slice(&[0, 0]); // reserved
        BigEndian::write_u32(&mut buf4, parent_cnid);
        rec.extend_from_slice(&buf4); // parentID (the actual parent of the entry)
        BigEndian::write_u16(&mut buf2, utf16.len() as u16);
        rec.extend_from_slice(&buf2); // name_len
        for &ch in &utf16 {
            BigEndian::write_u16(&mut buf2, ch);
            rec.extend_from_slice(&buf2);
        }
        (key, rec)
    }

    /// Sync metadata: write catalog + allocation bitmap + volume header + flush.
    fn do_sync_metadata(&mut self) -> Result<(), FilesystemError> {
        self.vh.modify_date = hfs_common::hfs_now();
        // Stamp clean-unmount state into the volume header. Without this,
        // a VH read from a mounted/dirty volume (bit 8 clear, bits 11/14
        // set) gets persisted as-is and Disk Utility refuses to mount the
        // result. Mirrors the unconditional `drAtrbUmounted` set in
        // classic HFS `write_mdb`. See ~/Downloads/HFSTests/ corruption
        // case (2026-05): rusty-backup edit on /dev/rdisk preserved
        // attributes 0x80004000 instead of writing 0x80000100.
        self.vh.attributes |= HFSPLUS_VOLUME_UNMOUNTED_BIT;
        self.vh.attributes &= !HFSPLUS_BOOT_VOLUME_INCONSISTENT_BIT;
        self.vh.attributes &= !HFSPLUS_VOLUME_INCONSISTENT_BIT;
        self.write_catalog()?;
        self.write_extents_overflow()?;
        self.write_attributes()?;
        self.write_allocation_bitmap()?;
        self.write_volume_header()?;
        if let Some(ref boot) = self.pending_boot_blocks {
            self.reader.seek(SeekFrom::Start(self.partition_offset))?;
            self.reader.write_all(boot.as_ref())?;
        }
        self.reader.flush()?;
        Ok(())
    }
}

impl<R: Read + Seek + Send> Filesystem for HfsPlusFilesystem<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> {
        // For directory hardlinks, `entry.location` points at the stub
        // catalog row; the actual children live under the `dir_<N>` inode
        // referenced by `link_target_cnid`. Following the link here keeps
        // recursive walks (browse view, fsck, capture) seeing the real
        // contents instead of the empty stub.
        let parent_cnid = entry
            .link_target_cnid
            .map(|c| c as u32)
            .unwrap_or(entry.location as u32);
        let children = self.list_children(parent_cnid)?;

        let mut entries = Vec::new();
        for child in children {
            match child {
                CatalogEntry::Folder {
                    folder_id,
                    name,
                    content_mod_date,
                    bsd,
                } => {
                    let path = if entry.path == "/" {
                        format!("/{name}")
                    } else {
                        format!("{}/{name}", entry.path)
                    };
                    let mut fe = FileEntry::new_directory(name, path, folder_id as u64);
                    bsd.apply_to(&mut fe);
                    fe.modified = crate::hfs_common::format_mac_date(content_mod_date);
                    fe.modified_unix = crate::hfs_common::mac_date_to_unix(content_mod_date);
                    entries.push(fe);
                }
                CatalogEntry::File {
                    file_id,
                    name,
                    data_size,
                    data_fork,
                    rsrc_size,
                    rsrc_fork,
                    type_code,
                    creator_code,
                    finder_flags,
                    link_inode_num,
                    dir_link_inode_num,
                    content_mod_date,
                    bsd,
                } => {
                    let path = if entry.path == "/" {
                        format!("/{name}")
                    } else {
                        format!("{}/{name}", entry.path)
                    };
                    // Directory hardlink: surface as a Directory entry that
                    // points at the dir-inode under .HFS+ Private Directory
                    // Data. list_directory called on it follows the link
                    // (see the parent_cnid resolution at the top of this fn).
                    if let Some(num) = dir_link_inode_num {
                        let mut fe = FileEntry::new_directory(name, path, file_id as u64);
                        fe.type_code = Some(type_code);
                        fe.creator_code = Some(creator_code);
                        bsd.apply_to(&mut fe);
                        if let Some(target_cnid) = self.resolve_dir_hardlink_inode(num)? {
                            fe.link_target_cnid = Some(target_cnid as u64);
                        }
                        let _ = (data_fork, rsrc_fork, finder_flags);
                        entries.push(fe);
                        continue;
                    }
                    // For file hardlinks (`fdType='hlnk'`/`fdCreator='hfs+'`),
                    // resolve the inode CNID and surface the inode's data /
                    // resource fork sizes — the link's own forks are empty.
                    let mut display_size = data_size;
                    let mut display_rsrc = rsrc_size;
                    let resolved_target = match link_inode_num {
                        Some(num) => self.resolve_hardlink_inode(num)?,
                        None => None,
                    };
                    if let Some(target_cnid) = resolved_target {
                        if let Some((d, r)) = self.find_file_by_id(target_cnid) {
                            display_size = d.logical_size;
                            display_rsrc = r.logical_size;
                        }
                    }
                    let mut fe = FileEntry::new_file(name, path, display_size, file_id as u64);
                    fe.type_code = Some(type_code);
                    fe.creator_code = Some(creator_code);
                    fe.finder_flags = Some(finder_flags);
                    bsd.apply_to(&mut fe);
                    fe.modified = crate::hfs_common::format_mac_date(content_mod_date);
                    fe.modified_unix = crate::hfs_common::mac_date_to_unix(content_mod_date);
                    if display_rsrc > 0 {
                        fe.resource_fork_size = Some(display_rsrc);
                    }
                    if let Some(target) = resolved_target {
                        fe.link_target_cnid = Some(target as u64);
                    }
                    // NOTE: symlink/alias *target resolution* used to happen
                    // here (read the data fork for `slnk`/`rhap` files; read
                    // the resource fork for entries with the IS_ALIAS finder
                    // flag). On a slow or forward-only source — zstd
                    // streaming backups, NAS-backed images — those reads can
                    // each take minutes because the source has to decompress
                    // gigabytes to reach the fork's extent. With Mac OS X
                    // root directories typically holding a handful of
                    // symlinks (etc → private/etc, var → private/var, etc.),
                    // listing the root would stall for tens of minutes.
                    //
                    // The target isn't load-bearing for navigation: the GUI
                    // file preview already reads the data fork on demand
                    // when the user selects the entry, and an `slnk`/`rhap`
                    // data fork is just the UTF-8 target path — it renders
                    // fine as a text preview. The Finder-alias path
                    // (`mac_alias::resolve_alias_target`) was inline-used
                    // by the directory listing only; nothing else depends
                    // on the alias having a resolved target. So we drop the
                    // eager resolution and let the preview path do the read
                    // when (and only when) the user actually clicks.
                    let _ = (data_fork, rsrc_fork);
                    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> {
        // Hardlink stubs carry empty forks; follow the indirection to the
        // inode under `HFS+ Private Data` and read its data fork instead.
        let file_id = entry
            .link_target_cnid
            .map(|c| c as u32)
            .unwrap_or(entry.location as u32);
        let (data_fork, _rsrc_fork) = 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_user_fork(file_id, HFSPLUS_FORK_DATA, &data_fork)?;
        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()));
        }
        // Hardlink stubs: read forks from the inode CNID, not the stub.
        let file_id = entry
            .link_target_cnid
            .map(|c| c as u32)
            .unwrap_or(entry.location as u32);
        let (data_fork, _rsrc_fork) = self.find_file_by_id(file_id).ok_or_else(|| {
            FilesystemError::NotFound(format!("file id {file_id} not found in catalog"))
        })?;
        write_fork_to(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            &data_fork,
            writer,
        )
    }

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

    fn fs_type(&self) -> &str {
        if self.vh.is_hfsx() {
            "HFSX"
        } else {
            "HFS+"
        }
    }

    fn validate_name(&self, name: &str) -> Result<(), FilesystemError> {
        validate_hfsplus_create_name(name)
    }

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

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

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

    /// HFS+ allocates fork storage in fixed-size allocation blocks
    /// (`blockSize`), 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.vh.block_size == 0 {
            None
        } else {
            Some(self.vh.block_size as u64)
        }
    }

    fn last_data_byte(&mut self) -> Result<u64, FilesystemError> {
        let bitmap = self.read_allocation_bitmap()?;
        // The alternate header's blocks are always allocated; skip them, and only them (R-078).
        let search_up_to = alt_vh_blocks(self.vh.total_blocks, self.vh.block_size).start;
        let last = find_last_set_bit(&bitmap, search_up_to);
        // The trim point must leave room for the alternate VH at the new end:
        // the resizer counts those trailing blocks as used (two at 512 bytes).
        let trailing: u64 = if self.vh.block_size <= 512 { 2 } else { 1 };
        match last {
            Some(block) => {
                let byte = (block as u64 + 1 + trailing) * self.vh.block_size as u64;
                Ok(byte.min(self.total_size()))
            }
            None => Ok(self.total_size()),
        }
    }

    fn defragmented_minimum_size(&mut self) -> Result<u64, FilesystemError> {
        // After a packed clone the volume holds:
        //   - boot blocks + primary VH (in allocation block 0)
        //   - all currently-allocated user data + B-tree files + bitmap
        //   - the alternate VH at the last 1024 bytes of the volume
        //
        // We can't access the `SourceCatalogSnapshot` here (it's built
        // later by the clone pipeline), so we can't run the precise
        // record-byte tally that [`hfsplus_defrag::plan_defrag_layout`]
        // uses. Instead, over-estimate the target catalog as
        // `2× source_catalog_file.logical_size`, matching the packing
        // overhead multiplier the planner applies. Then add an extra ×2
        // safety pad: the planner's exact estimate could in theory exceed
        // 2× source catalog if a volume has been heavily deleted (lots of
        // empty space inside leaves that the precise estimator wouldn't
        // count), but it can't exceed 4×. This puts a hard ceiling on the
        // partition envelope without the catalog-growth invariant the
        // planner enforces precisely on the clone path.
        //
        // We also add 1024 bytes to host the new alt-VH at the end of the
        // smaller image and round up to a whole block.
        let block_size = self.vh.block_size as u64;
        let used_blocks = self.vh.total_blocks.saturating_sub(self.vh.free_blocks) as u64;
        let used_bytes = used_blocks.saturating_mul(block_size);
        // Catalog-growth pad: 3× source catalog logical size. Combined
        // with the catalog blocks already counted in `used_blocks` (the
        // source's allocated catalog) that's 4× source total — the safe
        // over-estimate for the planner's exact-record-bytes × 2 result.
        let catalog_pad = self.vh.catalog_file.logical_size.saturating_mul(3);
        let total = used_bytes.saturating_add(catalog_pad).saturating_add(1024);
        Ok(total.div_ceil(block_size) * block_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_fork, rsrc_fork) = self.find_file_by_id(file_id).ok_or_else(|| {
            FilesystemError::NotFound(format!("file id {file_id} not found in catalog"))
        })?;
        if rsrc_fork.logical_size == 0 {
            return Ok(0);
        }
        let data = read_fork(
            &mut self.reader,
            self.partition_offset,
            self.vh.block_size,
            &rsrc_fork,
        )?;
        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(|(_d, r)| r.logical_size)
            .unwrap_or(0)
    }

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

    fn blessed_system_folder(&mut self) -> Option<(u64, String)> {
        // finderInfo[0] = Classic Mac OS System Folder CNID
        let cnid = self.vh.finder_info[0];
        if cnid == 0 {
            // Try finderInfo[5] = Mac OS X boot directory
            let cnid_x = self.vh.finder_info[5];
            if cnid_x == 0 {
                return None;
            }
            return self.lookup_folder_name(cnid_x);
        }
        self.lookup_folder_name(cnid)
    }

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

    fn journal_detail(&mut self) -> Result<Option<Box<dyn std::any::Any + Send>>, FilesystemError> {
        // Boxed so `dyn Filesystem` callers can downcast to `JournalDetail`; concrete calls hit the inherent method.
        Ok(HfsPlusFilesystem::journal_detail(self)?
            .map(|d| Box::new(d) as Box<dyn std::any::Any + Send>))
    }
}

impl<R: Read + Seek + Send> HfsPlusFilesystem<R> {
    fn lookup_folder_name(&self, cnid: u32) -> Option<(u64, String)> {
        // Find the thread record for this CNID to get its name
        if let Some((_node, _rec, offset)) = self.find_catalog_record_by_cnid(cnid) {
            let node_size = self.catalog_header.node_size as usize;
            let key_len = BigEndian::read_u16(&self.catalog_data[offset..offset + 2]) as usize;
            let mut rec_data_start = offset + 2 + key_len;
            if !rec_data_start.is_multiple_of(2) {
                rec_data_start += 1;
            }
            // Thread record: type(2) + reserved(2) + parentID(4) + name_len(2) + name(UTF-16BE)
            if rec_data_start + 10 <= self.catalog_data.len() {
                let name_len = BigEndian::read_u16(
                    &self.catalog_data[rec_data_start + 8..rec_data_start + 10],
                ) as usize;
                let name_end = rec_data_start + 10 + name_len * 2;
                if name_end <= self.catalog_data.len() {
                    let name = decode_utf16be(&self.catalog_data[rec_data_start + 10..name_end]);
                    return Some((cnid as u64, name));
                }
            }
            let _ = node_size;
        }
        // CNID set but can't resolve name
        Some((cnid as u64, format!("CNID {}", cnid)))
    }
}

/// Stream a fork's data through its extent descriptors to a writer.
fn write_fork_to<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
    block_size: u32,
    fork: &ForkData,
    writer: &mut dyn std::io::Write,
) -> Result<u64, FilesystemError> {
    let size = fork.logical_size;
    let mut written: u64 = 0;
    let mut buf = vec![0u8; 64 * 1024];
    for ext in &fork.extents {
        if ext.is_empty() || written >= size {
            break;
        }
        let offset = partition_offset + ext.start_block as u64 * block_size as u64;
        let extent_len = ext.block_count as u64 * 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)
}

/// Read a fork's data through its extent descriptors.
fn read_fork<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
    block_size: u32,
    fork: &ForkData,
) -> Result<Vec<u8>, FilesystemError> {
    let size = fork.logical_size as usize;
    let mut data = Vec::with_capacity(size);

    let extent_count = fork.extents.iter().filter(|e| !e.is_empty()).count();
    let t_total = std::time::Instant::now();
    log::debug!(
        "[HFS+ read_fork] start: logical_size={} bytes, inline_extents={}",
        size,
        extent_count
    );

    for (idx, ext) in fork.extents.iter().enumerate() {
        if ext.is_empty() {
            break;
        }
        let offset = partition_offset + ext.start_block as u64 * block_size as u64;
        let len = ext.block_count as u64 * block_size as u64;
        let read_len = len.min((size - data.len()) as u64) as usize;
        let t_ext = std::time::Instant::now();
        reader.seek(SeekFrom::Start(offset))?;
        let mut buf = vec![0u8; read_len];
        reader.read_exact(&mut buf)?;
        let elapsed_ms = t_ext.elapsed().as_secs_f64() * 1000.0;
        let mb = read_len as f64 / (1024.0 * 1024.0);
        let mbps = if elapsed_ms > 0.0 {
            mb / (elapsed_ms / 1000.0)
        } else {
            f64::INFINITY
        };
        log::debug!(
            "[HFS+ read_fork] ext[{}]: offset={} bytes={} time={:.1}ms throughput={:.2} MB/s",
            idx,
            offset,
            read_len,
            elapsed_ms,
            mbps
        );
        data.extend_from_slice(&buf);
        if data.len() >= size {
            break;
        }
    }

    data.truncate(size);
    let total_ms = t_total.elapsed().as_secs_f64() * 1000.0;
    let total_mb = size as f64 / (1024.0 * 1024.0);
    let total_mbps = if total_ms > 0.0 {
        total_mb / (total_ms / 1000.0)
    } else {
        f64::INFINITY
    };
    log::debug!(
        "[HFS+ read_fork] done: {} bytes in {:.1}ms ({:.2} MB/s)",
        size,
        total_ms,
        total_mbps
    );
    Ok(data)
}

/// Walk the extents-overflow B-tree leaf chain and collect every extent
/// belonging to (`file_id`, `fork_type`) whose `startBlock` key is at or
/// past `min_start_block`.
///
/// The HFS+ extents-overflow record is:
/// ```text
/// HFSPlusExtentKey { keyLength: u16 = 10, forkType: u8, pad: u8,
///                    fileID: u32, startBlock: u32 }
/// HFSPlusExtentRecord { extents: [HFSPlusExtentDescriptor; 8] }
/// ```
/// Each `HFSPlusExtentDescriptor` is `{ startBlock: u32, blockCount: u32 }`.
fn collect_hfsplus_overflow_extents(
    extents_data: &[u8],
    file_id: u32,
    fork_type: u8,
    min_start_block: u32,
) -> Vec<ExtentDescriptor> {
    use crate::hfs_common::walk_leaf_records;

    if extents_data.len() < 14 + 30 {
        return Vec::new();
    }
    let header = BTreeHeaderRecord::parse(&extents_data[14..14 + 30.min(extents_data.len() - 14)]);
    let node_size = header.node_size as usize;
    if node_size == 0 {
        return Vec::new();
    }

    let mut out: Vec<(u32, ExtentDescriptor)> = Vec::new();
    walk_leaf_records::<(), _>(
        extents_data,
        header.first_leaf_node,
        node_size,
        |_node, _rec_idx, _abs_off, rec| {
            if rec.len() < 12 {
                return None;
            }
            let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
            // HFS+ extent key: forkType(1) pad(1) fileID(4) startBlock(4) = 10 bytes.
            if key_len < 10 || 2 + key_len > rec.len() {
                return None;
            }
            let rec_fork = rec[2];
            let rec_file = BigEndian::read_u32(&rec[4..8]);
            let rec_start_block = BigEndian::read_u32(&rec[8..12]);
            if rec_fork != fork_type || rec_file != file_id {
                return None;
            }
            if rec_start_block < min_start_block {
                return None;
            }
            // Record body is 8 × 8-byte HFSPlusExtentDescriptor immediately
            // after the key; HFS+ keys are 2-byte aligned by construction.
            let data_off = 2 + key_len;
            if data_off + 64 > rec.len() {
                return None;
            }
            for j in 0..8 {
                let ext = ExtentDescriptor::parse(&rec[data_off + j * 8..data_off + j * 8 + 8]);
                if ext.block_count > 0 {
                    out.push((rec_start_block, ext));
                }
            }
            None
        },
    );

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

/// Like `read_fork`, but consults the extents-overflow B-tree when the inline
/// 8 extents don't cover `fork.logical_size`.
///
/// `extents_overflow_data` is the bytes of `vh.extents_file` (loaded once via
/// `read_fork`; the extents-overflow file itself can't have overflow records
/// — its 8 inline extents are authoritative). Pass `None` if the volume has
/// no extents-overflow file or you've already verified the fork fits inline.
fn read_fork_with_overflow<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
    block_size: u32,
    fork: &ForkData,
    file_id: u32,
    fork_type: u8,
    extents_overflow_data: Option<&[u8]>,
) -> Result<Vec<u8>, FilesystemError> {
    let mut data = read_fork(reader, partition_offset, block_size, fork)?;
    let target = fork.logical_size as usize;
    if data.len() >= target {
        return Ok(data);
    }
    let Some(ext_data) = extents_overflow_data else {
        return Err(FilesystemError::InvalidData(format!(
            "file {file_id} fork {fork_type:#x}: {} bytes requested but only \
             {} bytes in inline extents and no extents-overflow B-tree available",
            fork.logical_size,
            data.len()
        )));
    };
    let inline_blocks: u32 = fork.extents.iter().map(|e| e.block_count).sum();
    let overflow = collect_hfsplus_overflow_extents(ext_data, file_id, fork_type, inline_blocks);
    for ext in overflow {
        if data.len() >= target {
            break;
        }
        if ext.block_count == 0 {
            continue;
        }
        let offset = partition_offset + ext.start_block as u64 * block_size as u64;
        let extent_len = ext.block_count as u64 * block_size as u64;
        let to_read = extent_len.min((target - data.len()) as u64) as usize;
        reader.seek(SeekFrom::Start(offset))?;
        let mut buf = vec![0u8; to_read];
        reader.read_exact(&mut buf)?;
        data.extend_from_slice(&buf);
    }
    if data.len() < target {
        return Err(FilesystemError::InvalidData(format!(
            "file {file_id} fork {fork_type:#x}: extents (inline + overflow) \
             cover {} of {} bytes",
            data.len(),
            fork.logical_size
        )));
    }
    Ok(data)
}

/// Translate a byte offset within a fork (file space) to a byte offset on
/// the underlying device, using the fork's inline 8 extents. Returns
/// `Some((device_offset, contiguous_bytes_remaining))` for the extent that
/// contains `fork_offset`, or `None` if `fork_offset` falls past the inline
/// extents (caller would need to consult the extents-overflow B-tree).
fn translate_fork_offset(
    fork: &ForkData,
    block_size: u32,
    partition_offset: u64,
    fork_offset: u64,
) -> Option<(u64, u64)> {
    let bs = block_size as u64;
    let mut cursor: u64 = 0;
    for ext in &fork.extents {
        if ext.block_count == 0 {
            continue;
        }
        let len = ext.block_count as u64 * bs;
        if fork_offset < cursor + len {
            let local = fork_offset - cursor;
            let dev = partition_offset + ext.start_block as u64 * bs + local;
            return Some((dev, len - local));
        }
        cursor += len;
    }
    None
}

/// Read exactly one B-tree node from a fork, by node index.
fn read_node_from_fork<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
    block_size: u32,
    fork: &ForkData,
    node_idx: u32,
    node_size: usize,
) -> Option<Vec<u8>> {
    let fork_offset = (node_idx as u64).checked_mul(node_size as u64)?;
    let (dev_off, contig) = translate_fork_offset(fork, block_size, partition_offset, fork_offset)?;
    if (contig as usize) < node_size {
        // Node straddles an extent boundary — should never happen for HFS+
        // since node_size divides block_size. Bail rather than do a multi-
        // extent read for the cheap probe path.
        return None;
    }
    reader.seek(SeekFrom::Start(dev_off)).ok()?;
    let mut buf = vec![0u8; node_size];
    reader.read_exact(&mut buf).ok()?;
    Some(buf)
}

/// Probe an HFS+ volume header at `partition_offset` and return the volume
/// label without loading the full catalog.
///
/// The volume name lives in the *key* of the root folder record at
/// `(parent=1, name=<vol_name>)`. Catalog records are sorted primarily by
/// parent CNID (ascending u32), and `parent=1` is smaller than every other
/// parent in the catalog — so the root folder record is guaranteed to be
/// record 0 of the first leaf node. We don't need to look at the root
/// thread record at all (it sorts after every `parent=1` and `parent=2`
/// non-thread record, and on a volume with many top-level entries it can
/// spill into a later leaf — which is what was causing this probe to come
/// back empty for real volumes).
///
/// Reads node 0 (the B-tree header) and the first leaf node of the catalog
/// directly via the catalog fork's inline extents — typically two small
/// reads. Returns None if the partition doesn't hold an HFS+/HFSX volume.
pub fn probe_hfsplus_volume_label<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
) -> Option<String> {
    // APM "Apple_HFS" partitions can be pure classic HFS, native HFS+, or
    // **HFS-wrapped HFS+** (the legacy hybrid where a classic HFS MDB at
    // partition_offset+1024 carries `drEmbedSigWord=0x482B` and points at
    // the embedded HFS+ region somewhere inside the partition). The wrapper
    // case is the failure mode we hit on real volumes — `resolve_apple_hfs`
    // returns the embedded HFS+ offset for all three cases.
    let (fs_type, hfsplus_offset) = resolve_apple_hfs(reader, partition_offset);
    if fs_type != "hfsplus" {
        return None;
    }
    reader.seek(SeekFrom::Start(hfsplus_offset + 1024)).ok()?;
    let mut vh_buf = [0u8; 512];
    reader.read_exact(&mut vh_buf).ok()?;
    let vh = HfsPlusVolumeHeader::parse(&vh_buf).ok()?;
    if vh.block_size == 0 {
        return None;
    }

    // Read node 0 to learn the catalog's actual node_size and first_leaf_node.
    // We don't yet know node_size, so probe with the volume's allocation block
    // size (HFS+ catalog node sizes are typically 4 KiB or 8 KiB and never
    // exceed the allocation block size on commonly-encountered volumes).
    let probe_size = (vh.block_size as usize).clamp(512, 32 * 1024);
    let node0 = read_node_from_fork(
        reader,
        hfsplus_offset,
        vh.block_size,
        &vh.catalog_file,
        0,
        probe_size,
    )?;
    if node0.len() < 14 + 30 {
        return None;
    }
    let header = BTreeHeaderRecord::parse(&node0[14..14 + 30]);
    let node_size = header.node_size as usize;
    if node_size == 0 || node_size > 32 * 1024 || header.first_leaf_node == 0 {
        return None;
    }

    // Read the first leaf node. Record 0 is the root folder record whose key
    // is (parent=1, nameLength, name in UTF-16BE).
    let leaf = read_node_from_fork(
        reader,
        hfsplus_offset,
        vh.block_size,
        &vh.catalog_file,
        header.first_leaf_node,
        node_size,
    )?;
    if leaf.len() < node_size || leaf[8] as i8 != -1 {
        return None;
    }
    let num_records = BigEndian::read_u16(&leaf[10..12]) as usize;
    if num_records == 0 {
        return None;
    }
    let (rec_start, rec_end) = crate::hfs_common::btree_record_range(&leaf, node_size, 0);
    if rec_start >= rec_end || rec_end > node_size {
        return None;
    }
    let rec = &leaf[rec_start..rec_end];
    if rec.len() < 8 {
        return None;
    }
    let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
    if key_len < 6 || 2 + key_len > rec.len() {
        return None;
    }
    let parent_id = BigEndian::read_u32(&rec[2..6]);
    if parent_id != 1 {
        return None;
    }
    let name_length = BigEndian::read_u16(&rec[6..8]) as usize;
    if name_length == 0 {
        return None;
    }
    let body_start = 8;
    let body_end = body_start + name_length * 2;
    if body_end > rec.len() || body_end > 2 + key_len {
        return None;
    }
    let label = decode_utf16be(&rec[body_start..body_end]);
    if label.is_empty() {
        None
    } else {
        Some(label)
    }
}

/// Write data through a fork's extent descriptors.
fn write_fork_data<R: Write + Seek>(
    writer: &mut R,
    partition_offset: u64,
    block_size: u32,
    fork: &ForkData,
    data: &[u8],
) -> Result<(), FilesystemError> {
    let mut written = 0usize;
    for ext in &fork.extents {
        if ext.is_empty() || written >= data.len() {
            break;
        }
        let offset = partition_offset + ext.start_block as u64 * block_size as u64;
        let extent_len = ext.block_count as u64 * 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(())
}

/// Write a special-file B-tree fork that may have grown past its 8 inline
/// extents (§4b Phase B). Writes the inline extents first, then continues
/// into the fork's overflow extents pulled from the extents-overflow B-tree
/// — the write-side mirror of [`read_fork_with_overflow`]. Without this, a
/// grown catalog/attributes fork would be silently truncated on disk to its
/// first 8 extents even though it looks complete in memory.
#[allow(clippy::too_many_arguments)]
fn write_fork_data_with_overflow<R: Write + Seek>(
    writer: &mut R,
    partition_offset: u64,
    block_size: u32,
    fork: &ForkData,
    file_id: u32,
    fork_type: u8,
    extents_overflow_data: Option<&[u8]>,
    data: &[u8],
) -> Result<(), FilesystemError> {
    let mut written = 0usize;
    let write_extent = |writer: &mut R, ext: &ExtentDescriptor, written: &mut usize| {
        if ext.block_count == 0 || *written >= data.len() {
            return Ok(false);
        }
        let offset = partition_offset + ext.start_block as u64 * block_size as u64;
        let extent_len = ext.block_count as u64 * 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::<bool, FilesystemError>(true)
    };

    for ext in &fork.extents {
        if ext.is_empty() {
            break;
        }
        if !write_extent(writer, ext, &mut written)? {
            return Ok(());
        }
    }
    if written >= data.len() {
        return Ok(());
    }
    // Inline extents didn't cover the whole fork — continue into overflow.
    let Some(ext_data) = extents_overflow_data else {
        return Err(FilesystemError::InvalidData(format!(
            "special file {file_id} fork {fork_type:#x}: {} bytes to write but only \
             inline extents and no extents-overflow B-tree",
            data.len()
        )));
    };
    let inline_blocks: u32 = fork.extents.iter().map(|e| e.block_count).sum();
    for ext in collect_hfsplus_overflow_extents(ext_data, file_id, fork_type, inline_blocks) {
        if !write_extent(writer, &ext, &mut written)? {
            break;
        }
    }
    if written < data.len() {
        return Err(FilesystemError::InvalidData(format!(
            "special file {file_id} fork {fork_type:#x}: extents cover {written} of {} bytes",
            data.len()
        )));
    }
    Ok(())
}

/// Decode a UTF-16BE byte slice to a String.
fn decode_utf16be(data: &[u8]) -> String {
    let chars: Vec<u16> = data.chunks_exact(2).map(BigEndian::read_u16).collect();
    String::from_utf16_lossy(&chars)
}

/// Find the volume label from the catalog B-tree (root folder thread record).
/// Count data-fork extents per file by walking catalog leaves. Cheap —
/// all catalog data already lives in `catalog_data` (loaded at FS open),
/// so this is a pure in-memory scan. Each file record's data fork holds 8
/// inline extent descriptors at offset 88+16; we tally non-zero ones and
/// flag forks that overflow into the extents-overflow B-tree as having
/// >1 extent (the most common cause of real-world fragmentation).
fn hfsplus_fragmentation_stats(
    catalog_data: &[u8],
    first_leaf: u32,
    node_size: usize,
) -> disk_core::filesystem::FragmentationStats {
    use crate::hfs_common::walk_leaf_records;
    use byteorder::{BigEndian, ByteOrder};

    let mut stats = disk_core::filesystem::FragmentationStats::default();
    if node_size == 0 || catalog_data.is_empty() {
        return stats;
    }
    walk_leaf_records::<(), _>(
        catalog_data,
        first_leaf,
        node_size,
        |_node_idx, _rec_idx, _abs_off, rec| {
            // HFS+ catalog leaf record: u16 keyLength at offset 0, then the
            // key payload (parentID + HFSUniStr255), then the record body
            // (padded to even offset). The body's first 2 bytes carry the
            // record type — 0x0002 = file, 0x0001 = folder, threads = 3/4.
            if rec.len() < 4 {
                return None;
            }
            let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
            let mut body_start = 2 + key_len;
            if !body_start.is_multiple_of(2) {
                body_start += 1;
            }
            if body_start + 88 + 80 > rec.len() {
                return None;
            }
            let body = &rec[body_start..];
            let rec_type = BigEndian::read_u16(&body[0..2]);
            if rec_type != 0x0002 {
                return None;
            }
            let data_fork = &body[88..88 + 80];
            let total_blocks = BigEndian::read_u32(&data_fork[12..16]);
            if total_blocks == 0 {
                return None;
            }
            let mut inline_extents: u32 = 0;
            let mut inline_blocks: u32 = 0;
            for i in 0..8 {
                let off = 16 + i * 8;
                let count = BigEndian::read_u32(&data_fork[off + 4..off + 8]);
                if count > 0 {
                    inline_extents += 1;
                    inline_blocks = inline_blocks.saturating_add(count);
                }
            }
            stats.files_with_data += 1;
            // Multiple inline extents OR overflow into the extents B-tree
            // both count as fragmented for UI purposes.
            if inline_extents > 1 || total_blocks > inline_blocks {
                stats.fragmented_files += 1;
            }
            None
        },
    );
    stats
}

fn find_volume_label(catalog_data: &[u8], header: &BTreeHeaderRecord) -> String {
    use crate::hfs_common::walk_leaf_records;

    let node_size = header.node_size as usize;
    if node_size == 0 {
        return String::new();
    }

    walk_leaf_records::<String, _>(
        catalog_data,
        header.first_leaf_node,
        node_size,
        |_node_idx, _rec_idx, _abs_off, rec| {
            if rec.len() < 8 {
                return None;
            }
            let key_len = BigEndian::read_u16(&rec[0..2]) as usize;
            if key_len < 6 || 2 + key_len > rec.len() {
                return None;
            }
            // Catalog key: parent_id(4) + name_length(2) + name(UTF-16BE)
            let parent_id = BigEndian::read_u32(&rec[2..6]);
            if parent_id != 2 {
                return None;
            }
            let name_length = BigEndian::read_u16(&rec[6..8]) as usize;
            if name_length != 0 {
                return None;
            }

            // Record data follows the key, 2-byte aligned. HFS+ keys are
            // already 2-byte sized so no padding is needed in the standard
            // case, but tolerate odd offsets defensively.
            let mut data_start = 2 + key_len;
            if !data_start.is_multiple_of(2) {
                data_start += 1;
            }
            if data_start + 10 > rec.len() {
                return None;
            }
            let record_type = BigEndian::read_i16(&rec[data_start..data_start + 2]);
            // Folder thread = 3
            if record_type != 3 {
                return None;
            }
            let thread_name_len =
                BigEndian::read_u16(&rec[data_start + 8..data_start + 10]) as usize;
            let body_start = data_start + 10;
            let body_end = body_start + thread_name_len * 2;
            if body_end > rec.len() {
                return None;
            }
            Some(decode_utf16be(&rec[body_start..body_end]))
        },
    )
    .unwrap_or_default()
}

/// Find the index of the last set bit in a bitmap (MSB-first).
///
/// MSB-first means bit position 7 of byte N (mask 0x80) corresponds to
/// global index `N*8`, and bit position 0 (mask 0x01) to global index
/// `N*8 + 7`. The "last" set bit is the one with the highest global index.
fn find_last_set_bit(bitmap: &[u8], max_bits: u32) -> Option<u32> {
    let max = max_bits as usize;
    let scan_bytes = max.div_ceil(8).min(bitmap.len());
    for byte_idx in (0..scan_bytes).rev() {
        let byte = bitmap[byte_idx];
        if byte == 0 {
            continue;
        }
        // Within the byte, the highest global index belongs to the lowest
        // bit position (LSB). Iterate bit positions 0..8 ascending and
        // return the first set one in range.
        for bit_pos in 0..8u32 {
            let global = (byte_idx as u32) * 8 + (7 - bit_pos);
            if global >= max_bits {
                continue;
            }
            if (byte >> bit_pos) & 1 == 1 {
                return Some(global);
            }
        }
    }
    None
}

// --- EditableFilesystem implementation ---

impl<R: Read + Write + Seek + Send> EditableFilesystem for HfsPlusFilesystem<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 create_file(
        &mut self,
        parent: &FileEntry,
        name: &str,
        data: &mut dyn std::io::Read,
        data_len: u64,
        options: &CreateFileOptions,
    ) -> Result<FileEntry, FilesystemError> {
        let snap = self.snapshot();
        let result = self.create_file_inner(parent, name, data, data_len, options);
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    fn create_directory(
        &mut self,
        parent: &FileEntry,
        name: &str,
        options: &CreateDirectoryOptions,
    ) -> Result<FileEntry, FilesystemError> {
        let snap = self.snapshot();
        let result = self.create_directory_inner(parent, name, options);
        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 result = self.delete_entry_inner(parent, entry);
        if result.is_err() {
            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(());
        }
        validate_hfsplus_create_name(new_name)?;
        let snap = self.snapshot();
        let result = self.rename_inner(parent, entry, new_name);
        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 = self.set_type_creator_inner(entry, type_code, creator_code);
        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 result = self.write_resource_fork_inner(entry, data, len);
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    fn set_permissions(&mut self, entry: &FileEntry, mode: u32) -> Result<(), FilesystemError> {
        let frec = self.record_body_offset(entry.location as u32)?;
        let base = Self::bsd_type_bits(&self.catalog_data, frec, entry.is_directory());
        let new = disk_core::unix_common::inode::with_permission_bits(base, mode) as u16;
        let at = frec + HfsPlusBsdInfo::OFFSET + 10;
        BigEndian::write_u16(&mut self.catalog_data[at..at + 2], new);
        Ok(())
    }

    fn set_owner(&mut self, entry: &FileEntry, uid: u32, gid: u32) -> Result<(), FilesystemError> {
        // HFSPlusBSDInfo carries 32-bit ownerID / groupID.
        let frec = self.record_body_offset(entry.location as u32)?;
        let at = frec + HfsPlusBsdInfo::OFFSET;
        BigEndian::write_u32(&mut self.catalog_data[at..at + 4], uid);
        BigEndian::write_u32(&mut self.catalog_data[at + 4..at + 8], gid);
        // An ownership change on a record with no POSIX info yet would be
        // invisible to OS X, which reads ownership only where `fileMode`
        // says the block is populated. Give it the type bits so the file
        // gets a real mode instead of a half-filled one.
        let mode_at = frec + HfsPlusBsdInfo::OFFSET + 10;
        if BigEndian::read_u16(&self.catalog_data[mode_at..mode_at + 2]) == 0 {
            let default_mode = if entry.is_directory() {
                0o040_755
            } else {
                0o100_644
            };
            BigEndian::write_u16(
                &mut self.catalog_data[mode_at..mode_at + 2],
                default_mode as u16,
            );
        }
        Ok(())
    }

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

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

    fn set_blessed_folder(&mut self, entry: &FileEntry) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let result = self.set_blessed_folder_inner(entry);
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

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

impl<R: Read + Write + Seek + Send> HfsPlusFilesystem<R> {
    /// Set (or replace) an inline extended attribute on `cnid`.
    ///
    /// Any existing record keyed by `(cnid, name)` is removed first so the
    /// final state holds exactly one record per `(cnid, name)` pair. Records
    /// whose payload would not fit in a single B-tree leaf node are rejected
    /// with `XattrTooLarge` — fork-style storage is not yet wired up.
    ///
    /// Wrapped in the snapshot guard so partial failures (e.g. a leaf split
    /// running out of free B-tree nodes) leave the in-memory state byte-equal
    /// to the pre-call state.
    pub fn set_xattr(
        &mut self,
        cnid: u32,
        name: &str,
        value: &[u8],
    ) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let result = (|| -> Result<(), FilesystemError> {
            self.remove_xattr_records(cnid, Some(name))?;
            let rec = Self::build_inline_attr_record(cnid, name, value);
            self.insert_xattr_record(&rec)?;
            if let Some(set) = self.xattr_cnids.as_mut() {
                set.insert(cnid);
            }
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Remove a single extended attribute by name. Returns `NotFound` if no
    /// matching record exists. Wrapped in the snapshot guard.
    pub fn remove_xattr(&mut self, cnid: u32, name: &str) -> Result<(), FilesystemError> {
        let snap = self.snapshot();
        let result = (|| -> Result<(), FilesystemError> {
            let removed = self.remove_xattr_records(cnid, Some(name))?;
            if removed == 0 {
                return Err(FilesystemError::NotFound(format!(
                    "extended attribute '{name}' on cnid {cnid}"
                )));
            }
            // Drop the cnid from the cached set if no records remain.
            if self.list_xattrs(cnid)?.is_empty() {
                if let Some(set) = self.xattr_cnids.as_mut() {
                    set.remove(&cnid);
                }
            }
            Ok(())
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }
}

/// Captured per-record metadata, replayed by [`HfsPlusFilesystem::set_record_metadata`]
/// onto a freshly-created target catalog record. Field offsets are
/// identical for HFS+ file (248-byte) and folder (88-byte) records, so the
/// same struct serves both shapes.
///
/// Used by the clone pipeline (Step 21 of `docs/hfsplus_enhancements.md`)
/// to stamp the source's dates / Finder metadata / BSD info / text
/// encoding onto each cloned entry after `create_file` /
/// `create_directory` has assigned it a new CNID.
#[derive(Debug, Clone, Default)]
pub(crate) struct RecordMetadata {
    pub create_date: u32,
    pub content_mod_date: u32,
    pub attribute_mod_date: u32,
    pub access_date: u32,
    pub backup_date: u32,
    pub bsd_info: [u8; 16],
    pub finder_info: [u8; 16],
    pub extended_finder_info: [u8; 16],
    pub text_encoding: u32,
}

impl<R: Read + Write + Seek + Send> HfsPlusFilesystem<R> {
    /// Replay captured per-record metadata onto the catalog record for
    /// `cnid`. Patches dates, BSD info, FInfo / FXInfo (or DInfo / DXInfo
    /// for folders — same offsets), and textEncoding. The locked-bit and
    /// flags-word fields are intentionally untouched here so callers can
    /// stamp them via dedicated paths (none today; the source's `flags` is
    /// already mirrored by `create_file` / `create_directory` for the
    /// fields the clone cares about).
    ///
    /// Mostly used by the clone replay path; tests cover the round-trip
    /// in `clone_round_trip_*`.
    /// Byte offset of catalog record `cnid`'s **body** (past the key) inside
    /// `catalog_data`, resolved through the record's thread entry.
    ///
    /// Shared by every in-place record patch — the metadata replay below and
    /// the POSIX-permission setters — so the thread-lookup / key-skip /
    /// even-alignment dance lives in one place.
    pub(crate) fn record_body_offset(&mut self, cnid: u32) -> Result<usize, FilesystemError> {
        let (_, _, t_offset) = self.find_catalog_record_by_cnid(cnid).ok_or_else(|| {
            FilesystemError::NotFound(format!("thread record for CNID {cnid} not found"))
        })?;
        let key_len = BigEndian::read_u16(&self.catalog_data[t_offset..t_offset + 2]) as usize;
        let mut rec_data_start = t_offset + 2 + 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 + 4..rec_data_start + 8]);
        let thread_name_len =
            BigEndian::read_u16(&self.catalog_data[rec_data_start + 8..rec_data_start + 10])
                as usize;
        let thread_name = decode_utf16be(
            &self.catalog_data[rec_data_start + 10..rec_data_start + 10 + thread_name_len * 2],
        );

        let (_, _, f_offset) = self
            .find_catalog_record(thread_parent, &thread_name)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!(
                    "catalog record for CNID {cnid} ('{thread_name}') not found"
                ))
            })?;
        let fkey_len = BigEndian::read_u16(&self.catalog_data[f_offset..f_offset + 2]) as usize;
        let mut frec = f_offset + 2 + fkey_len;
        if !frec.is_multiple_of(2) {
            frec += 1;
        }
        if frec + 84 > self.catalog_data.len() {
            return Err(FilesystemError::InvalidData(format!(
                "catalog record for CNID {cnid} truncated"
            )));
        }
        Ok(frec)
    }

    /// The `S_IFMT` bits to build a new `fileMode` on, for a record at
    /// `frec`.
    ///
    /// Normally the record's existing `fileMode` supplies them. A volume
    /// that has never carried POSIX info has `fileMode == 0` and therefore
    /// no type bits — writing bare permission bits there would leave a
    /// typeless mode that OS X reads as neither file nor directory, so the
    /// type comes from the catalog record's own kind instead.
    fn bsd_type_bits(catalog: &[u8], frec: usize, is_dir: bool) -> u32 {
        let at = frec + HfsPlusBsdInfo::OFFSET + 10;
        let cur = BigEndian::read_u16(&catalog[at..at + 2]) as u32;
        if cur & 0o170_000 != 0 {
            cur
        } else if is_dir {
            0o040_000
        } else {
            0o100_000
        }
    }

    pub(crate) fn set_record_metadata(
        &mut self,
        cnid: u32,
        meta: &RecordMetadata,
    ) -> Result<(), FilesystemError> {
        let frec = self.record_body_offset(cnid)?;

        BigEndian::write_u32(
            &mut self.catalog_data[frec + 12..frec + 16],
            meta.create_date,
        );
        BigEndian::write_u32(
            &mut self.catalog_data[frec + 16..frec + 20],
            meta.content_mod_date,
        );
        BigEndian::write_u32(
            &mut self.catalog_data[frec + 20..frec + 24],
            meta.attribute_mod_date,
        );
        BigEndian::write_u32(
            &mut self.catalog_data[frec + 24..frec + 28],
            meta.access_date,
        );
        BigEndian::write_u32(
            &mut self.catalog_data[frec + 28..frec + 32],
            meta.backup_date,
        );
        self.catalog_data[frec + 32..frec + 48].copy_from_slice(&meta.bsd_info);
        self.catalog_data[frec + 48..frec + 64].copy_from_slice(&meta.finder_info);
        self.catalog_data[frec + 64..frec + 80].copy_from_slice(&meta.extended_finder_info);
        BigEndian::write_u32(
            &mut self.catalog_data[frec + 80..frec + 84],
            meta.text_encoding,
        );
        Ok(())
    }

    /// Set the volume's create / modify / backup / checked dates. The
    /// `modify_date` is overwritten by `do_sync_metadata` with `hfs_now()`
    /// at sync time, so callers that want the source's modifyDate to
    /// survive should call this *after* the final mutation (i.e. as the
    /// last step before sync) — but for the clone pipeline the modifyDate
    /// is intentionally bumped to "now" anyway, so the input value here is
    /// a fallback used only if sync doesn't run.
    pub(crate) fn set_volume_dates(
        &mut self,
        create_date: u32,
        modify_date: u32,
        backup_date: u32,
        checked_date: u32,
    ) {
        self.vh.create_date = create_date;
        self.vh.modify_date = modify_date;
        self.vh.backup_date = backup_date;
        self.vh.checked_date = checked_date;
    }

    /// Replace the volume header's 8 × u32 Finder Info slots verbatim. The
    /// caller is responsible for any CNID remap (slots 0/3/5 etc. may hold
    /// CNIDs that point at the now-renumbered blessed folder / OS folder).
    pub(crate) fn set_volume_finder_info(&mut self, finder_info: [u32; 8]) {
        self.vh.finder_info = finder_info;
    }

    /// Stage the source volume's first 1024 bytes (boot blocks) for write
    /// at the next `sync_metadata`. Macs only ever care about the boot
    /// blocks on the System volume, but the area is part of the volume's
    /// signature, so the clone copies it verbatim for round-trip parity.
    pub(crate) fn set_boot_blocks(&mut self, blocks: &[u8; 1024]) {
        self.pending_boot_blocks = Some(Box::new(*blocks));
    }
}

impl<R: Read + Write + Seek + Send> HfsPlusFilesystem<R> {
    /// Locate the `\0\0\0\0HFS+ Private Data` directory at root, creating
    /// it if missing. Returns its `FileEntry`. The directory's existence is
    /// the prerequisite for any hardlink-related write — both
    /// [`Self::create_hardlink_inode`] and [`Self::create_hardlink`] call
    /// this internally so the replay path doesn't need to.
    pub fn ensure_private_dir(&mut self) -> Result<FileEntry, FilesystemError> {
        let private_name = hfsplus_private_dir_name();
        let root = self.root()?;
        for entry in self.list_directory(&root)? {
            if entry.is_directory() && entry.name == private_name {
                return Ok(entry);
            }
        }
        self.create_directory(&root, &private_name, &CreateDirectoryOptions::default())
    }

    /// Locate the `.HFS+ Private Directory Data\r` directory at root,
    /// creating it if missing. Companion to [`Self::ensure_private_dir`]
    /// for directory hardlinks.
    pub fn ensure_dir_private_dir(&mut self) -> Result<FileEntry, FilesystemError> {
        let dir_private_name = hfsplus_dir_private_dir_name();
        let root = self.root()?;
        for entry in self.list_directory(&root)? {
            if entry.is_directory() && entry.name == dir_private_name {
                return Ok(entry);
            }
        }
        self.create_directory(&root, &dir_private_name, &CreateDirectoryOptions::default())
    }

    /// Create a hardlink inode (`iNode<inode_num>`) under the volume's
    /// private directory. The inode's data and resource forks hold the
    /// shared payload; its `bsdInfo.special` (linkCount) starts at zero
    /// and is bumped per-link by [`Self::create_hardlink`]. The caller is
    /// responsible for calling `sync_metadata` once all replay edits are
    /// staged.
    ///
    /// Returns an `AlreadyExists` error if `iNode<inode_num>` already lives
    /// in the private dir, so callers don't accidentally double-emit.
    pub fn create_hardlink_inode(
        &mut self,
        inode_num: u32,
        data: &mut dyn std::io::Read,
        data_len: u64,
        options: &CreateFileOptions,
    ) -> Result<FileEntry, FilesystemError> {
        let snap = self.snapshot();
        let result = (|| -> Result<FileEntry, FilesystemError> {
            let private = self.ensure_private_dir()?;
            let inode_name = format!("iNode{inode_num}");
            self.create_file(&private, &inode_name, data, data_len, options)
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Create a file hardlink stub at `(parent, name)` referencing the
    /// inode `iNode<inode_num>` under the private dir. The stub carries
    /// empty forks and FInfo `('hlnk', 'hfs+')` with
    /// `bsdInfo.special = inode_num`. The matching inode's linkCount
    /// (`bsdInfo.special`) is bumped by 1.
    ///
    /// Returns the stub's `FileEntry` with `link_target_cnid` set to the
    /// inode's CNID — callers that want the inode bytes can read through
    /// it directly via [`Self::read_file`] / [`Self::write_file_to`].
    pub fn create_hardlink(
        &mut self,
        parent: &FileEntry,
        name: &str,
        inode_num: u32,
    ) -> Result<FileEntry, FilesystemError> {
        let snap = self.snapshot();
        let result = (|| -> Result<FileEntry, FilesystemError> {
            let private_cnid = self.find_private_dir_cnid()?.ok_or_else(|| {
                FilesystemError::NotFound(
                    "HFS+ Private Data directory missing — call create_hardlink_inode first".into(),
                )
            })?;
            // Locate the inode and confirm it exists; bump its linkCount.
            let inode_name = format!("iNode{inode_num}");
            let inode_cnid = self
                .list_children(private_cnid)?
                .into_iter()
                .find_map(|c| match c {
                    CatalogEntry::File {
                        file_id, name: n, ..
                    } if n == inode_name => Some(file_id),
                    _ => None,
                })
                .ok_or_else(|| {
                    FilesystemError::NotFound(format!(
                        "hardlink inode '{inode_name}' missing — create it before linking"
                    ))
                })?;

            // Create the stub as an empty file with type/creator overrides.
            let mut empty: &[u8] = &[];
            let stub = self.create_file(
                parent,
                name,
                &mut empty,
                0,
                &CreateFileOptions {
                    os_type: Some(*b"hlnk"),
                    os_creator: Some(*b"hfs+"),
                    ..Default::default()
                },
            )?;

            // Patch bsdInfo.special on the stub to hold the iNodeNum.
            let parent_cnid = parent.location as u32;
            let (_, _, abs) = self.find_catalog_record(parent_cnid, name).ok_or_else(|| {
                FilesystemError::NotFound(format!(
                    "freshly-created stub '{name}' missing from catalog"
                ))
            })?;
            let key_len = BigEndian::read_u16(&self.catalog_data[abs..abs + 2]) as usize;
            let mut body = abs + 2 + key_len;
            if !body.is_multiple_of(2) {
                body += 1;
            }
            BigEndian::write_u32(&mut self.catalog_data[body + 44..body + 48], inode_num);

            // Bump linkCount on the inode (saturates if it overflows).
            self.adjust_inode_link_count(private_cnid, inode_num, 1)?;

            // Drop the cached inode_num -> CNID map so the next hardlink
            // resolution sees the new inode without picking up stale state.
            self.hardlink_inode_map = None;

            // Surface the inode CNID on the returned entry so callers can
            // inspect it without re-walking the catalog.
            let mut fe = stub;
            fe.link_target_cnid = Some(inode_cnid as u64);
            Ok(fe)
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Create a directory-hardlink inode (`dir_<inode_num>`) under the
    /// volume's directory-private directory. The inode is a regular folder
    /// — callers populate its contents like any other directory. Its
    /// `bsdInfo.special` (linkCount) starts at zero and is bumped per stub
    /// by [`Self::create_dir_hardlink`].
    pub fn create_dir_hardlink_inode(
        &mut self,
        inode_num: u32,
        options: &CreateDirectoryOptions,
    ) -> Result<FileEntry, FilesystemError> {
        let snap = self.snapshot();
        let result = (|| -> Result<FileEntry, FilesystemError> {
            let private = self.ensure_dir_private_dir()?;
            let inode_name = format!("dir_{inode_num}");
            self.create_directory(&private, &inode_name, options)
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Create a directory-hardlink stub at `(parent, name)` referencing
    /// `dir_<inode_num>` under the directory-private directory. The stub
    /// is a FILE record (not a folder) with FInfo `('fdrp', 'MACS')` and
    /// `bsdInfo.special = inode_num`; `list_directory` surfaces it as a
    /// `Directory` entry that follows the link automatically. The matching
    /// inode's linkCount (`bsdInfo.special`) is bumped by 1.
    pub fn create_dir_hardlink(
        &mut self,
        parent: &FileEntry,
        name: &str,
        inode_num: u32,
    ) -> Result<FileEntry, FilesystemError> {
        let snap = self.snapshot();
        let result = (|| -> Result<FileEntry, FilesystemError> {
            let dir_private_cnid = self.find_dir_private_dir_cnid()?.ok_or_else(|| {
                FilesystemError::NotFound(
                    ".HFS+ Private Directory Data missing — call create_dir_hardlink_inode first"
                        .into(),
                )
            })?;
            let inode_name = format!("dir_{inode_num}");
            let inode_cnid = self
                .list_children(dir_private_cnid)?
                .into_iter()
                .find_map(|c| match c {
                    CatalogEntry::Folder {
                        folder_id, name: n, ..
                    } if n == inode_name => Some(folder_id),
                    _ => None,
                })
                .ok_or_else(|| {
                    FilesystemError::NotFound(format!(
                        "directory inode '{inode_name}' missing — create it before linking"
                    ))
                })?;

            let mut empty: &[u8] = &[];
            let stub = self.create_file(
                parent,
                name,
                &mut empty,
                0,
                &CreateFileOptions {
                    os_type: Some(*b"fdrp"),
                    os_creator: Some(*b"MACS"),
                    ..Default::default()
                },
            )?;

            // Patch bsdInfo.special on the stub to hold the iNodeNum.
            let parent_cnid = parent.location as u32;
            let (_, _, abs) = self.find_catalog_record(parent_cnid, name).ok_or_else(|| {
                FilesystemError::NotFound(format!(
                    "freshly-created stub '{name}' missing from catalog"
                ))
            })?;
            let key_len = BigEndian::read_u16(&self.catalog_data[abs..abs + 2]) as usize;
            let mut body = abs + 2 + key_len;
            if !body.is_multiple_of(2) {
                body += 1;
            }
            BigEndian::write_u32(&mut self.catalog_data[body + 44..body + 48], inode_num);

            // Bump linkCount on the dir-inode's folder record (lives at
            // body+44..48 of the folder record too — DInfo doesn't overlap).
            self.adjust_dir_inode_link_count(dir_private_cnid, inode_num, 1)?;

            // Drop the cached map so the next lookup sees the new inode.
            self.dir_hardlink_inode_map = None;

            // Surface the inode CNID on the returned entry; flip its type
            // to Directory so callers treat it as one.
            let mut fe = stub;
            fe.entry_type = disk_core::entry::EntryType::Directory;
            fe.size = 0;
            fe.link_target_cnid = Some(inode_cnid as u64);
            Ok(fe)
        })();
        if result.is_err() {
            self.restore_snapshot(snap);
        }
        result
    }

    /// Adjust the directory-inode `linkCount` (`bsdInfo.special` u32 — at
    /// folder-record body offset 32+12 = 44, same as file records) by
    /// `delta`. Mirrors `adjust_inode_link_count` for file inodes.
    fn adjust_dir_inode_link_count(
        &mut self,
        dir_private_cnid: u32,
        inode_num: u32,
        delta: i64,
    ) -> Result<u32, FilesystemError> {
        let inode_name = format!("dir_{inode_num}");
        let (_, _, abs_off) = self
            .find_catalog_record(dir_private_cnid, &inode_name)
            .ok_or_else(|| {
                FilesystemError::InvalidData(format!(
                    "directory inode '{inode_name}' missing from .HFS+ Private Directory Data"
                ))
            })?;
        let key_len = BigEndian::read_u16(&self.catalog_data[abs_off..abs_off + 2]) as usize;
        let mut body_start = abs_off + 2 + key_len;
        if !body_start.is_multiple_of(2) {
            body_start += 1;
        }
        let cur = BigEndian::read_u32(&self.catalog_data[body_start + 44..body_start + 48]) as i64;
        let new = (cur + delta).max(0) as u32;
        BigEndian::write_u32(
            &mut self.catalog_data[body_start + 44..body_start + 48],
            new,
        );
        Ok(new)
    }

    fn create_file_inner(
        &mut self,
        parent: &FileEntry,
        name: &str,
        data: &mut dyn std::io::Read,
        data_len: u64,
        options: &CreateFileOptions,
    ) -> Result<FileEntry, FilesystemError> {
        let parent_cnid = parent.location as u32;

        validate_hfsplus_create_name(name)?;

        // Check for duplicates
        if self.find_catalog_record(parent_cnid, name).is_some() {
            return Err(FilesystemError::AlreadyExists(name.into()));
        }

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

        // Determine type/creator: prefer caller-supplied, fill any missing or
        // blank half from the extension dictionary so a partial FInfo from an
        // imported AppleDouble 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_fork = self.write_data_to_blocks(data, data_len, file_id, HFSPLUS_FORK_DATA)?;

        // Handle resource fork
        let rsrc_fork = 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);
                    self.write_data_to_blocks(
                        &mut cursor,
                        rsrc_data.len() as u64,
                        file_id,
                        HFSPLUS_FORK_RESOURCE,
                    )?
                }
                disk_core::filesystem::ResourceForkSource::File(path) => {
                    let mut f = std::fs::File::open(path)?;
                    let len = f.metadata()?.len();
                    self.write_data_to_blocks(&mut f, len, file_id, HFSPLUS_FORK_RESOURCE)?
                }
            }
        } else {
            ForkData::empty()
        };

        // 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`. The after-create Commander `set_dates` path still overrides.
        let mtime = options.unix_times.map(|t| t.mtime_or_now());
        let file_rec = Self::build_file_record_with_dates(
            file_id,
            &data_fork,
            &rsrc_fork,
            &type_code,
            &creator_code,
            mtime,
            options.finder_flags.unwrap_or(0),
        );

        // Build key + record for catalog insertion
        let key = Self::build_catalog_key(parent_cnid, name);
        let mut key_record = key.clone();
        // Pad to even boundary if needed
        if key_record.len() % 2 != 0 {
            key_record.push(0);
        }
        key_record.extend_from_slice(&file_rec);

        // Insert file record
        self.insert_catalog_record(&key_record)?;

        // Build and insert thread record
        let (thread_key, thread_data) =
            Self::build_thread_record(CATALOG_FILE_THREAD, parent_cnid, name);
        let mut thread_record = thread_key;
        if thread_record.len() % 2 != 0 {
            thread_record.push(0);
        }
        thread_record.extend_from_slice(&thread_data);
        // Thread key is (file_id, ""), but build_thread_record used parent_cnid...
        // Actually, thread records are keyed by (file_id, "")
        let actual_thread_key = Self::build_catalog_key(file_id, "");
        let mut actual_thread_record = actual_thread_key;
        if actual_thread_record.len() % 2 != 0 {
            actual_thread_record.push(0);
        }
        actual_thread_record.extend_from_slice(&thread_data);
        self.insert_catalog_record(&actual_thread_record)?;

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

        // Update VH counts
        self.vh.file_count += 1;

        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);
        }
        if rsrc_fork.logical_size > 0 {
            fe.resource_fork_size = Some(rsrc_fork.logical_size);
        }
        let stamped = mtime.unwrap_or_else(disk_core::times::now);
        fe.modified_unix = Some(stamped);
        Ok(fe)
    }

    fn create_directory_inner(
        &mut self,
        parent: &FileEntry,
        name: &str,
        options: &CreateDirectoryOptions,
    ) -> Result<FileEntry, FilesystemError> {
        let parent_cnid = parent.location as u32;

        validate_hfsplus_create_name(name)?;

        // Diagnostic: refuse to create a second `\0\0\0\0HFS+ Private Data`
        // or `.HFS+ Private Directory Data\r` directory at the volume root.
        // The hardlink subsystem is the only legitimate creator of these
        // magic-named directories (via `ensure_private_dir`), and it walks
        // `list_directory(root)` to detect an existing one before falling
        // back to create. If `find_catalog_record` later misses it (e.g.
        // due to a key-compare quirk), the resulting duplicate is the bug
        // observed in HFSTest6 (2026-05). Belt-and-suspenders: in addition
        // to the find_catalog_record check below, scan root by CNID-aware
        // lookup so neither a name-fold mismatch nor a misplaced record
        // slips through. See docs/hfs_write_tweaks.md.
        if parent_cnid == 2
            && (name == hfsplus_private_dir_name() || name == hfsplus_dir_private_dir_name())
        {
            let already_present = self
                .find_private_dir_cnid()?
                .filter(|_| name == hfsplus_private_dir_name())
                .is_some()
                || self
                    .find_dir_private_dir_cnid()?
                    .filter(|_| name == hfsplus_dir_private_dir_name())
                    .is_some();
            if already_present {
                let bt = std::backtrace::Backtrace::force_capture();
                log::error!(
                    "[HFS+] refused create_directory for magic name (already \
                     present). parent_cnid={}, leading NULs={}\nbacktrace:\n{bt}",
                    parent_cnid,
                    name.chars().take_while(|c| *c == '\0').count()
                );
                return Err(FilesystemError::AlreadyExists(name.into()));
            }
        }

        // Check duplicates
        if self.find_catalog_record(parent_cnid, name).is_some() {
            return Err(FilesystemError::AlreadyExists(name.into()));
        }

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

        // Build folder record
        // See build_file_record_with_dates for the mtime semantics.
        let mtime = options.unix_times.map(|t| t.mtime_or_now());
        let folder_rec = Self::build_folder_record_with_dates(folder_id, mtime);

        // Build key + record
        let key = Self::build_catalog_key(parent_cnid, name);
        let mut key_record = key.clone();
        if key_record.len() % 2 != 0 {
            key_record.push(0);
        }
        key_record.extend_from_slice(&folder_rec);

        self.insert_catalog_record(&key_record)?;

        // Thread record (type 3 = folder thread)
        let (_thread_key, thread_data) =
            Self::build_thread_record(CATALOG_FOLDER_THREAD, parent_cnid, name);
        let actual_thread_key = Self::build_catalog_key(folder_id, "");
        let mut actual_thread_record = actual_thread_key;
        if actual_thread_record.len() % 2 != 0 {
            actual_thread_record.push(0);
        }
        actual_thread_record.extend_from_slice(&thread_data);
        self.insert_catalog_record(&actual_thread_record)?;

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

        // Update VH
        self.vh.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);
        Ok(fe)
    }

    fn delete_entry_inner(
        &mut self,
        parent: &FileEntry,
        entry: &FileEntry,
    ) -> Result<(), FilesystemError> {
        let parent_cnid = parent.location as u32;
        let cnid = entry.location as u32;

        // Drop every attribute record attached to this CNID so we don't leave
        // dangling rows in the attributes B-tree pointing at a freed CNID.
        // No-op on volumes without an attributes file. Errors here trip the
        // snapshot rollback in `delete_entry`.
        let xattrs_removed = self.remove_xattr_records(cnid, None)?;
        if xattrs_removed > 0 {
            if let Some(set) = self.xattr_cnids.as_mut() {
                set.remove(&cnid);
            }
        }

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

        // File hardlink stub? If so, decrement the inode's linkCount before
        // we touch the stub's catalog row. Last reference also frees the
        // inode's forks and removes its iNode<N> entry from the private
        // directory.
        let link_inode_num = if entry.is_directory() {
            None
        } else {
            self.read_file_record_link_inode_num(parent_cnid, &entry.name)?
        };
        if let Some(inode_num) = link_inode_num {
            self.delete_hardlink_inode_ref(inode_num)?;
        }

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

        // If it's a file, free its data and resource fork blocks (including
        // any overflow extents) and remove its overflow records. Hardlink
        // stubs have empty forks (the data lives on the inode we already
        // adjusted above), so this is a no-op for them.
        if !entry.is_directory() {
            if let Some((data_fork, rsrc_fork)) = self.find_file_by_id(cnid) {
                self.free_fork_overflow_extents(cnid, HFSPLUS_FORK_DATA, &data_fork);
                self.free_fork_overflow_extents(cnid, HFSPLUS_FORK_RESOURCE, &rsrc_fork);
                self.remove_extents_overflow_records_for(cnid, HFSPLUS_FORK_DATA)?;
                self.remove_extents_overflow_records_for(cnid, HFSPLUS_FORK_RESOURCE)?;
                self.free_fork_blocks(&data_fork);
                self.free_fork_blocks(&rsrc_fork);
            }
        }

        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_cnid, -1)?;

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

        Ok(())
    }

    fn rename_inner(
        &mut self,
        parent: &FileEntry,
        entry: &FileEntry,
        new_name: &str,
    ) -> Result<(), FilesystemError> {
        let parent_cnid = parent.location as u32;
        let cnid = entry.location as u32;

        // Locate the entry's catalog record by its current (parent, name) key.
        let (node_idx, rec_idx, _abs) = self
            .find_catalog_record(parent_cnid, &entry.name)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("entry '{}' not found in catalog", entry.name))
            })?;

        // Reject a collision only with a DIFFERENT record. On a case-insensitive
        // volume a case-only rename folds back to this same record (allowed).
        if let Some((n2, r2, _)) = self.find_catalog_record(parent_cnid, new_name) {
            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 (CNID, forks, Finder info, BSD info all preserved).
        let node_size = self.catalog_node_size();
        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) = crate::hfs_common::btree_record_range(node, node_size, rec_idx);
        let key_len = BigEndian::read_u16(&node[rec_start..rec_start + 2]) as usize;
        let mut data_rel = 2 + 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_cnid, new_name);
        if new_record.len() % 2 != 0 {
            new_record.push(0);
        }
        new_record.extend_from_slice(&data_bytes);

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

        // The thread record's name is a variable-length UTF-16 string, so its
        // footprint changes with the new name — rebuild it (remove + reinsert)
        // rather than patching in place. Folders always have a thread; files
        // generally do.
        if let Some((t_node, t_rec, _)) = self.find_catalog_record_by_cnid(cnid) {
            self.remove_catalog_record(t_node, t_rec)?;
            let thread_type = if entry.is_directory() {
                CATALOG_FOLDER_THREAD
            } else {
                CATALOG_FILE_THREAD
            };
            let (_k, thread_data) = Self::build_thread_record(thread_type, parent_cnid, new_name);
            let mut thread_record = Self::build_catalog_key(cnid, "");
            if thread_record.len() % 2 != 0 {
                thread_record.push(0);
            }
            thread_record.extend_from_slice(&thread_data);
            self.insert_catalog_record(&thread_record)?;
        }
        // A same-parent rename leaves parent valence and VH counts unchanged.
        Ok(())
    }

    /// Adjust the inode-record `linkCount` (`bsdInfo.special`, body offset
    /// 44..48) by `delta` and return the post-update count. Locates the
    /// record by `(private_dir_cnid, "iNode<N>")` so the in-memory edit
    /// hits the live catalog leaf. Touches `attributeModDate` so users can
    /// see when the inode was last referenced.
    fn adjust_inode_link_count(
        &mut self,
        private_cnid: u32,
        inode_num: u32,
        delta: i64,
    ) -> Result<u32, FilesystemError> {
        let inode_name = format!("iNode{inode_num}");
        let (_, _, abs_off) = self
            .find_catalog_record(private_cnid, &inode_name)
            .ok_or_else(|| {
                FilesystemError::InvalidData(format!(
                    "hardlink inode '{inode_name}' missing from HFS+ Private Data"
                ))
            })?;
        let key_len = BigEndian::read_u16(&self.catalog_data[abs_off..abs_off + 2]) as usize;
        let mut body_start = abs_off + 2 + key_len;
        if !body_start.is_multiple_of(2) {
            body_start += 1;
        }
        let cur = BigEndian::read_u32(&self.catalog_data[body_start + 44..body_start + 48]) as i64;
        let new = (cur + delta).max(0) as u32;
        BigEndian::write_u32(
            &mut self.catalog_data[body_start + 44..body_start + 48],
            new,
        );
        self.stamp_record_dates(body_start, false);
        Ok(new)
    }

    /// Decrement `linkCount` on the inode named `iNode<inode_num>` under the
    /// volume's `HFS+ Private Data` dir. When the count drops to zero, free
    /// the inode's forks, drop its xattrs, and remove the inode catalog row
    /// plus thread plus map entry. Bumps `vh.file_count` and the private
    /// dir's valence accordingly.
    fn delete_hardlink_inode_ref(&mut self, inode_num: u32) -> Result<(), FilesystemError> {
        let private_cnid = self.find_private_dir_cnid()?.ok_or_else(|| {
            FilesystemError::InvalidData(
                "hardlink stub on volume with no HFS+ Private Data directory".into(),
            )
        })?;
        let inode_cnid = self.resolve_hardlink_inode(inode_num)?.ok_or_else(|| {
            FilesystemError::InvalidData(format!(
                "hardlink target iNode{inode_num} missing from HFS+ Private Data"
            ))
        })?;

        let new_count = self.adjust_inode_link_count(private_cnid, inode_num, -1)?;
        if new_count > 0 {
            return Ok(());
        }

        // Last reference — free the inode's forks and drop its rows.
        if let Some((data_fork, rsrc_fork)) = self.find_file_by_id(inode_cnid) {
            self.free_fork_overflow_extents(inode_cnid, HFSPLUS_FORK_DATA, &data_fork);
            self.free_fork_overflow_extents(inode_cnid, HFSPLUS_FORK_RESOURCE, &rsrc_fork);
            self.remove_extents_overflow_records_for(inode_cnid, HFSPLUS_FORK_DATA)?;
            self.remove_extents_overflow_records_for(inode_cnid, HFSPLUS_FORK_RESOURCE)?;
            self.free_fork_blocks(&data_fork);
            self.free_fork_blocks(&rsrc_fork);
        }

        let xattrs_removed = self.remove_xattr_records(inode_cnid, None)?;
        if xattrs_removed > 0 {
            if let Some(set) = self.xattr_cnids.as_mut() {
                set.remove(&inode_cnid);
            }
        }

        let inode_name = format!("iNode{inode_num}");
        if let Some((n, r, _)) = self.find_catalog_record(private_cnid, &inode_name) {
            self.remove_catalog_record(n, r)?;
        }
        if let Some((tn, tr, _)) = self.find_catalog_record_by_cnid(inode_cnid) {
            self.remove_catalog_record(tn, tr)?;
        }
        self.update_parent_valence(private_cnid, -1)?;
        self.vh.file_count = self.vh.file_count.saturating_sub(1);

        if let Some(map) = self.hardlink_inode_map.as_mut() {
            map.remove(&inode_num);
        }
        Ok(())
    }

    fn set_type_creator_inner(
        &mut self,
        entry: &FileEntry,
        type_code: &str,
        creator_code: &str,
    ) -> Result<(), FilesystemError> {
        let cnid = entry.location as u32;

        // Find the thread to get parent + name
        let (_t_node, _t_rec, t_offset) =
            self.find_catalog_record_by_cnid(cnid).ok_or_else(|| {
                FilesystemError::NotFound(format!("thread for CNID {cnid} not found"))
            })?;

        // Read parent_cnid and name from thread data
        let node_size = self.catalog_header.node_size as usize;
        let key_len = BigEndian::read_u16(&self.catalog_data[t_offset..t_offset + 2]) as usize;
        let mut rec_data_start = t_offset + 2 + 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 + 4..rec_data_start + 8]);
        let thread_name_len =
            BigEndian::read_u16(&self.catalog_data[rec_data_start + 8..rec_data_start + 10])
                as usize;
        let thread_name = decode_utf16be(
            &self.catalog_data[rec_data_start + 10..rec_data_start + 10 + thread_name_len * 2],
        );

        // Find the actual file record
        let (f_node, f_rec, f_offset) = self
            .find_catalog_record(thread_parent, &thread_name)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("file record for '{}' not found", thread_name))
            })?;

        // Compute the record data offset
        let fkey_len = BigEndian::read_u16(&self.catalog_data[f_offset..f_offset + 2]) as usize;
        let mut frec_start = f_offset + 2 + fkey_len;
        if !frec_start.is_multiple_of(2) {
            frec_start += 1;
        }

        // Write type and creator at offsets 48-52 and 52-56
        let tc = hfs_common::encode_fourcc(type_code);
        let cc = hfs_common::encode_fourcc(creator_code);
        self.catalog_data[frec_start + 48..frec_start + 52].copy_from_slice(&tc);
        self.catalog_data[frec_start + 52..frec_start + 56].copy_from_slice(&cc);

        // Type/creator is an attribute-only change.
        self.stamp_record_dates(frec_start, false);

        let _ = (f_node, f_rec, node_size); // suppress warnings
        Ok(())
    }

    fn write_resource_fork_inner(
        &mut self,
        entry: &FileEntry,
        data: &mut dyn std::io::Read,
        len: u64,
    ) -> Result<(), FilesystemError> {
        let cnid = entry.location as u32;

        // Free existing resource fork blocks (inline + any overflow extents).
        if let Some((_data_fork, rsrc_fork)) = self.find_file_by_id(cnid) {
            self.free_fork_overflow_extents(cnid, HFSPLUS_FORK_RESOURCE, &rsrc_fork);
            self.remove_extents_overflow_records_for(cnid, HFSPLUS_FORK_RESOURCE)?;
            self.free_fork_blocks(&rsrc_fork);
        }

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

        // Find the file record and update the resource fork
        let (t_node, _t_rec, t_offset) =
            self.find_catalog_record_by_cnid(cnid).ok_or_else(|| {
                FilesystemError::NotFound(format!("thread for CNID {cnid} not found"))
            })?;

        let key_len = BigEndian::read_u16(&self.catalog_data[t_offset..t_offset + 2]) as usize;
        let mut rec_data_start = t_offset + 2 + 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 + 4..rec_data_start + 8]);
        let thread_name_len =
            BigEndian::read_u16(&self.catalog_data[rec_data_start + 8..rec_data_start + 10])
                as usize;
        let thread_name = decode_utf16be(
            &self.catalog_data[rec_data_start + 10..rec_data_start + 10 + thread_name_len * 2],
        );

        let (_f_node, _f_rec, f_offset) = self
            .find_catalog_record(thread_parent, &thread_name)
            .ok_or_else(|| {
                FilesystemError::NotFound(format!("file record for '{}' not found", thread_name))
            })?;

        let fkey_len = BigEndian::read_u16(&self.catalog_data[f_offset..f_offset + 2]) as usize;
        let mut frec_start = f_offset + 2 + fkey_len;
        if !frec_start.is_multiple_of(2) {
            frec_start += 1;
        }

        // Write resource fork data (at offset 168 in file record)
        let mut rsrc_bytes = [0u8; 80];
        new_rsrc.serialize(&mut rsrc_bytes);
        self.catalog_data[frec_start + 168..frec_start + 248].copy_from_slice(&rsrc_bytes);

        // Fork rewrite is a content change, so contentModDate also moves.
        self.stamp_record_dates(frec_start, true);

        let _ = t_node;
        Ok(())
    }

    fn set_blessed_folder_inner(&mut self, entry: &FileEntry) -> Result<(), FilesystemError> {
        if !entry.is_directory() {
            return Err(FilesystemError::InvalidData(
                "can only bless a directory".into(),
            ));
        }
        self.vh.finder_info[0] = entry.location as u32;
        Ok(())
    }
}

// --- Compact reader ---

/// Compact reader for HFS+: layout-preserving image with zeros for unallocated blocks.
///
/// Outputs `total_blocks * block_size` bytes. Allocated blocks are read from the
/// source; unallocated blocks are emitted as zeros. This preserves the original
/// block layout so that `block_N` is always at byte offset `N * block_size`,
/// enabling correct filesystem browsing and reliable restore.
/// Streaming reader over a single user fork. Built by
/// [`HfsPlusFilesystem::fork_stream_reader`] with all inline + overflow
/// extents resolved up front; `read` walks the extent list, seeking the
/// underlying source reader as it crosses extent boundaries. Bounded
/// strictly by the fork's `logical_size` — the trailing partial block is
/// truncated at the byte level rather than the block level.
pub struct ForkStreamReader<'a, R: Read + Seek> {
    reader: &'a mut R,
    /// `(device_offset, byte_length)` for each extent, in fork order.
    extents: Vec<(u64, u64)>,
    /// Total bytes the reader is allowed to emit (`fork.logical_size`).
    logical_size: u64,
    /// Bytes already produced.
    pos: u64,
    cur_extent: usize,
    /// Bytes already consumed from the current extent.
    cur_extent_consumed: u64,
}

impl<'a, R: Read + Seek> Read for ForkStreamReader<'a, R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.pos >= self.logical_size || buf.is_empty() {
            return Ok(0);
        }
        // Skip past extents whose bytes are fully consumed.
        while self.cur_extent < self.extents.len() {
            let (_, len) = self.extents[self.cur_extent];
            if self.cur_extent_consumed < len {
                break;
            }
            self.cur_extent += 1;
            self.cur_extent_consumed = 0;
        }
        if self.cur_extent >= self.extents.len() {
            return Ok(0);
        }
        let (off, len) = self.extents[self.cur_extent];
        let remaining_in_extent = len - self.cur_extent_consumed;
        let remaining_logical = self.logical_size - self.pos;
        let max_chunk = remaining_in_extent.min(remaining_logical);
        let to_read = (buf.len() as u64).min(max_chunk) as usize;
        self.reader
            .seek(SeekFrom::Start(off + self.cur_extent_consumed))?;
        let n = self.reader.read(&mut buf[..to_read])?;
        if n == 0 {
            return Ok(0);
        }
        self.cur_extent_consumed += n as u64;
        self.pos += n as u64;
        Ok(n)
    }
}

pub struct CompactHfsPlusReader<R: Read + Seek> {
    reader: R,
    partition_offset: u64,
    block_size: u32,
    total_blocks: u32,
    bitmap: Vec<u8>,
    /// Current allocation block being output.
    current_block: u32,
    /// Byte position within the current block.
    block_pos: u64,
    #[allow(dead_code)]
    original_size: u64,
}

impl<R: Read + Seek> CompactHfsPlusReader<R> {
    pub fn new(
        mut reader: R,
        partition_offset: u64,
    ) -> Result<(Self, CompactResult), FilesystemError> {
        // Read volume header
        log::debug!(
            "[HFS+ compact] seeking to VH at offset {}",
            partition_offset + 1024
        );
        reader.seek(SeekFrom::Start(partition_offset + 1024))?;
        let mut vh_buf = [0u8; 512];
        reader.read_exact(&mut vh_buf)?;
        let vh = HfsPlusVolumeHeader::parse(&vh_buf)?;
        log::debug!(
            "[HFS+ compact] VH ok: block_size={}, total_blocks={}, alloc_file extents[0]=(start={}, count={})",
            vh.block_size,
            vh.total_blocks,
            vh.allocation_file.extents[0].start_block,
            vh.allocation_file.extents[0].block_count,
        );

        // Load extents-overflow first so the allocation file can use it if
        // it's fragmented past 8 inline extents.
        let extents_overflow_data = if vh.extents_file.logical_size > 0 {
            Some(read_fork(
                &mut reader,
                partition_offset,
                vh.block_size,
                &vh.extents_file,
            )?)
        } else {
            None
        };

        // Read allocation file
        let alloc_data = read_fork_with_overflow(
            &mut reader,
            partition_offset,
            vh.block_size,
            &vh.allocation_file,
            HFSPLUS_ALLOCATION_FILE_ID,
            HFSPLUS_FORK_DATA,
            extents_overflow_data.as_deref(),
        )
        .map_err(|e| {
            log::debug!("[HFS+ compact] read_fork(alloc_file) failed: {e}");
            e
        })?;
        log::debug!(
            "[HFS+ compact] allocation bitmap read: {} bytes",
            alloc_data.len()
        );

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

        let original_size = vh.total_blocks as u64 * vh.block_size as u64;
        // Layout-preserving: output size equals the original partition size.
        // Unallocated blocks are zeroed, so they compress extremely well.
        let compacted_size = original_size;
        // data_size: only allocated blocks require disk reads.
        let data_size = allocated as u64 * vh.block_size as u64;
        log::debug!(
            "[HFS+ compact] compacted_size={} data_size={} original_size={} (layout-preserving; free blocks -> zeros)",
            compacted_size, data_size, original_size
        );

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

        Ok((
            CompactHfsPlusReader {
                reader,
                partition_offset,
                block_size: vh.block_size,
                total_blocks: vh.total_blocks,
                bitmap: alloc_data,
                current_block: 0,
                block_pos: 0,
                original_size,
            },
            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 CompactHfsPlusReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.current_block >= self.total_blocks {
            return Ok(0);
        }

        let block_size = self.block_size as u64;

        // Find the longest run starting at the current block whose
        // allocation state matches the current block's, then service as
        // much of that run as fits in `buf`. Coalescing turns a 24 GiB
        // partition's ~6M per-4-KiB-block syscalls into far fewer reads
        // (typically one per file extent), critical on slow source media
        // where each seek + read costs milliseconds.
        let allocated = self.is_block_allocated(self.current_block);
        let mut run_end = self.current_block + 1;
        while run_end < self.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.current_block as u64 * block_size + self.block_pos;
            self.reader.seek(SeekFrom::Start(offset))?;
            self.reader.read(&mut buf[..to_read])?
        } else {
            // Unallocated run — emit zeros so free space compresses to nothing.
            buf[..to_read].fill(0);
            to_read
        };

        // Advance cursor by however many bytes we actually produced.
        let mut remaining_in_n = n as u64;
        // First, finish the partial block we may have been mid-way through.
        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;
            }
        }
        // Then jump whole blocks.
        let whole = (remaining_in_n / block_size) as u32;
        self.current_block += whole;
        remaining_in_n -= whole as u64 * block_size;
        // Finally the trailing partial block.
        if remaining_in_n > 0 {
            self.block_pos = remaining_in_n;
        }

        Ok(n)
    }
}

// --- Blank-volume builder ---

/// Build a freshly-formatted, mountable HFS+ (or HFSX) image as a raw byte
/// buffer.
///
/// Layout (sized for `block_size` ≤ `node_size`; node_size is fixed at
/// 4096 to match Apple's default):
///
/// - Block 0: VH region (1024 boot bytes + primary VH at byte 1024)
/// - Bitmap blocks: enough to hold `total_blocks / 8` bytes
/// - Extents-overflow B-tree: 4 nodes (header + empty leaf + 2 free)
/// - Catalog B-tree: 4 nodes (header + leaf with root folder + thread)
/// - Free user-data area
/// - Last 1024 bytes: alt VH (mirror of primary)
///
/// The catalog leaf carries two records: the root folder thread keyed by
/// `(parent=2, name="")` (data: `recordType=3`, `parentID=1`, nodeName =
/// `name`) and the root folder record keyed by `(parent=1, name=name)`
/// (data: `recordType=1`, `folderID=2`, valence=0, dates set to now).
///
/// `case_sensitive=true` produces an HFSX volume (signature `H+`/`HX`,
/// catalog header `keyCompareType = kHFSBinaryCompare`); `false` produces
/// plain HFS+ with case-folding compare. The journaled bit is never set —
/// edit mode refuses journaled volumes (Step 4) so a freshly built blank
/// must opt out.
///
/// Panics if `size_bytes` is too small to hold the reserved region or if
/// `block_size` isn't a power of 2 in `[512, 4096]`.
pub fn create_blank_hfsplus(
    size_bytes: u64,
    block_size: u32,
    name: &str,
    case_sensitive: bool,
) -> Vec<u8> {
    create_blank_hfsplus_sized(size_bytes, block_size, name, case_sensitive, 0, 0)
}

/// Volume-scaled default catalog B-tree size, in bytes, for a fresh HFS+
/// volume. Mirrors classic HFS's `default_btree_sizes`: ~0.5% of the volume so
/// a blank holds thousands of records before exhausting its node budget (HFS+
/// has no grow-on-full path — docs/hfsplus_btree_growth_plan.md §4c). The
/// `build_blank_hfsplus_front` caller clamps the result to whole nodes in
/// `[4, header-bitmap capacity]`.
pub fn default_hfsplus_catalog_bytes(volume_bytes: u64) -> u64 {
    volume_bytes / 200
}

/// Variant of [`create_blank_hfsplus`] that lets the caller request minimum
/// catalog and extents-overflow B-tree sizes (in bytes) — e.g. a clone target
/// that must hold every record from a fragmented source, or a test that needs a
/// deep catalog without a multi-GiB volume. Each minimum is rounded up to whole
/// nodes and raised to the 4-node floor; the catalog also never drops below the
/// volume-scaled [`default_hfsplus_catalog_bytes`].
pub fn create_blank_hfsplus_sized(
    size_bytes: u64,
    block_size: u32,
    name: &str,
    case_sensitive: bool,
    min_catalog_bytes: u32,
    min_extents_bytes: u32,
) -> Vec<u8> {
    let (front, vh_bytes, image_size) = build_blank_hfsplus_front(
        size_bytes,
        block_size,
        name,
        case_sensitive,
        min_catalog_bytes,
        min_extents_bytes,
    );
    let mut img = vec![0u8; image_size];
    img[..front.len()].copy_from_slice(&front);
    let alt = image_size - 1024;
    img[alt..alt + 512].copy_from_slice(&vh_bytes);
    img
}

/// Build only the front (boot/VH/bitmap/B-trees) region and the 512-byte
/// VH bytes. Returns `(front_bytes, vh_bytes, total_image_size)`. Used by
/// both [`create_blank_hfsplus`] (full Vec) and
/// [`write_blank_hfsplus_into`] (sparse-file streaming).
fn build_blank_hfsplus_front(
    size_bytes: u64,
    block_size: u32,
    name: &str,
    case_sensitive: bool,
    min_catalog_bytes: u32,
    min_extents_bytes: u32,
) -> (Vec<u8>, [u8; 512], usize) {
    assert!(
        block_size.is_power_of_two() && (512..=4096).contains(&block_size),
        "block_size must be a power of 2 in [512, 4096], got {block_size}"
    );
    let bs = block_size as u64;
    let total_blocks = (size_bytes / bs) as u32;
    assert!(total_blocks >= 64, "image too small ({size_bytes} bytes)");

    // node_size pinned at 4096 — Apple's default and what every existing
    // helper in this file assumes (compute_record_offsets, etc.).
    let node_size: usize = 4096;
    let nodes_per_block: u32 = (node_size as u32 / block_size).max(1);
    let blocks_per_node: u32 = (block_size / node_size as u32).max(1);
    let _ = nodes_per_block;

    // Size the catalog B-tree from the volume (docs/hfsplus_btree_growth_plan.md
    // §4c): HFS+ has no grow-on-full path, so a blank that reserved only the
    // legacy 4 nodes exhausted after ~24 files. Scale it to ~0.5% of the volume
    // (mirroring classic HFS's `default_btree_sizes`) so a fresh volume holds
    // thousands of records, honouring an explicit `min_catalog_bytes` floor from
    // sized/clone callers. The extents-overflow tree keeps the 4-node default
    // unless a caller asks for more (its own scaling is P3 work).
    //
    // `to_nodes` rounds a byte budget up to whole nodes and clamps to
    // [4, header-bitmap capacity]. The blank's node-allocation bitmap lives
    // entirely in the header node's record 2 (bytes 248..node_size-8 — see
    // `write_blank_btree_header_node`), which addresses `(node_size - 256) * 8`
    // nodes without dedicated map nodes; cap there. Volumes whose 0.5% catalog
    // would exceed this (~123 MiB at 4096, i.e. hundreds of GiB of volume) are
    // far larger than this tool targets, and the defrag/clone path — which does
    // build map nodes — covers them. (The §4b live-grow path appends map nodes
    // incrementally past this cap; see `grow_btree_fork`.)
    let max_btree_nodes: u32 = ((node_size - 256) * 8) as u32;
    let to_nodes = |bytes: u64| -> u32 {
        bytes
            .div_ceil(node_size as u64)
            .clamp(4, max_btree_nodes as u64) as u32
    };
    let catalog_node_count =
        to_nodes(default_hfsplus_catalog_bytes(size_bytes).max(min_catalog_bytes as u64));
    let extents_node_count = to_nodes(min_extents_bytes as u64);

    let catalog_btree_blocks: u32 = catalog_node_count * blocks_per_node;
    let extents_btree_blocks: u32 = extents_node_count * blocks_per_node;

    let bitmap_bytes = total_blocks.div_ceil(8) as u64;
    let bitmap_blocks = bitmap_bytes.div_ceil(bs) as u32;

    let bitmap_start: u32 = 1;
    let extents_start: u32 = bitmap_start + bitmap_blocks;
    let catalog_start: u32 = extents_start + extents_btree_blocks;
    let reserved_blocks: u32 = catalog_start + catalog_btree_blocks;
    assert!(
        reserved_blocks + 1 < total_blocks,
        "image too small for reserved region: need {} blocks, have {total_blocks}",
        reserved_blocks + 1
    );

    let image_size = total_blocks as usize * block_size as usize;
    // Build only the front (boot/VH/bitmap/B-trees) and the 512-byte alt VH
    // separately, so multi-GB blanks don't have to materialise a full image
    // in RAM. The middle of the volume is free space — sparse-file zeroes
    // are good enough.
    let front_size = reserved_blocks as usize * block_size as usize;
    let mut front = vec![0u8; front_size];

    // The alternate volume header occupies the last 1024 bytes of the volume.
    // Apple always marks the trailing allocation block(s) it touches as used
    // (one block for block_size >= 1024, two for 512-byte blocks) and excludes
    // them from the free-block count. Without this, fsck_hfs reports
    // "Invalid volume free block count" / bitmap under-allocation.
    let alt_vh_start_block: u32 = ((image_size as u64 - 1024) / bs) as u32;
    let trailing_blocks: u32 = total_blocks - alt_vh_start_block;

    // --- Allocation bitmap ---
    {
        let bitmap_off = bitmap_start as usize * block_size as usize;
        let bitmap = &mut front[bitmap_off..bitmap_off + (bitmap_bytes as usize).max(1)];
        let mut mark = |blk: u32| {
            // MSB-first big-endian: bit position (7 - blk%8) of byte (blk/8).
            let byte_idx = (blk / 8) as usize;
            let bit_pos = 7 - (blk % 8);
            bitmap[byte_idx] |= 1 << bit_pos;
        };
        for blk in 0..reserved_blocks {
            mark(blk);
        }
        for blk in alt_vh_start_block..total_blocks {
            mark(blk);
        }
    }

    // --- Extents-overflow B-tree (empty: header node only) ---
    // An empty tree is depth-0 / root-0 with no leaf node, exactly as Apple's
    // newfs_hfs lays it out (see `write_blank_btree_header_node`). The first
    // fragmented-file insert bootstraps a root leaf via `btree_insert_full`.
    {
        let off = extents_start as usize * block_size as usize;
        write_blank_btree_header_node(
            &mut front[off..off + node_size],
            node_size,
            /* leaf_records= */ 0,
            /* total_nodes= */ extents_node_count,
            /* free_nodes= */ extents_node_count - 1, // only the header node is used
            /* max_key_len= */ 10,
            /* key_compare_type= */ 0, // unused for extents
        );
    }

    // --- Catalog B-tree (header + leaf with root + thread) ---
    let name_utf16: Vec<u16> = fs_mac_unicode::hfs_unicode::decompose_str(name);
    {
        let off = catalog_start as usize * block_size as usize;
        let key_compare = if case_sensitive {
            KEY_COMPARE_BINARY
        } else {
            KEY_COMPARE_CASE_FOLDING
        };
        write_blank_btree_header_node(
            &mut front[off..off + node_size],
            node_size,
            /* leaf_records= */ 2,
            catalog_node_count,
            catalog_node_count - 2,
            /* max_key_len= */ 516, // HFS+ catalog max key
            key_compare,
        );
        let leaf_off = off + node_size;
        write_root_catalog_leaf(&mut front[leaf_off..leaf_off + node_size], &name_utf16);
    }

    // --- Volume header ---
    let signature = if case_sensitive {
        HFSX_SIGNATURE
    } else {
        HFS_PLUS_SIGNATURE
    };
    let now = hfs_common::hfs_now();
    let vh = HfsPlusVolumeHeader {
        signature,
        version: if case_sensitive { 5 } else { 4 },
        attributes: HFSPLUS_VOLUME_UNMOUNTED_BIT,
        last_mounted_version: 0,
        journal_info_block: 0,
        create_date: now,
        modify_date: now,
        backup_date: 0,
        checked_date: now,
        file_count: 0,
        // Per Apple TN1150, folder_count EXCLUDES the root directory.
        // Matches what macOS / Disk Utility / fsck_hfs expect on a fresh
        // volume; mismatching this causes false-positive
        // FolderCountMismatch reports when fsck'ing volumes created
        // elsewhere and edited here.
        folder_count: 0,
        block_size,
        total_blocks,
        free_blocks: total_blocks - reserved_blocks - trailing_blocks,
        next_allocation: reserved_blocks,
        rsrc_clump_size: block_size,
        data_clump_size: block_size,
        next_catalog_id: 16,
        write_count: 0,
        encodings_bitmap: 1, // bit 0 = MacRoman, conventional default
        finder_info: [0u32; 8],
        allocation_file: ForkData {
            logical_size: bitmap_blocks as u64 * bs,
            clump_size: 0,
            total_blocks: bitmap_blocks,
            extents: extent_array(bitmap_start, bitmap_blocks),
        },
        extents_file: ForkData {
            logical_size: extents_btree_blocks as u64 * bs,
            clump_size: 0,
            total_blocks: extents_btree_blocks,
            extents: extent_array(extents_start, extents_btree_blocks),
        },
        catalog_file: ForkData {
            logical_size: catalog_btree_blocks as u64 * bs,
            clump_size: 0,
            total_blocks: catalog_btree_blocks,
            extents: extent_array(catalog_start, catalog_btree_blocks),
        },
        attributes_file: ForkData::empty(),
        startup_file: ForkData::empty(),
    };
    let vh_bytes = vh.serialize();

    // Primary VH at offset 1024 (always inside the front region).
    front[1024..1536].copy_from_slice(&vh_bytes);

    (front, vh_bytes, image_size)
}

/// Streaming variant of [`create_blank_hfsplus`]. Writes the metadata
/// regions (boot, VH, bitmap, B-trees, alt-VH) into `target` at `at_offset`
/// and leaves the free middle untouched. Caller is responsible for sizing
/// the underlying file (e.g. via `File::set_len`) so reads of the free area
/// return zeros.
///
/// Used by the defrag-clone backup path and the Mac CD-ROM builder so a
/// multi-hundred-MB blank target doesn't need that much contiguous RAM. Only
/// the front region (~2 MiB worst case) plus the 512-byte alt VH is held in
/// memory. `size_bytes` should be a whole multiple of `block_size`, otherwise
/// the alt VH lands past the volume's last allocation block.
pub fn write_blank_hfsplus_into<W: Write + Seek>(
    target: &mut W,
    at_offset: u64,
    size_bytes: u64,
    block_size: u32,
    name: &str,
    case_sensitive: bool,
) -> std::io::Result<()> {
    let (front, vh_bytes, _image_size) =
        build_blank_hfsplus_front(size_bytes, block_size, name, case_sensitive, 0, 0);
    target.seek(SeekFrom::Start(at_offset))?;
    target.write_all(&front)?;
    target.seek(SeekFrom::Start(at_offset + size_bytes - 1024))?;
    target.write_all(&vh_bytes)?;
    target.write_all(&[0u8; 512])?;
    Ok(())
}

/// Helper for `create_blank_hfsplus`: build a single-extent inline array.
fn extent_array(start: u32, count: u32) -> [ExtentDescriptor; 8] {
    let mut e = [ExtentDescriptor {
        start_block: 0,
        block_count: 0,
    }; 8];
    e[0] = ExtentDescriptor {
        start_block: start,
        block_count: count,
    };
    e
}

/// Stamp a B-tree header node into `node` (must be exactly `node_size`
/// bytes). Lays out three records — header(106), user-data(128), node
/// bitmap (rest) — and marks node 0 (header) and node 1 (leaf) as
/// allocated in the node bitmap.
pub(crate) fn write_blank_btree_header_node(
    node: &mut [u8],
    node_size: usize,
    leaf_records: u32,
    total_nodes: u32,
    free_nodes: u32,
    max_key_len: u16,
    key_compare_type: u8,
) {
    node.fill(0);
    node[8] = 1; // kind = header
    BigEndian::write_u16(&mut node[10..12], 3); // 3 records

    // Record 0: BTHeaderRec at offset 14 (106 bytes).
    //
    // An *empty* tree (no leaf records, e.g. a fresh extents-overflow or
    // attributes B-tree) is represented exactly as Apple's `newfs_hfs` does:
    // treeDepth = 0, rootNode = 0, firstLeafNode = lastLeafNode = 0, and no
    // leaf node allocated — only the header node is in use. A populated blank
    // (the catalog, with its root folder + thread records) has a single
    // root *leaf* at node 1. `fsck_hfs` rejects a depth-1 tree whose root is
    // an empty leaf ("Invalid node structure"), which is why the empty case
    // must collapse to depth 0. `btree_insert_full` bootstraps the first leaf
    // on the initial insert into a depth-0 tree.
    let empty = leaf_records == 0;
    let (depth, root_first_last): (u16, u32) = if empty { (0, 0) } else { (1, 1) };
    let hr = 14usize;
    BigEndian::write_u16(&mut node[hr..hr + 2], depth);
    BigEndian::write_u32(&mut node[hr + 2..hr + 6], root_first_last); // root
    BigEndian::write_u32(&mut node[hr + 6..hr + 10], leaf_records);
    BigEndian::write_u32(&mut node[hr + 10..hr + 14], root_first_last); // first leaf
    BigEndian::write_u32(&mut node[hr + 14..hr + 18], root_first_last); // last leaf
    BigEndian::write_u16(&mut node[hr + 18..hr + 20], node_size as u16);
    BigEndian::write_u16(&mut node[hr + 20..hr + 22], max_key_len);
    BigEndian::write_u32(&mut node[hr + 22..hr + 26], total_nodes);
    BigEndian::write_u32(&mut node[hr + 26..hr + 30], free_nodes);
    // BTHeaderRec offset 36 = btreeType (0=control); offset 37 = keyCompareType
    node[hr + 36] = 0; // kBTHFSTreeType
    node[hr + 37] = key_compare_type;
    // Offset 38 = attributes: Apple sets kBTBigKeysMask on every HFS+ tree and
    // kBTVariableIndexKeysMask on the catalog and attributes trees (not extents).
    let attributes = if max_key_len == 10 {
        hfs_common::KBT_BIG_KEYS_MASK
    } else {
        hfs_common::KBT_BIG_KEYS_MASK | hfs_common::KBT_VARIABLE_INDEX_KEYS_MASK
    };
    BigEndian::write_u32(&mut node[hr + 38..hr + 42], attributes);

    // Canonical TN1150 B-tree header node layout. The BTHeaderRec (record 0)
    // is *exactly* 106 bytes — Apple's `fsck_hfs` rejects any other length
    // ("Invalid BTH length"). So record 1 (the 128-byte reserved user-data
    // record) starts at 14 + 106 = 120, and record 2 (the node-allocation
    // bitmap) starts at 120 + 128 = 248, filling the node to the offset
    // table. The bitmap therefore addresses (node_size - 256) * 8 nodes,
    // which is exactly what `hfs_common::map_nodes_required` assumes — so the
    // header-vs-map-node boundary is consistent (see the discrepancy noted in
    // docs/todo_hfsplus_fork_growth.md §5, resolved by using 248 here).
    let user_off: u16 = 120;
    let bitmap_off: u16 = 248;
    let free_off: u16 = (node_size as u16).saturating_sub(8); // fills to offset table

    let ot_end = node_size;
    BigEndian::write_u16(&mut node[ot_end - 2..ot_end], 14); // record 0
    BigEndian::write_u16(&mut node[ot_end - 4..ot_end - 2], user_off);
    BigEndian::write_u16(&mut node[ot_end - 6..ot_end - 4], bitmap_off);
    BigEndian::write_u16(&mut node[ot_end - 8..ot_end - 6], free_off);

    // Mark allocated nodes in the bitmap: node 0 (header) always; node 1
    // (the root leaf) only for a populated tree. An empty tree's node 1 is
    // free and zero-filled, matching Apple.
    node[bitmap_off as usize] = if empty { 0b10000000 } else { 0b11000000 };
}

/// Write an empty leaf node (kind=-1, height=1, 0 records). Only used by test
/// fixtures now — the production blank/defrag builders represent an empty tree
/// as depth 0 with no leaf node (the first insert bootstraps the root leaf).
#[cfg(test)]
pub(crate) fn write_empty_leaf_node(node: &mut [u8]) {
    node.fill(0);
    node[8] = 0xFF; // kind = -1
    node[9] = 1; // height
    BigEndian::write_u16(&mut node[10..12], 0); // 0 records
    let n = node.len();
    BigEndian::write_u16(&mut node[n - 2..n], 14); // free-space offset
}

/// Write the catalog leaf node containing the root folder record (key =
/// `(parent=1, name=<volume>)`) and the root thread record (key =
/// `(parent=2, name="")`, data = recordType=3 + parentID=1 + name=volume).
fn write_root_catalog_leaf(node: &mut [u8], name_utf16: &[u16]) {
    node.fill(0);
    let n = node.len();
    node[8] = 0xFF; // kind = -1 leaf
    node[9] = 1; // height
    BigEndian::write_u16(&mut node[10..12], 2); // 2 records

    let now = hfs_common::hfs_now();

    // ---- Record 0: root folder record ----
    // Key: key_len(2) + parent_id(4) + name_len(2) + name(UTF-16BE)
    let r0_off = 14usize;
    let key_body = 4 + 2 + name_utf16.len() * 2;
    BigEndian::write_u16(&mut node[r0_off..r0_off + 2], key_body as u16);
    BigEndian::write_u32(&mut node[r0_off + 2..r0_off + 6], 1); // parent = 1
    BigEndian::write_u16(&mut node[r0_off + 6..r0_off + 8], name_utf16.len() as u16);
    for (i, &u) in name_utf16.iter().enumerate() {
        BigEndian::write_u16(&mut node[r0_off + 8 + i * 2..r0_off + 10 + i * 2], u);
    }
    let mut r0_data = r0_off + 2 + key_body;
    if !r0_data.is_multiple_of(2) {
        r0_data += 1;
    }
    BigEndian::write_i16(&mut node[r0_data..r0_data + 2], CATALOG_FOLDER);
    // valence = 0 at +4, folderID = 2 at +8, then dates.
    BigEndian::write_u32(&mut node[r0_data + 8..r0_data + 12], 2);
    BigEndian::write_u32(&mut node[r0_data + 12..r0_data + 16], now);
    BigEndian::write_u32(&mut node[r0_data + 16..r0_data + 20], now);
    BigEndian::write_u32(&mut node[r0_data + 20..r0_data + 24], now);
    BigEndian::write_u32(&mut node[r0_data + 24..r0_data + 28], now);
    let r0_end = r0_data + 88; // folder record is 88 bytes total

    // ---- Record 1: root thread record ----
    // Key: key_len(2) + parent_id(4=2) + name_len(2=0)
    let r1_off = r0_end;
    BigEndian::write_u16(&mut node[r1_off..r1_off + 2], 6); // key_len
    BigEndian::write_u32(&mut node[r1_off + 2..r1_off + 6], 2); // parent = 2 (root CNID)
    BigEndian::write_u16(&mut node[r1_off + 6..r1_off + 8], 0); // name_len = 0
    let mut r1_data = r1_off + 2 + 6;
    if !r1_data.is_multiple_of(2) {
        r1_data += 1;
    }
    // Thread data: type(2)=3, reserved(2)=0, parentID(4)=1, name_len(2),
    // name(UTF-16BE).
    BigEndian::write_i16(&mut node[r1_data..r1_data + 2], 3); // folder thread
    BigEndian::write_u32(&mut node[r1_data + 4..r1_data + 8], 1);
    BigEndian::write_u16(
        &mut node[r1_data + 8..r1_data + 10],
        name_utf16.len() as u16,
    );
    for (i, &u) in name_utf16.iter().enumerate() {
        BigEndian::write_u16(&mut node[r1_data + 10 + i * 2..r1_data + 12 + i * 2], u);
    }
    let r1_end = r1_data + 10 + name_utf16.len() * 2;

    // Offset table at the end of the node.
    BigEndian::write_u16(&mut node[n - 2..n], 14); // record 0 offset
    BigEndian::write_u16(&mut node[n - 4..n - 2], r1_off as u16);
    BigEndian::write_u16(&mut node[n - 6..n - 4], r1_end as u16); // free-space offset
}

// --- Resize and validation ---

/// Resize an HFS+ filesystem in place.
pub fn resize_hfsplus_in_place(
    device: &mut (impl Read + Write + Seek),
    partition_offset: u64,
    new_size_bytes: u64,
    log: &mut impl FnMut(&str),
) -> anyhow::Result<()> {
    // Read volume header
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    let mut vh_buf = [0u8; 512];
    device.read_exact(&mut vh_buf)?;

    let sig = BigEndian::read_u16(&vh_buf[0..2]);
    if sig != HFS_PLUS_SIGNATURE && sig != HFSX_SIGNATURE {
        log("HFS+ resize: not an HFS+ volume, skipping");
        return Ok(());
    }
    let mut vh = HfsPlusVolumeHeader::parse(&vh_buf)?;
    let bs = vh.block_size;
    let old_total = vh.total_blocks;
    let new_total = (new_size_bytes / bs as u64) as u32;
    if new_total < 8 {
        anyhow::bail!("HFS+ resize: {new_size_bytes} bytes is too small for a volume");
    }

    // The allocation file is one extent on every volume Apple or we format.
    let af = &vh.allocation_file;
    if af.extents[0].block_count == 0 || af.extents[1].block_count != 0 {
        anyhow::bail!("HFS+ resize: the allocation file is not a single extent; refusing");
    }
    let (mut af_start, mut af_blocks) = (af.extents[0].start_block, af.extents[0].block_count);
    let mut bitmap = vec![0u8; af_blocks as usize * bs as usize];
    device.seek(SeekFrom::Start(
        partition_offset + af_start as u64 * bs as u64,
    ))?;
    device.read_exact(&mut bitmap)?;

    let old_tail = alt_vh_blocks(old_total, bs);
    let new_tail = alt_vh_blocks(new_total, bs);
    if new_total < old_total {
        // A count says nothing about position: the last used block must fit.
        let highest = find_last_set_bit(&bitmap, old_tail.start).map_or(0, |b| b + 1);
        if highest > new_tail.start {
            anyhow::bail!(
                "HFS+ resize: new size {} blocks ends before the last allocated block ({})",
                new_total,
                highest
            );
        }
    }

    // The alternate header's blocks move with the end of the volume (R-056);
    // bits past the old end were padding and the grown area starts free.
    let cap_bits = (bitmap.len() as u64 * 8).min(u32::MAX as u64) as u32;
    for b in old_tail.start..old_total.min(cap_bits) {
        bitmap_clear_bit_be(&mut bitmap, b);
    }
    for b in old_total..new_total.min(cap_bits) {
        bitmap_clear_bit_be(&mut bitmap, b);
    }

    // A bigger volume may need a bigger allocation file: extend it in place
    // when the blocks after it are free, else move it to a free run.
    let needed_blocks = (new_total as u64).div_ceil(8).div_ceil(bs as u64) as u32;
    if needed_blocks > af_blocks {
        let mut grown = bitmap.clone();
        grown.resize(needed_blocks as usize * bs as usize, 0);
        let usable = new_tail.start;
        let extend_ok = (af_start + af_blocks..af_start + needed_blocks)
            .all(|b| b < usable && !bitmap_test_bit_be(&grown, b));
        let new_start = if extend_ok {
            af_start
        } else {
            hfs_common::bitmap_find_clear_run_be(&grown, usable, needed_blocks).ok_or_else(
                || {
                    anyhow::anyhow!(
                        "HFS+ resize: no free run of {needed_blocks} blocks for the allocation file"
                    )
                },
            )?
        };
        if new_start != af_start {
            for b in af_start..af_start + af_blocks {
                bitmap_clear_bit_be(&mut grown, b);
            }
        }
        for b in new_start..new_start + needed_blocks {
            bitmap_set_bit_be(&mut grown, b);
        }
        log(&format!(
            "HFS+ resize: allocation file grows from {af_blocks} to {needed_blocks} blocks at \
             block {new_start}"
        ));
        bitmap = grown;
        af_start = new_start;
        af_blocks = needed_blocks;
        vh.allocation_file.extents[0] = ExtentDescriptor {
            start_block: af_start,
            block_count: af_blocks,
        };
        vh.allocation_file.total_blocks = af_blocks;
        vh.allocation_file.logical_size = af_blocks as u64 * bs as u64;
    }
    for b in new_tail.clone() {
        bitmap_set_bit_be(&mut bitmap, b);
    }
    let cap_bits = (bitmap.len() as u64 * 8).min(u32::MAX as u64) as u32;
    for b in new_total..cap_bits {
        bitmap_clear_bit_be(&mut bitmap, b);
    }

    let used = count_used_blocks(&bitmap, new_total);
    vh.total_blocks = new_total;
    vh.free_blocks = new_total - used;
    if vh.next_allocation >= new_tail.start {
        vh.next_allocation = 0;
    }
    log(&format!(
        "HFS+ resize: {} -> {} blocks ({} free)",
        old_total, new_total, vh.free_blocks
    ));

    device.seek(SeekFrom::Start(
        partition_offset + af_start as u64 * bs as u64,
    ))?;
    device.write_all(&bitmap)?;
    let out = vh.serialize();
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    device.write_all(&out)?;
    if new_size_bytes > 1024 {
        device.seek(SeekFrom::Start(partition_offset + new_size_bytes - 1024))?;
        device.write_all(&out)?;
    }
    device.flush()?;
    Ok(())
}

/// Mirror the volume header 1024 bytes before the partition end when the
/// volume is smaller than its partition, where Mac OS looks for it (R-057).
/// Returns whether a copy was written.
pub fn mirror_alternate_volume_header(
    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 vh_buf = [0u8; 512];
    device.read_exact(&mut vh_buf)?;
    let sig = BigEndian::read_u16(&vh_buf[0..2]);
    if sig != HFS_PLUS_SIGNATURE && sig != HFSX_SIGNATURE {
        return Ok(false);
    }
    let block_size = BigEndian::read_u32(&vh_buf[40..44]) as u64;
    let total_blocks = BigEndian::read_u32(&vh_buf[44..48]) as u64;
    let volume_len = total_blocks * block_size;
    if partition_len < 2048 || volume_len >= partition_len {
        return Ok(false);
    }
    device.seek(SeekFrom::Start(partition_offset + partition_len - 1024))?;
    device.write_all(&vh_buf)?;
    device.flush()?;
    log(&format!(
        "HFS+ volume of {volume_len} bytes in a {partition_len}-byte partition: alternate \
         volume header mirrored at the partition end"
    ));
    Ok(true)
}

/// The blocks that hold a volume's alternate volume header, its last 1024
/// bytes: one block at 1024 bytes and up, two at 512.
fn alt_vh_blocks(total_blocks: u32, block_size: u32) -> std::ops::Range<u32> {
    if total_blocks == 0 {
        return 0..0;
    }
    let bytes = total_blocks as u64 * block_size as u64;
    let start = (bytes.saturating_sub(1024) / block_size as u64) as u32;
    start..total_blocks
}

/// Set bits among the first `total_blocks` of the allocation bitmap.
fn count_used_blocks(bitmap: &[u8], total_blocks: u32) -> u32 {
    let full = (total_blocks / 8) as usize;
    let mut used: u32 = bitmap[..full.min(bitmap.len())]
        .iter()
        .map(|b| b.count_ones())
        .sum();
    let keep = total_blocks % 8;
    if keep > 0 {
        if let Some(&last) = bitmap.get(full) {
            let mask = 0xFFu8 << (8 - keep);
            used += (last & mask).count_ones();
        }
    }
    used
}

/// Validate HFS+ filesystem integrity.
pub fn validate_hfsplus_integrity(
    device: &mut (impl Read + Seek),
    partition_offset: u64,
    log: &mut impl FnMut(&str),
) -> anyhow::Result<()> {
    device.seek(SeekFrom::Start(partition_offset + 1024))?;
    let mut vh_buf = [0u8; 512];
    device.read_exact(&mut vh_buf)?;

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

    let block_size = BigEndian::read_u32(&vh_buf[40..44]);
    let total_blocks = BigEndian::read_u32(&vh_buf[44..48]);

    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(())
}

/// Resolve the actual HFS filesystem variant for an "Apple_HFS" APM partition.
///
/// Returns `(fs_type, hfsplus_offset)` where `fs_type` is `"hfs"`, `"hfsplus"`,
/// or `"unknown"`, and `hfsplus_offset` is the partition_offset to pass to
/// `HfsPlusFilesystem::open` (accounts for the embedded volume's position).
///
/// Three cases are handled:
/// - Native HFS+ (0x482B/0x4858 at partition_offset+1024): `hfsplus_offset == partition_offset`.
/// - Embedded HFS+ (HFS wrapper with 0x4244 MDB, drEmbedSigWord == 0x482B): `hfsplus_offset`
///   is calculated from the MDB's drAlBlSt/drAlBlkSiz/drEmbedExtent fields.
/// - Pure HFS (0x4244, no embedded HFS+): returns `"hfs"`.
pub fn resolve_apple_hfs<R: Read + Seek>(
    reader: &mut R,
    partition_offset: u64,
) -> (&'static str, u64) {
    // The HFS MDB / HFS+ volume header sits at partition_offset + 1024 (sector-aligned).
    // Read 512 bytes (one sector) — all required fields are within the first 512 bytes
    // of the MDB (largest field needed is drEmbedExtent.startBlock at MDB offset 127).
    // This keeps the read sector-aligned for raw character device compatibility.
    if reader
        .seek(SeekFrom::Start(partition_offset + 1024))
        .is_err()
    {
        return ("unknown", partition_offset);
    }
    let mut buf = [0u8; 512];
    if reader.read_exact(&mut buf).is_err() {
        return ("unknown", partition_offset);
    }
    let sig = u16::from_be_bytes([buf[0], buf[1]]);
    match sig {
        0x4244 => {
            // HFS MDB — check for embedded HFS+ (drEmbedSigWord at MDB offset 124)
            let embedded_sig = u16::from_be_bytes([buf[124], buf[125]]);
            if embedded_sig == 0x482B {
                // Embedded HFS+: calculate the embedded volume's starting offset.
                // drAlBlkSiz (allocation block size, bytes) at MDB offset 20 (u32 BE).
                // drAlBlSt (first alloc block in 512-byte sectors) at MDB offset 28 (u16 BE).
                // drEmbedExtent.startBlock at MDB offset 126 (u16 BE).
                let block_size = u32::from_be_bytes([buf[20], buf[21], buf[22], buf[23]]) as u64;
                let first_alloc_block = u16::from_be_bytes([buf[28], buf[29]]) as u64;
                let embedded_start = u16::from_be_bytes([buf[126], buf[127]]) as u64;
                // HFS+ volume starts at: partition_offset + drAlBlSt*512 + startBlock*drAlBlkSiz
                let hfsplus_offset =
                    partition_offset + first_alloc_block * 512 + embedded_start * block_size;
                ("hfsplus", hfsplus_offset)
            } else {
                ("hfs", partition_offset)
            }
        }
        // Native HFS+ or HFSX — volume header is directly at partition_offset+1024
        0x482B | 0x4858 => ("hfsplus", partition_offset),
        _ => ("unknown", partition_offset),
    }
}

#[cfg(test)]
#[allow(clippy::identity_op)] // `1usize * block_size` keeps offset rows aligned
mod tests {
    use super::*;

    /// 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() {
        use std::io::Cursor;
        let img = create_blank_hfsplus(64 * 1024 * 1024, 4096, "Churn", false);
        let mut fs = HfsPlusFilesystem::open(Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();
        let root = fs.root().unwrap();
        let clean = |fs: &mut HfsPlusFilesystem<Cursor<Vec<u8>>>, stage: &str| {
            fs.sync_metadata().unwrap();
            let r = fs.fsck().expect("hfsplus has fsck").unwrap();
            assert!(r.errors.is_empty(), "{stage}: {:?}", r.errors);
        };
        let put = |fs: &mut HfsPlusFilesystem<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.vh.free_blocks;
        let trees0 = fs.vh.catalog_file.total_blocks + fs.vh.extents_file.total_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();
        }
        // The B-trees keep what they grew by; every other block comes back.
        let trees = fs.vh.catalog_file.total_blocks + fs.vh.extents_file.total_blocks;
        assert_eq!(
            fs.vh.free_blocks + (trees - trees0),
            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"]);
    }

    /// Apple stamps kBTBigKeysMask on every HFS+ tree and adds
    /// kBTVariableIndexKeysMask on the catalog and attributes trees; so do we.
    #[test]
    fn blank_btree_headers_carry_apples_attribute_bits() {
        let img = create_blank_hfsplus(16 * 1024 * 1024, 4096, "Attrs", false);
        let vh = &img[1024..1536];
        let block_size = BigEndian::read_u32(&vh[0x28..0x2c]) as usize;
        // BTHeaderRec.attributes sits at node offset 14 + 38; a fork's first
        // extent start is 16 bytes into its HFSPlusForkData (extents file at
        // 0xC0, catalog at 0x110 in the volume header).
        let attrs = |fork: usize| {
            let start = BigEndian::read_u32(&vh[fork + 0x10..fork + 0x14]) as usize;
            BigEndian::read_u32(&img[start * block_size + 52..start * block_size + 56])
        };
        assert_eq!(attrs(0xC0), hfs_common::KBT_BIG_KEYS_MASK, "extents");
        let variable = hfs_common::KBT_BIG_KEYS_MASK | hfs_common::KBT_VARIABLE_INDEX_KEYS_MASK;
        assert_eq!(attrs(0x110), variable, "catalog");
    }

    #[test]
    fn test_volume_header_parse() {
        let mut data = [0u8; 512];
        BigEndian::write_u16(&mut data[0..2], HFS_PLUS_SIGNATURE);
        BigEndian::write_u16(&mut data[2..4], 4); // version
        BigEndian::write_u32(&mut data[40..44], 4096); // block_size
        BigEndian::write_u32(&mut data[44..48], 100000); // total_blocks
        BigEndian::write_u32(&mut data[48..52], 30000); // free_blocks

        let vh = HfsPlusVolumeHeader::parse(&data).unwrap();
        assert_eq!(vh.signature, HFS_PLUS_SIGNATURE);
        assert_eq!(vh.block_size, 4096);
        assert_eq!(vh.total_blocks, 100000);
        assert_eq!(vh.free_blocks, 30000);
        assert!(!vh.is_hfsx());
    }

    #[test]
    fn test_hfsx_signature() {
        let mut data = [0u8; 512];
        BigEndian::write_u16(&mut data[0..2], HFSX_SIGNATURE);
        BigEndian::write_u32(&mut data[40..44], 4096);
        BigEndian::write_u32(&mut data[44..48], 100000);
        BigEndian::write_u32(&mut data[48..52], 30000);

        let vh = HfsPlusVolumeHeader::parse(&data).unwrap();
        assert!(vh.is_hfsx());
    }

    #[test]
    fn test_decode_utf16be() {
        // "Hello" in UTF-16BE
        let data = [0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F];
        assert_eq!(decode_utf16be(&data), "Hello");
    }

    #[test]
    fn test_decode_utf16be_with_non_ascii() {
        // "Ä" (U+00C4) in UTF-16BE
        let data = [0x00, 0xC4];
        assert_eq!(decode_utf16be(&data), "Ä");
    }

    #[test]
    fn test_extent_descriptor() {
        let mut data = [0u8; 8];
        BigEndian::write_u32(&mut data[0..4], 100);
        BigEndian::write_u32(&mut data[4..8], 50);

        let ext = ExtentDescriptor::parse(&data);
        assert_eq!(ext.start_block, 100);
        assert_eq!(ext.block_count, 50);
        assert!(!ext.is_empty());
    }

    #[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 empty = [0u8; 2];
        assert_eq!(find_last_set_bit(&empty, 16), None);
    }

    #[test]
    fn test_find_last_set_bit_dense_byte() {
        // Regression: when the highest non-zero byte has multiple set bits,
        // the result must be the highest global index in that byte, not the
        // lowest. 0b11111100 has bits 0..=5 set (MSB-first), so the answer
        // is 5, not 0.
        assert_eq!(find_last_set_bit(&[0b11111100], 8), Some(5));
        assert_eq!(find_last_set_bit(&[0b11111111], 8), Some(7));
        assert_eq!(find_last_set_bit(&[0b00000001], 8), Some(7));
        assert_eq!(find_last_set_bit(&[0b10000000], 8), Some(0));
        // Multi-byte: byte 0 dense, byte 1 zero — answer is in byte 0.
        assert_eq!(find_last_set_bit(&[0b11111100, 0b00000000], 16), Some(5));
        // Bound clipping: 0b11111111 with max_bits=4 → only bits 0..=3 are
        // valid; the highest-valid one is 3.
        assert_eq!(find_last_set_bit(&[0b11111111], 4), Some(3));
    }

    #[test]
    fn test_volume_header_serialize_roundtrip() {
        let mut data = [0u8; 512];
        BigEndian::write_u16(&mut data[0..2], HFS_PLUS_SIGNATURE);
        BigEndian::write_u16(&mut data[2..4], 4);
        BigEndian::write_u32(&mut data[40..44], 4096);
        BigEndian::write_u32(&mut data[44..48], 100);
        BigEndian::write_u32(&mut data[48..52], 50);
        BigEndian::write_u32(&mut data[64..68], 10); // next_catalog_id
        BigEndian::write_u32(&mut data[80..84], 42); // finder_info[0]

        let vh = HfsPlusVolumeHeader::parse(&data).unwrap();
        assert_eq!(vh.next_catalog_id, 10);
        assert_eq!(vh.finder_info[0], 42);

        let serialized = vh.serialize();
        let vh2 = HfsPlusVolumeHeader::parse(&serialized).unwrap();
        assert_eq!(vh2.block_size, 4096);
        assert_eq!(vh2.total_blocks, 100);
        assert_eq!(vh2.free_blocks, 50);
        assert_eq!(vh2.next_catalog_id, 10);
        assert_eq!(vh2.finder_info[0], 42);
    }

    #[test]
    fn test_fork_data_serialize_roundtrip() {
        let fork = ForkData {
            logical_size: 12345,
            clump_size: 0,
            total_blocks: 3,
            extents: [
                ExtentDescriptor {
                    start_block: 10,
                    block_count: 3,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
                ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                },
            ],
        };
        let mut buf = [0u8; 80];
        fork.serialize(&mut buf);
        let fork2 = ForkData::parse(&buf);
        assert_eq!(fork2.logical_size, 12345);
        assert_eq!(fork2.total_blocks, 3);
        assert_eq!(fork2.extents[0].start_block, 10);
        assert_eq!(fork2.extents[0].block_count, 3);
    }

    /// Create a minimal valid in-memory HFS+ image for testing.
    /// Layout: 256 blocks × 4096 bytes = 1 MB
    /// - Block 0: unused (VH at byte 1024 within this block)
    /// - Block 1: allocation bitmap
    /// - Block 2-5: catalog B-tree (4 blocks = 16 KB = 4 nodes of 4096 bytes)
    ///   - Node 0: header node
    ///   - Node 1: leaf node with root folder record + thread
    ///   - Nodes 2-3: free
    /// - Blocks 6+: free for user data
    fn make_editable_hfsplus_image() -> Vec<u8> {
        let block_size = 4096u32;
        let total_blocks = 256u32;
        let image_size = total_blocks as usize * block_size as usize; // 1 MB
        let mut img = vec![0u8; image_size];

        // Allocation bitmap: blocks 0-5 allocated (VH area + bitmap + catalog)
        let bitmap_block = 1u32;
        let catalog_start_block = 2u32;
        let catalog_blocks = 4u32;
        let alloc_blocks = 1 + 1 + catalog_blocks; // VH + bitmap + catalog = 6 blocks
        let bitmap_data = &mut img[bitmap_block as usize * block_size as usize
            ..(bitmap_block + 1) as usize * block_size as usize];
        // Set bits 0-5 (MSB-first): byte 0 = 0b11111100
        bitmap_data[0] = 0b11111100;

        // Build catalog B-tree in blocks 2-5 (4 nodes × 4096)
        let node_size = 4096usize;
        let catalog_offset = catalog_start_block as usize * block_size as usize;
        let catalog_size = catalog_blocks as usize * block_size as usize;

        // Node 0: Header node
        let hdr_off = catalog_offset;
        // Node descriptor: next=0, prev=0, kind=1(header), height=0, numRecords=3
        img[hdr_off + 8] = 1; // kind = header
        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 (folder + thread)
        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], 516); // max_key_len
        BigEndian::write_u32(&mut img[hr + 22..hr + 26], 4); // total_nodes = 4
        BigEndian::write_u32(&mut img[hr + 26..hr + 30], 2); // free_nodes = 2

        // Record offsets for header node (3 records + free space offset)
        // Record 0: header record at offset 14
        // Record 1: user data record (128 bytes at offset 14+128=142)
        // Record 2: bitmap record (256 bytes at offset 142+128=270)
        // Free space offset at end
        let ot = hdr_off + node_size; // offset table at end of node
        BigEndian::write_u16(&mut img[ot - 2..ot], 14); // record 0 offset
        BigEndian::write_u16(&mut img[ot - 4..ot - 2], 142); // record 1 offset
        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 offset

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

        // Node 1: Leaf node with root folder record + thread record
        let leaf_off = catalog_offset + node_size;
        // Node descriptor: next=0, prev=0, kind=-1(leaf), height=1, numRecords=2
        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(2) + parent_id(4, =1) + name_len(2, =0)  — root folder's parent is CNID 1
        let r0_off = leaf_off + 14;
        BigEndian::write_u16(&mut img[r0_off..r0_off + 2], 6); // key_len = 6
        BigEndian::write_u32(&mut img[r0_off + 2..r0_off + 6], 1); // parent_id = 1 (root parent)
        BigEndian::write_u16(&mut img[r0_off + 6..r0_off + 8], 0); // name_len = 0
                                                                   // Record data starts after key (at offset 8, even-aligned)
        let r0_data = r0_off + 8;
        BigEndian::write_i16(&mut img[r0_data..r0_data + 2], CATALOG_FOLDER); // type = folder
        BigEndian::write_u32(&mut img[r0_data + 8..r0_data + 12], 2); // folderID = 2
                                                                      // Folder record is 88 bytes total

        // Record 1: Thread record for root folder (CNID 2)
        // Thread key: parent_id = CNID = 2, name = empty
        let r1_off = r0_data + 88; // after folder record
        BigEndian::write_u16(&mut img[r1_off..r1_off + 2], 6); // key_len = 6
        BigEndian::write_u32(&mut img[r1_off + 2..r1_off + 6], 2); // parent_id = 2 (CNID)
        BigEndian::write_u16(&mut img[r1_off + 6..r1_off + 8], 0); // name_len = 0
                                                                   // Thread record data
        let r1_data = r1_off + 8;
        BigEndian::write_i16(&mut img[r1_data..r1_data + 2], 3); // type = folder thread
        BigEndian::write_u32(&mut img[r1_data + 4..r1_data + 8], 1); // parentID = 1
        BigEndian::write_u16(&mut img[r1_data + 8..r1_data + 10], 0); // name_len = 0
                                                                      // Thread record is variable length, but at minimum 10 bytes

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

        // Volume Header at byte 1024
        let vh = HfsPlusVolumeHeader {
            signature: HFS_PLUS_SIGNATURE,
            version: 4,
            attributes: 0,
            last_mounted_version: 0,
            journal_info_block: 0,
            create_date: hfs_common::hfs_now(),
            modify_date: hfs_common::hfs_now(),
            backup_date: 0,
            checked_date: 0,
            file_count: 0,
            folder_count: 0, // Apple TN1150: excludes root
            block_size,
            total_blocks,
            free_blocks: total_blocks - alloc_blocks,
            next_allocation: alloc_blocks,
            rsrc_clump_size: 0,
            data_clump_size: 0,
            next_catalog_id: 16, // next available CNID
            write_count: 0,
            encodings_bitmap: 0,
            finder_info: [0u32; 8],
            allocation_file: ForkData {
                logical_size: block_size as u64,
                clump_size: 0,
                total_blocks: 1,
                extents: {
                    let mut e = [ExtentDescriptor {
                        start_block: 0,
                        block_count: 0,
                    }; 8];
                    e[0] = ExtentDescriptor {
                        start_block: bitmap_block,
                        block_count: 1,
                    };
                    e
                },
            },
            extents_file: ForkData::empty(),
            catalog_file: ForkData {
                logical_size: catalog_size as u64,
                clump_size: 0,
                total_blocks: catalog_blocks,
                extents: {
                    let mut e = [ExtentDescriptor {
                        start_block: 0,
                        block_count: 0,
                    }; 8];
                    e[0] = ExtentDescriptor {
                        start_block: catalog_start_block,
                        block_count: catalog_blocks,
                    };
                    e
                },
            },
            attributes_file: ForkData::empty(),
            startup_file: ForkData::empty(),
        };

        let vh_bytes = vh.serialize();
        img[1024..1024 + 512].copy_from_slice(&vh_bytes);

        // Backup VH at last 1024 bytes
        let backup_pos = image_size - 1024;
        img[backup_pos..backup_pos + 512].copy_from_slice(&vh_bytes);

        img
    }

    /// Build an editable HFS+ image that also carries a 4-node empty
    /// extents-overflow B-tree at blocks 6..9. Used by tests that exercise
    /// fragmented files needing more than 8 extents (Step 7).
    ///
    /// Layout (4 KiB blocks, 256 total = 1 MiB image):
    /// - Block 0: VH/boot region
    /// - Block 1: allocation bitmap
    /// - Blocks 2..5: catalog B-tree (4 nodes)
    /// - Blocks 6..9: extents-overflow B-tree (4 nodes — header + empty leaf
    ///   + 2 free)
    /// - Blocks 10..255: free user data area
    fn make_editable_hfsplus_image_with_extents_btree() -> Vec<u8> {
        // Start from the standard editable image, then carve in an
        // extents-overflow B-tree.
        let mut img = make_editable_hfsplus_image();
        let block_size = 4096u32;
        let node_size = 4096usize;
        let extents_start_block = 6u32;
        let extents_blocks = 4u32;

        // Mark blocks 6..9 allocated in the bitmap (byte 0 was 0b11111100 →
        // blocks 0..=5 allocated; flip bits 1..=3 of byte 1 to allocate
        // blocks 6..=9, leaving bits 4..=7 free for user data continuation).
        let bitmap_off = 1usize * block_size as usize;
        img[bitmap_off] = 0xFF; // blocks 0..=7 allocated
        img[bitmap_off + 1] = 0b11000000; // blocks 8..=9 allocated

        // --- Header node (block 6, node 0) ---
        let hdr_off = extents_start_block as usize * block_size as usize;
        img[hdr_off + 8] = 1; // kind = header
        BigEndian::write_u16(&mut img[hdr_off + 10..hdr_off + 12], 3); // 3 records

        // B-tree header record 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], 0); // leaf_records = 0
        BigEndian::write_u32(&mut img[hr + 10..hr + 14], 1); // first_leaf = 1
        BigEndian::write_u32(&mut img[hr + 14..hr + 18], 1); // last_leaf = 1
        BigEndian::write_u16(&mut img[hr + 18..hr + 20], node_size as u16);
        BigEndian::write_u16(&mut img[hr + 20..hr + 22], 10); // max_key_len
        BigEndian::write_u32(&mut img[hr + 22..hr + 26], 4); // total_nodes
        BigEndian::write_u32(&mut img[hr + 26..hr + 30], 2); // free_nodes (2,3)

        // Offset table at end of node 0: header(14), user(142), bitmap(270),
        // free(526) — same shape as the catalog header node.
        let ot = hdr_off + node_size;
        BigEndian::write_u16(&mut img[ot - 2..ot], 14);
        BigEndian::write_u16(&mut img[ot - 4..ot - 2], 142);
        BigEndian::write_u16(&mut img[ot - 6..ot - 4], 270);
        BigEndian::write_u16(&mut img[ot - 8..ot - 6], 526);

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

        // --- Empty leaf node (block 7, node 1) ---
        let leaf_off = hdr_off + 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], 0); // 0 records

        // Offset table: just the free-space offset at byte 14 (start of
        // record area).
        let lot = leaf_off + node_size;
        BigEndian::write_u16(&mut img[lot - 2..lot], 14);

        // Patch the volume header: point extents_file at blocks 6..9 with
        // a 16 KiB logical size, and decrement free_blocks by 4.
        // VH lives at offset 1024; offset 4..8 is `attributes`, but
        // extents_file fork lives at VH bytes 192..272.
        // Easier path: re-parse the VH, patch the fields, re-serialize.
        let mut vh = HfsPlusVolumeHeader::parse(&img[1024..1536]).expect("parse seed VH");
        vh.extents_file = ForkData {
            logical_size: (extents_blocks as u64) * (block_size as u64),
            clump_size: 0,
            total_blocks: extents_blocks,
            extents: {
                let mut e = [ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                }; 8];
                e[0] = ExtentDescriptor {
                    start_block: extents_start_block,
                    block_count: extents_blocks,
                };
                e
            },
        };
        vh.free_blocks -= extents_blocks;
        vh.next_allocation = 10;
        let vh_bytes = vh.serialize();
        img[1024..1536].copy_from_slice(&vh_bytes);
        let alt = img.len() - 1024;
        img[alt..alt + 512].copy_from_slice(&vh_bytes);
        img
    }

    /// Build an editable HFS+ image whose attributes B-tree carries one inline
    /// `com.apple.FinderInfo` record for `cnid` with `value` as the payload.
    /// Used by the Step 12 round-trip test.
    ///
    /// Layout (4 KiB blocks, 256 total = 1 MiB image):
    /// - Block 0: VH/boot region
    /// - Block 1: allocation bitmap
    /// - Blocks 2-5: catalog B-tree
    /// - Blocks 6-7: attributes B-tree (header + leaf)
    /// - Blocks 8..255: free
    fn make_editable_hfsplus_image_with_inline_xattr(cnid: u32, value: &[u8]) -> Vec<u8> {
        let mut img = make_editable_hfsplus_image();
        let block_size = 4096u32;
        let node_size = 4096usize;
        let attr_start_block = 6u32;
        let attr_blocks = 2u32;

        // Mark blocks 6 and 7 allocated. Seed image had byte 0 = 0b11111100
        // (blocks 0..=5); set bits 6..=7 of byte 0.
        let bitmap_off = 1usize * block_size as usize;
        img[bitmap_off] = 0xFF; // blocks 0..=7 allocated

        // --- Header node (block 6, node 0) ---
        let hdr_off = attr_start_block as usize * block_size as usize;
        img[hdr_off + 8] = 1; // kind = header
        BigEndian::write_u16(&mut img[hdr_off + 10..hdr_off + 12], 3);

        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], 1); // leaf_records = 1
        BigEndian::write_u32(&mut img[hr + 10..hr + 14], 1); // first_leaf = 1
        BigEndian::write_u32(&mut img[hr + 14..hr + 18], 1); // last_leaf = 1
        BigEndian::write_u16(&mut img[hr + 18..hr + 20], node_size as u16);
        BigEndian::write_u16(&mut img[hr + 20..hr + 22], 512); // max_key_len
        BigEndian::write_u32(&mut img[hr + 22..hr + 26], attr_blocks); // total_nodes = 2

        // Offset table for header node (header(14) / user(142) / bitmap(270) /
        // free(526) — same shape as the catalog header node).
        let ot = hdr_off + node_size;
        BigEndian::write_u16(&mut img[ot - 2..ot], 14);
        BigEndian::write_u16(&mut img[ot - 4..ot - 2], 142);
        BigEndian::write_u16(&mut img[ot - 6..ot - 4], 270);
        BigEndian::write_u16(&mut img[ot - 8..ot - 6], 526);

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

        // --- Leaf node (block 7, node 1) carrying one inline xattr record ---
        let leaf_off = hdr_off + 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], 1); // 1 record

        // Build the record: key + record-data.
        // Key body: pad(2) + fileID(4) + startBlock(4) + nameLen(2) + name UTF-16BE
        let name = "com.apple.FinderInfo";
        let name_utf16: Vec<u16> = name.encode_utf16().collect();
        let name_byte_len = name_utf16.len() * 2;
        let key_body_len = 12 + name_byte_len;
        // recordType(4) + reserved[2](8) + attrSize(4) + attrData(value.len())
        let data_section_len = 4 + 8 + 4 + value.len();
        let rec_total = 2 + key_body_len + data_section_len;

        let r0 = leaf_off + 14;
        BigEndian::write_u16(&mut img[r0..r0 + 2], key_body_len as u16);
        // pad already zero
        BigEndian::write_u32(&mut img[r0 + 4..r0 + 8], cnid);
        BigEndian::write_u32(&mut img[r0 + 8..r0 + 12], 0); // startBlock = 0
        BigEndian::write_u16(&mut img[r0 + 12..r0 + 14], name_utf16.len() as u16);
        for (i, ch) in name_utf16.iter().enumerate() {
            BigEndian::write_u16(&mut img[r0 + 14 + i * 2..r0 + 14 + i * 2 + 2], *ch);
        }
        let data_off = r0 + 2 + key_body_len;
        BigEndian::write_u32(&mut img[data_off..data_off + 4], HFSPLUS_ATTR_INLINE_DATA);
        // reserved[2] (8 bytes) already zero
        BigEndian::write_u32(&mut img[data_off + 12..data_off + 16], value.len() as u32);
        img[data_off + 16..data_off + 16 + value.len()].copy_from_slice(value);

        // Offset table: record 0 at 14, free-space at 14 + rec_total.
        let lot = leaf_off + node_size;
        BigEndian::write_u16(&mut img[lot - 2..lot], 14);
        BigEndian::write_u16(&mut img[lot - 4..lot - 2], (14 + rec_total) as u16);

        // Patch the volume header: point attributes_file at blocks 6..7,
        // decrement free_blocks by 2.
        let mut vh = HfsPlusVolumeHeader::parse(&img[1024..1536]).expect("parse seed VH");
        vh.attributes_file = ForkData {
            logical_size: (attr_blocks as u64) * (block_size as u64),
            clump_size: 0,
            total_blocks: attr_blocks,
            extents: {
                let mut e = [ExtentDescriptor {
                    start_block: 0,
                    block_count: 0,
                }; 8];
                e[0] = ExtentDescriptor {
                    start_block: attr_start_block,
                    block_count: attr_blocks,
                };
                e
            },
        };
        vh.free_blocks -= attr_blocks;
        vh.next_allocation = 8;
        let vh_bytes = vh.serialize();
        img[1024..1536].copy_from_slice(&vh_bytes);
        let alt = img.len() - 1024;
        img[alt..alt + 512].copy_from_slice(&vh_bytes);
        img
    }

    /// Build a minimal HFS+ image whose first leaf node holds the root folder
    /// record at `(parent=1, name=<volume_name>)` followed by N synthetic
    /// "child" records keyed by `(parent=2, name=childN)` — pushing the root
    /// thread record `(parent=2, name="")` into a later leaf. This mirrors
    /// the failure mode `probe_hfsplus_volume_label` had on real volumes
    /// where many top-level entries existed under the root.
    fn make_hfsplus_image_with_label(volume_name: &str, num_children: usize) -> Vec<u8> {
        let block_size = 4096u32;
        let total_blocks = 256u32;
        let image_size = total_blocks as usize * block_size as usize;
        let mut img = vec![0u8; image_size];

        // Layout: block 0 (VH region), block 1 (bitmap), blocks 2..=5 (catalog, 4 nodes).
        let bitmap_block = 1u32;
        let catalog_start_block = 2u32;
        let catalog_blocks = 4u32;
        // Bitmap byte 0 = 0b11111100 (blocks 0..=5 allocated).
        img[bitmap_block as usize * block_size as usize] = 0b11111100;

        let node_size = 4096usize;
        let catalog_offset = catalog_start_block as usize * block_size as usize;

        // Node 0: header.
        let hdr = catalog_offset;
        img[hdr + 8] = 1; // kind = header
        BigEndian::write_u16(&mut img[hdr + 10..hdr + 12], 3);
        let hr = hdr + 14;
        BigEndian::write_u16(&mut img[hr..hr + 2], 1); // depth
        BigEndian::write_u32(&mut img[hr + 2..hr + 6], 1); // root_node = 1 (first leaf)
        BigEndian::write_u32(&mut img[hr + 6..hr + 10], (1 + num_children + 1) as u32);
        BigEndian::write_u32(&mut img[hr + 10..hr + 14], 1); // first_leaf
                                                             // Probe only ever reads the first leaf, so last_leaf can be anything ≥ 1.
        BigEndian::write_u32(&mut img[hr + 14..hr + 18], 2);
        BigEndian::write_u16(&mut img[hr + 18..hr + 20], node_size as u16);
        BigEndian::write_u16(&mut img[hr + 20..hr + 22], 516);
        BigEndian::write_u32(&mut img[hr + 22..hr + 26], 4);
        BigEndian::write_u32(&mut img[hr + 26..hr + 30], 0);
        // Header offset table.
        let ot = hdr + node_size;
        BigEndian::write_u16(&mut img[ot - 2..ot], 14); // header rec
        BigEndian::write_u16(&mut img[ot - 4..ot - 2], 142); // user data
        BigEndian::write_u16(&mut img[ot - 6..ot - 4], 270); // bitmap
        BigEndian::write_u16(&mut img[ot - 8..ot - 6], 526); // free space

        // Node 1: first leaf. Record 0 = root folder record at
        // (parent=1, name=<volume_name>). The probe reads the volume name
        // from this record's key alone.
        let leaf = catalog_offset + node_size;
        img[leaf + 8] = 0xFF; // kind = -1 (leaf)
        img[leaf + 9] = 1; // height
        let total_recs = 1 + num_children;
        BigEndian::write_u16(&mut img[leaf + 10..leaf + 12], total_recs as u16);

        // Record 0: root folder record key `(parent=1, name_len=N, name)` +
        // a 88-byte folder data payload.
        let name_units: Vec<u16> = volume_name.encode_utf16().collect();
        let name_bytes = name_units.len() * 2;
        let r0 = leaf + 14;
        let key_len = 6 + name_bytes; // parent(4) + name_len(2) + name
        BigEndian::write_u16(&mut img[r0..r0 + 2], key_len as u16);
        BigEndian::write_u32(&mut img[r0 + 2..r0 + 6], 1); // parent = 1
        BigEndian::write_u16(&mut img[r0 + 6..r0 + 8], name_units.len() as u16);
        for (i, u) in name_units.iter().enumerate() {
            BigEndian::write_u16(&mut img[r0 + 8 + i * 2..r0 + 10 + i * 2], *u);
        }
        let r0_data = r0 + 2 + key_len + ((2 + key_len) % 2); // 2-byte align
        BigEndian::write_i16(&mut img[r0_data..r0_data + 2], CATALOG_FOLDER);
        BigEndian::write_u32(&mut img[r0_data + 8..r0_data + 12], 2); // folderID

        // Records 1..=N: synthetic child records keyed by (parent=2, name="cN")
        // so the root thread (parent=2, name="") gets pushed past the first leaf.
        // Using the smallest plausible record (we don't actually open the FS
        // here, just probe), so payload size doesn't matter beyond bounds.
        let mut rec_offsets = vec![14u16];
        let mut cursor = r0_data + 88;
        for i in 0..num_children {
            let child_name = format!("c{i}");
            let cn_units: Vec<u16> = child_name.encode_utf16().collect();
            let key_len = 6 + cn_units.len() * 2;
            let off = cursor;
            BigEndian::write_u16(&mut img[off..off + 2], key_len as u16);
            BigEndian::write_u32(&mut img[off + 2..off + 6], 2);
            BigEndian::write_u16(&mut img[off + 6..off + 8], cn_units.len() as u16);
            for (j, u) in cn_units.iter().enumerate() {
                BigEndian::write_u16(&mut img[off + 8 + j * 2..off + 10 + j * 2], *u);
            }
            // 2-byte aligned data offset, minimal 4-byte folder-record stub
            // (the probe never inspects it).
            let data = off + 2 + key_len + ((2 + key_len) % 2);
            BigEndian::write_i16(&mut img[data..data + 2], CATALOG_FOLDER);
            rec_offsets.push((off - leaf) as u16);
            cursor = data + 88;
        }

        // Offset table at end of leaf, MSB-first record-offset slots.
        let lot = leaf + node_size;
        for (i, off) in rec_offsets.iter().enumerate() {
            BigEndian::write_u16(&mut img[lot - 2 - i * 2..lot - i * 2], *off);
        }
        BigEndian::write_u16(
            &mut img[lot - 2 - rec_offsets.len() * 2..lot - rec_offsets.len() * 2],
            (cursor - leaf) as u16,
        );

        // Volume header.
        let vh = HfsPlusVolumeHeader {
            signature: HFS_PLUS_SIGNATURE,
            version: 4,
            attributes: 0,
            last_mounted_version: 0,
            journal_info_block: 0,
            create_date: 0,
            modify_date: 0,
            backup_date: 0,
            checked_date: 0,
            file_count: 0,
            folder_count: num_children as u32,
            block_size,
            total_blocks,
            free_blocks: total_blocks - 6,
            next_allocation: 6,
            rsrc_clump_size: 0,
            data_clump_size: 0,
            next_catalog_id: (16 + num_children) as u32,
            write_count: 0,
            encodings_bitmap: 0,
            finder_info: [0; 8],
            allocation_file: ForkData {
                logical_size: block_size as u64,
                clump_size: 0,
                total_blocks: 1,
                extents: {
                    let mut e = [ExtentDescriptor {
                        start_block: 0,
                        block_count: 0,
                    }; 8];
                    e[0] = ExtentDescriptor {
                        start_block: bitmap_block,
                        block_count: 1,
                    };
                    e
                },
            },
            extents_file: ForkData::empty(),
            catalog_file: ForkData {
                logical_size: (catalog_blocks as u64) * (block_size as u64),
                clump_size: 0,
                total_blocks: catalog_blocks,
                extents: {
                    let mut e = [ExtentDescriptor {
                        start_block: 0,
                        block_count: 0,
                    }; 8];
                    e[0] = ExtentDescriptor {
                        start_block: catalog_start_block,
                        block_count: catalog_blocks,
                    };
                    e
                },
            },
            attributes_file: ForkData::empty(),
            startup_file: ForkData::empty(),
        };
        let vh_bytes = vh.serialize();
        img[1024..1024 + 512].copy_from_slice(&vh_bytes);
        let alt = image_size - 1024;
        img[alt..alt + 512].copy_from_slice(&vh_bytes);
        img
    }

    #[test]
    fn test_probe_hfsplus_volume_label_reads_from_root_key() {
        // Volume name lives in the root folder record's key, even when the
        // first leaf is dominated by `parent=2` child records that push the
        // root thread out of the first leaf. This is the regression case
        // that broke the probe on real volumes like Ariel-backup.
        let img = make_hfsplus_image_with_label("Ariel-backup", 20);
        let mut cursor = std::io::Cursor::new(img);
        let label = probe_hfsplus_volume_label(&mut cursor, 0);
        assert_eq!(label.as_deref(), Some("Ariel-backup"));
    }

    #[test]
    fn test_probe_hfsplus_volume_label_short_name() {
        let img = make_hfsplus_image_with_label("X", 0);
        let mut cursor = std::io::Cursor::new(img);
        assert_eq!(
            probe_hfsplus_volume_label(&mut cursor, 0).as_deref(),
            Some("X")
        );
    }

    #[test]
    fn test_prepare_for_edit_refuses_journaled_volume_without_valid_journal() {
        // Set the journaled bit but provide no valid journal (journalInfoBlock
        // points at zeroed boot blocks). Since we can't verify the journal is
        // clean, `prepare_for_edit` refuses; a plain read-only `open` still
        // succeeds. (Clean journaled volumes — verified empty — are accepted;
        // see hfsplus_fsck::tests::prepare_for_edit_allows_clean_journaled_volume.)
        let mut img = make_editable_hfsplus_image();
        let attr_off = 1024 + 4; // VH offset 4 = attributes (u32 BE)
        let mut attrs = BigEndian::read_u32(&img[attr_off..attr_off + 4]);
        attrs |= HFSPLUS_VOLUME_JOURNALED_BIT;
        BigEndian::write_u32(&mut img[attr_off..attr_off + 4], attrs);

        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("read-only open should succeed");
        let err = fs
            .prepare_for_edit()
            .expect_err("journaled volume with no valid journal must refuse edit prep");
        match err {
            FilesystemError::Unsupported(msg) => assert!(msg.contains("journal")),
            other => panic!("expected Unsupported(journal...), got {other:?}"),
        }
    }

    #[test]
    fn test_sync_metadata_stamps_clean_unmount_attributes() {
        // Regression: an HFS+ volume opened from a "mounted/dirty" on-disk
        // state (bit 8 clear, bit 14 set) must be persisted as cleanly
        // unmounted (bit 8 set, bits 11/14 clear) after sync_metadata.
        // Without this, Disk Utility / fsck_hfs flag the volume as
        // inconsistent on next mount. See ~/Downloads/HFSTests/ case.
        let mut img = make_editable_hfsplus_image();
        let attr_off = 1024 + 4;
        let dirty = 0x80004000u32 | HFSPLUS_BOOT_VOLUME_INCONSISTENT_BIT;
        BigEndian::write_u32(&mut img[attr_off..attr_off + 4], dirty);

        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open");
        fs.prepare_for_edit().expect("prep");
        fs.sync_metadata().expect("sync");

        let img = fs.reader.into_inner();
        let after = BigEndian::read_u32(&img[attr_off..attr_off + 4]);
        assert!(
            after & HFSPLUS_VOLUME_UNMOUNTED_BIT != 0,
            "unmounted bit must be set after sync, got 0x{after:08x}"
        );
        assert!(
            after & HFSPLUS_VOLUME_INCONSISTENT_BIT == 0,
            "inconsistent bit must be cleared, got 0x{after:08x}"
        );
        assert!(
            after & HFSPLUS_BOOT_VOLUME_INCONSISTENT_BIT == 0,
            "boot-inconsistent bit must be cleared, got 0x{after:08x}"
        );
    }

    #[test]
    fn test_prepare_for_edit_clean_volume_succeeds() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit()
            .expect("clean volume should accept edit prep");
        // No xattrs on the synthetic image — the cached set is empty.
        assert!(fs.xattr_cnids.as_ref().unwrap().is_empty());
    }

    /// Fill many leaves, delete everything, fill again: no index record may
    /// point at a freed leaf, or the next insert lands in a free node.
    #[test]
    fn deleting_a_leafs_first_record_refreshes_the_separators() {
        // fsck_hfs E_IKey: after the audit's fill-and-delete run the parent
        // still carried the first key the leaf had before the delete.
        use crate::hfs_common::{
            btree_record_range, btree_stale_index_keys, BTreeHeader, BTreeKeyFormat,
        };
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;
        let img = create_blank_hfsplus_sized(64 * 1024 * 1024, 4096, "IKey", false, 16 << 20, 0);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();
        let root = fs.root().unwrap();
        let options = CreateFileOptions::default();
        for i in 0..1200 {
            let mut empty = std::io::Cursor::new(Vec::new());
            fs.create_file(&root, &format!("f{i:04}.txt"), &mut empty, 0, &options)
                .unwrap();
        }
        let node_size = fs.catalog_node_size();
        let header = BTreeHeader::read(fs.catalog_data());
        assert!(
            header.depth >= 2,
            "need an index level, depth {}",
            header.depth
        );

        // The first record of the second leaf is a file record: deleting that
        // file changes the key its parent's separator must carry.
        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 = BigEndian::read_u16(&rec[6..8]) as usize;
            (0..name_len)
                .map(|i| BigEndian::read_u16(&rec[8 + 2 * i..10 + 2 * i]) as u8 as char)
                .collect::<String>()
        };
        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 cmp = |a: &[u8], b: &[u8]| Fs::catalog_compare(a, b, false);
        let stale = btree_stale_index_keys(
            fs.catalog_data(),
            node_size,
            &BTreeKeyFormat::HFSPLUS_CATALOG,
            &cmp,
        );
        assert!(stale.is_empty(), "separators still stale: {stale:?}");
        let report = fs.fsck().unwrap().unwrap();
        assert!(
            report.errors.is_empty(),
            "{:?}",
            report
                .errors
                .iter()
                .map(|e| &e.message)
                .take(4)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn emptied_leaves_leave_the_index_too() {
        use crate::hfs_common::{btree_bitmap_test, btree_record_range, BTREE_INDEX_NODE};
        let img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "Leaves", false);
        let mut fs = HfsPlusFilesystem::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();
        let root = fs.root().unwrap();
        let names: Vec<String> = (0..220).map(|i| format!("leaf-file-{i:04}.txt")).collect();
        let fill = |fs: &mut HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>| {
            for n in &names {
                let mut src = std::io::Cursor::new(n.as_bytes().to_vec());
                fs.create_file(
                    &root,
                    n,
                    &mut src,
                    n.len() as u64,
                    &CreateFileOptions::default(),
                )
                .unwrap_or_else(|e| panic!("create {n}: {e:?}"));
            }
        };
        fill(&mut fs);
        assert!(
            fs.catalog_header.depth > 1,
            "the test needs a split catalog"
        );

        for e in fs.list_directory(&root).unwrap() {
            fs.delete_entry(&root, &e).unwrap();
        }
        // No index record may point at a free node.
        let node_size = fs.catalog_header.node_size as usize;
        let data = &fs.catalog_data;
        for idx in 1..(data.len() / node_size) as u32 {
            if !btree_bitmap_test(data, node_size, idx) {
                continue;
            }
            let off = idx as usize * node_size;
            let node = &data[off..off + node_size];
            if node[8] as i8 != BTREE_INDEX_NODE {
                continue;
            }
            let n = BigEndian::read_u16(&node[10..12]) as usize;
            for r in 0..n {
                let (_, end) = btree_record_range(node, node_size, r);
                let child = BigEndian::read_u32(&node[end - 4..end]);
                assert!(
                    btree_bitmap_test(data, node_size, child),
                    "index node {idx} points at free node {child}"
                );
            }
        }

        fill(&mut fs);
        let listed = fs.list_directory(&root).unwrap();
        assert_eq!(listed.len(), names.len());
        for e in &listed {
            assert_eq!(fs.read_file(e, usize::MAX).unwrap(), e.name.as_bytes());
        }
        fs.sync_metadata().unwrap();
        let report = fs.fsck().unwrap().unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);
    }

    #[test]
    fn test_create_blank_hfsplus_32mib() {
        let img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "MyVol", false);
        assert_eq!(img.len(), 32 * 1024 * 1024);

        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("blank should open");
        assert_eq!(fs.fs_type(), "HFS+");
        assert_eq!(fs.label, "MyVol");

        let root = fs.root().unwrap();
        let entries = fs.list_directory(&root).unwrap();
        assert!(entries.is_empty(), "freshly built blank must list empty");

        // 32 MiB / 4096 = 8192 blocks. The catalog is now volume-scaled
        // (~0.5%, docs/hfsplus_btree_growth_plan.md §4c): 32 MiB / 200 =
        // 167,772 bytes -> 41 nodes @ 4096. Reserved = 1 (boot/VH) + 1 (bitmap)
        // + 4 (extents, default) + 41 (catalog) = 47 at the front, plus the
        // trailing allocation block holding the alternate volume header (Apple
        // reserves it; required for an fsck_hfs-clean free-block count).
        assert_eq!(fs.vh.total_blocks, 8192);
        assert_eq!(fs.vh.free_blocks, 8192 - 47 - 1);
        // Edit-mode prep should succeed (unmounted bit set, no journal).
        fs.prepare_for_edit().expect("blank must accept edit prep");
    }

    #[test]
    fn test_create_blank_hfsx_32mib_signature() {
        let img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "CSVol", true);
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("HFSX blank should open");
        assert_eq!(fs.fs_type(), "HFSX");
        assert!(fs.vh.is_hfsx());
        assert_eq!(fs.label, "CSVol");
        let root = fs.root().unwrap();
        assert!(fs.list_directory(&root).unwrap().is_empty());
    }

    #[test]
    fn test_create_blank_hfsplus_supports_create_file() {
        // Round-trip: build a blank, create a file inside it, sync, reopen.
        let img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "Work", false);
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();
        let root = fs.root().unwrap();
        let payload = b"hello world".to_vec();
        let mut data = std::io::Cursor::new(payload.clone());
        fs.create_file(
            &root,
            "hello.txt",
            &mut data,
            payload.len() as u64,
            &CreateFileOptions::default(),
        )
        .expect("create_file on blank");
        fs.sync_metadata().unwrap();

        let img2 = fs.reader.into_inner();
        let mut cursor2 = std::io::Cursor::new(img2);
        let mut fs2 = HfsPlusFilesystem::open(&mut cursor2, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries = fs2.list_directory(&root2).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "hello.txt");
        let got = fs2.read_file(&entries[0], 1024).unwrap();
        assert_eq!(got, payload);
    }

    #[test]
    fn test_hfsplus_rename_round_trips() {
        let img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "Work", false);
        let mut fs = HfsPlusFilesystem::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();
        let root = fs.root().unwrap();

        let payload = b"keep my bytes across a rename".to_vec();
        let mut data = std::io::Cursor::new(payload.clone());
        let fe = fs
            .create_file(
                &root,
                "before.txt",
                &mut data,
                payload.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap();
        let cnid = fe.location;
        fs.create_directory(&root, "olddir", &CreateDirectoryOptions::default())
            .unwrap();

        // File rename to a longer name — exercises the variable-length thread
        // record rebuild (not an in-place patch).
        fs.rename(&root, &fe, "a much longer renamed file.txt")
            .unwrap();
        // Directory rename — its thread record is rebuilt too.
        let old_dir = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "olddir")
            .unwrap();
        fs.rename(&root, &old_dir, "newdir").unwrap();

        // A collision with a different entry is rejected.
        let mut t = std::io::Cursor::new(b"x".as_slice());
        fs.create_file(&root, "taken.txt", &mut t, 1, &CreateFileOptions::default())
            .unwrap();
        let renamed_now = fs
            .list_directory(&root)
            .unwrap()
            .into_iter()
            .find(|e| e.name == "a much longer renamed file.txt")
            .unwrap();
        assert!(matches!(
            fs.rename(&root, &renamed_now, "taken.txt"),
            Err(FilesystemError::AlreadyExists(_))
        ));

        // Persist and reopen: the renames survive a round-trip to disk.
        fs.sync_metadata().unwrap();
        let img2 = fs.reader.into_inner();
        let mut c2 = std::io::Cursor::new(img2);
        let mut fs2 = HfsPlusFilesystem::open(&mut c2, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries = fs2.list_directory(&root2).unwrap();
        assert!(
            entries
                .iter()
                .any(|e| e.name == "a much longer renamed file.txt"),
            "{entries:?}"
        );
        assert!(
            !entries.iter().any(|e| e.name == "before.txt"),
            "{entries:?}"
        );
        let renamed = entries
            .iter()
            .find(|e| e.name == "a much longer renamed file.txt")
            .unwrap();
        // CNID and content preserved through the catalog re-key.
        assert_eq!(renamed.location, cnid);
        assert_eq!(fs2.read_file(renamed, 4096).unwrap(), payload);
        // The renamed directory is still browsable.
        let newdir = entries.iter().find(|e| e.name == "newdir").unwrap();
        assert!(fs2.list_directory(newdir).is_ok());
    }

    #[test]
    fn test_create_file_stamps_dates() {
        // Newly-created files must have createDate / contentModDate /
        // attributeModDate / accessDate equal to sync-time hfs_now() to
        // within a couple seconds (test wall-clock jitter).
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();

        let now_before = hfs_common::hfs_now();
        let root = fs.root().unwrap();
        let mut data = std::io::Cursor::new(b"hi".as_slice());
        let entry = fs
            .create_file(
                &root,
                "dated.txt",
                &mut data,
                2,
                &CreateFileOptions::default(),
            )
            .unwrap();
        let now_after = hfs_common::hfs_now();

        // Locate the new file's catalog record and read all four dates.
        let cnid = entry.location as u32;
        let (_n, _r, f_off) = fs.find_catalog_record(2, "dated.txt").unwrap();
        let fkey_len = BigEndian::read_u16(&fs.catalog_data[f_off..f_off + 2]) as usize;
        let mut frec = f_off + 2 + fkey_len;
        if !frec.is_multiple_of(2) {
            frec += 1;
        }
        let create_date = BigEndian::read_u32(&fs.catalog_data[frec + 12..frec + 16]);
        let content_mod = BigEndian::read_u32(&fs.catalog_data[frec + 16..frec + 20]);
        let attr_mod = BigEndian::read_u32(&fs.catalog_data[frec + 20..frec + 24]);
        let access = BigEndian::read_u32(&fs.catalog_data[frec + 24..frec + 28]);

        for (label, value) in [
            ("createDate", create_date),
            ("contentModDate", content_mod),
            ("attributeModDate", attr_mod),
            ("accessDate", access),
        ] {
            assert!(
                value >= now_before && value <= now_after + 1,
                "{label} {value} not in [{now_before}, {now_after}+1]"
            );
        }

        // Counter parity: VH file_count must have incremented by one.
        assert_eq!(fs.vh.file_count, 1);
        let _ = cnid;
    }

    #[test]
    fn test_set_type_creator_bumps_attribute_mod_date() {
        // set_type_creator is an attribute-only change: attributeModDate
        // moves forward, but contentModDate (set at create-time) stays
        // pinned to the original value.
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();

        let root = fs.root().unwrap();
        let mut data = std::io::Cursor::new(b"x".as_slice());
        let entry = fs
            .create_file(&root, "a.txt", &mut data, 1, &CreateFileOptions::default())
            .unwrap();

        let (_n, _r, f_off) = fs.find_catalog_record(2, "a.txt").unwrap();
        let fkey_len = BigEndian::read_u16(&fs.catalog_data[f_off..f_off + 2]) as usize;
        let mut frec = f_off + 2 + fkey_len;
        if !frec.is_multiple_of(2) {
            frec += 1;
        }
        let content_before = BigEndian::read_u32(&fs.catalog_data[frec + 16..frec + 20]);

        // Force the timestamp to advance — hfs_now() has 1-second resolution.
        // Stuff the create-time content date into the past so we can assert
        // it stays put while attributeModDate moves to "now".
        BigEndian::write_u32(
            &mut fs.catalog_data[frec + 16..frec + 20],
            content_before - 60,
        );
        BigEndian::write_u32(
            &mut fs.catalog_data[frec + 20..frec + 24],
            content_before - 60,
        );

        let now_before = hfs_common::hfs_now();
        fs.set_type_creator(&entry, "TEXT", "ttxt").unwrap();
        let now_after = hfs_common::hfs_now();

        let content_after = BigEndian::read_u32(&fs.catalog_data[frec + 16..frec + 20]);
        let attr_after = BigEndian::read_u32(&fs.catalog_data[frec + 20..frec + 24]);
        assert_eq!(
            content_after,
            content_before - 60,
            "contentModDate must not move on attribute-only change"
        );
        assert!(
            attr_after >= now_before && attr_after <= now_after + 1,
            "attributeModDate {attr_after} not in [{now_before}, {now_after}+1]"
        );
    }

    #[test]
    fn test_extents_overflow_round_trip_12_extents() {
        // Pre-fragment so 12 isolated 1-block runs are the only free space,
        // then create a 12-block file. The first 8 land in the inline
        // ForkData slots, the remaining 4 in one extents-overflow record.
        // Sync, reopen, verify byte-equal read via read_fork_with_overflow.
        let img = make_editable_hfsplus_image_with_extents_btree();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();

        // Mark every block 0..=255 allocated, then clear 12 isolated single
        // blocks at evenly-spaced odd indices in the user-data region. The
        // 12 free blocks are at positions 11, 13, 15, ..., 33.
        fs.ensure_bitmap().unwrap();
        let bitmap = fs.bitmap.as_mut().unwrap();
        for byte in bitmap.iter_mut().take(32) {
            *byte = 0xFF;
        }
        let free_positions: Vec<u32> = (0..12).map(|i| 11 + 2 * i as u32).collect();
        for &blk in &free_positions {
            bitmap_clear_bit_be(bitmap, blk);
        }
        fs.vh.free_blocks = 12;

        let block_size = fs.vh.block_size as usize;
        let payload: Vec<u8> = (0..(12 * block_size)).map(|i| (i % 251) as u8).collect();
        let mut reader = std::io::Cursor::new(payload.clone());
        let root = fs.root().unwrap();
        let entry = fs
            .create_file(
                &root,
                "frag12.bin",
                &mut reader,
                payload.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("12-extent allocation should succeed via overflow B-tree");

        let cnid = entry.location as u32;
        let (data_fork, _rsrc) = fs.find_file_by_id(cnid).unwrap();
        // 8 inline extents, all 1-block.
        for slot in &data_fork.extents {
            assert_eq!(slot.block_count, 1);
        }
        assert_eq!(data_fork.total_blocks, 12);

        // Sync to disk.
        fs.sync_metadata().unwrap();

        // Reopen the underlying buffer and confirm read_fork_with_overflow
        // reproduces the data byte-for-byte.
        let img_after = fs.reader.into_inner();
        let mut cursor2 = std::io::Cursor::new(img_after);
        let mut fs2 = HfsPlusFilesystem::open(&mut cursor2, 0).unwrap();
        let root2 = fs2.root().unwrap();
        let entries = fs2.list_directory(&root2).unwrap();
        let reopened = entries.iter().find(|e| e.name == "frag12.bin").unwrap();
        let got = fs2.read_file(reopened, payload.len() + 1).unwrap();
        assert_eq!(got.len(), payload.len());
        assert_eq!(got, payload);
    }

    #[test]
    fn test_allocate_extents_fragmented_bitmap() {
        // Pre-fragment the synthetic volume so 4 free blocks exist as four
        // 1-block runs (blocks 7, 9, 11, 13). Asking for 4 must return four
        // single-block extents and the data must round-trip byte-equal.
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();

        // Force the bitmap to load, then rewrite it. Block 0 = first byte
        // (bits 0..=7 = blocks 0..=7); we want blocks 0..=255 all allocated
        // EXCEPT 7, 9, 11, 13.
        fs.ensure_bitmap().unwrap();
        let bitmap = fs.bitmap.as_mut().unwrap();
        for byte in bitmap.iter_mut().take(32) {
            *byte = 0xFF;
        }
        // Clear blocks 7, 9, 11, 13.
        for blk in [7u32, 9, 11, 13] {
            bitmap_clear_bit_be(bitmap, blk);
        }
        fs.vh.free_blocks = 4;

        let block_size = fs.vh.block_size as usize;
        let payload: Vec<u8> = (0..(4 * block_size)).map(|i| (i % 251) as u8).collect();
        let mut reader = std::io::Cursor::new(payload.clone());
        let root = fs.root().unwrap();
        let entry = fs
            .create_file(
                &root,
                "frag.bin",
                &mut reader,
                payload.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("fragmented allocation should succeed");

        let cnid = entry.location as u32;
        let (data_fork, _rsrc) = fs.find_file_by_id(cnid).expect("file record present");

        // 4 single-block extents in slots 0..3.
        for (i, expected_start) in [7u32, 9, 11, 13].iter().enumerate() {
            assert_eq!(data_fork.extents[i].block_count, 1, "slot {i}");
            assert_eq!(
                data_fork.extents[i].start_block, *expected_start,
                "slot {i}"
            );
        }
        for slot in &data_fork.extents[4..] {
            assert!(slot.is_empty(), "slot past 4 should be empty");
        }
        assert_eq!(data_fork.total_blocks, 4);

        // Read it back and confirm byte-equal.
        let mut got = Vec::new();
        fs.write_file_to(&entry, &mut got).unwrap();
        assert_eq!(got, payload);
        assert_eq!(fs.vh.free_blocks, 0);
    }

    #[test]
    fn test_snapshot_rollback_on_disk_full_create_file() {
        // The synthetic editable image has 250 free 4 KiB blocks. Asking
        // create_file for 251 blocks' worth of data should trip the
        // allocator's DiskFull and the snapshot guard must rewind every
        // mutation made before the failure (next_catalog_id bump, bitmap
        // dirty load, etc.).
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();

        let next_cnid_before = fs.vh.next_catalog_id;
        let free_blocks_before = fs.vh.free_blocks;
        let file_count_before = fs.vh.file_count;
        let catalog_before = fs.catalog_data.clone();

        let root = fs.root().unwrap();
        let big_len: u64 = 251 * 4096 + 1; // exceeds the 250 free blocks
        let big_buf = vec![0u8; big_len as usize];
        let mut reader = std::io::Cursor::new(big_buf);
        let err = fs
            .create_file(
                &root,
                "too-big.bin",
                &mut reader,
                big_len,
                &CreateFileOptions::default(),
            )
            .expect_err("create_file should fail with DiskFull");
        assert!(matches!(err, FilesystemError::DiskFull(_)), "got {err:?}");

        assert_eq!(fs.vh.next_catalog_id, next_cnid_before);
        assert_eq!(fs.vh.free_blocks, free_blocks_before);
        assert_eq!(fs.vh.file_count, file_count_before);
        assert_eq!(fs.catalog_data, catalog_before);
    }

    #[test]
    fn test_set_xattr_round_trip_and_delete_cleanup() {
        // Step 13 round-trip: on a volume with an attributes B-tree, create a
        // file, attach 3 inline xattrs, sync, reopen, verify all 3 round-trip,
        // then delete the file and confirm every attribute record for its
        // CNID is gone.
        //
        // Seed image carries a sentinel record on cnid=99 so the attributes
        // file actually exists; the test never reads it back, just verifies
        // it survives unaffected when an unrelated CNID's xattrs are deleted.
        let sentinel_cnid = 99u32;
        let img = make_editable_hfsplus_image_with_inline_xattr(sentinel_cnid, &[0xAA; 8]);
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();

        let root = fs.root().unwrap();
        let mut data = std::io::Cursor::new(b"x".as_slice());
        let entry = fs
            .create_file(
                &root,
                "with-xattr.txt",
                &mut data,
                1,
                &CreateFileOptions::default(),
            )
            .expect("create_file");
        let cnid = entry.location as u32;

        let pairs: [(&str, &[u8]); 3] = [
            ("com.apple.FinderInfo", &[1u8; 32]),
            ("com.apple.metadata:_kMDItemUserTags", b"\x00bplist00 tag"),
            ("user.short", b"hi"),
        ];
        for (name, value) in pairs.iter() {
            fs.set_xattr(cnid, name, value).expect("set_xattr");
        }
        fs.sync_metadata().unwrap();

        // Reopen the freshly synced bytes and verify all three records survived.
        let img2 = fs.reader.into_inner();
        let mut cursor2 = std::io::Cursor::new(img2);
        let mut fs2 = HfsPlusFilesystem::open(&mut cursor2, 0).unwrap();
        let mut got = fs2.list_xattrs(cnid).expect("list_xattrs");
        got.sort_by(|a, b| a.name.cmp(&b.name));
        let mut want: Vec<(String, Vec<u8>)> = pairs
            .iter()
            .map(|(n, v)| (n.to_string(), v.to_vec()))
            .collect();
        want.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(got.len(), want.len());
        for (rec, (wname, wval)) in got.iter().zip(want.iter()) {
            assert_eq!(rec.name, *wname);
            match &rec.kind {
                XattrKind::Inline(bytes) => assert_eq!(bytes, wval),
                other => panic!("expected Inline xattr, got {other:?}"),
            }
        }

        // Sentinel xattr on the unrelated CNID still present.
        let sentinel = fs2
            .list_xattrs(sentinel_cnid)
            .expect("sentinel list_xattrs");
        assert_eq!(sentinel.len(), 1, "sentinel record should survive");

        // Delete the file: every attribute row keyed at our cnid must vanish.
        fs2.prepare_for_edit().unwrap();
        let root2 = fs2.root().unwrap();
        let listing = fs2.list_directory(&root2).unwrap();
        let target = listing
            .iter()
            .find(|e| e.name == "with-xattr.txt")
            .cloned()
            .expect("entry on reopened volume");
        fs2.delete_entry(&root2, &target).expect("delete");
        let after = fs2.list_xattrs(cnid).expect("post-delete list_xattrs");
        assert!(
            after.is_empty(),
            "expected 0 records after delete, got {}",
            after.len()
        );
        let sentinel_after = fs2
            .list_xattrs(sentinel_cnid)
            .expect("sentinel post-delete");
        assert_eq!(sentinel_after.len(), 1, "sentinel must survive delete");
    }

    #[test]
    fn test_remove_xattr_not_found_and_cleanup() {
        // remove_xattr on a missing name returns NotFound, and removing the
        // last xattr drops the cnid from the cached set.
        let cnid = 17u32;
        let img = make_editable_hfsplus_image_with_inline_xattr(cnid, &[0u8; 16]);
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();
        assert!(fs.xattr_cnids.as_ref().unwrap().contains(&cnid));

        let err = fs
            .remove_xattr(cnid, "com.apple.does-not-exist")
            .expect_err("missing xattr must error");
        assert!(matches!(err, FilesystemError::NotFound(_)));

        fs.remove_xattr(cnid, "com.apple.FinderInfo")
            .expect("remove existing xattr");
        assert!(
            !fs.xattr_cnids.as_ref().unwrap().contains(&cnid),
            "cnid should be dropped from cache once its last xattr is gone"
        );
    }

    #[test]
    fn test_list_xattrs_round_trips_inline_finder_info() {
        // Synthesize a 32-byte com.apple.FinderInfo inline xattr on CNID 17,
        // assert list_xattrs returns it byte-for-byte and reports an empty
        // list for an unrelated CNID.
        let cnid = 17u32;
        let finder_info: Vec<u8> = (0..32u8).collect();
        let img = make_editable_hfsplus_image_with_inline_xattr(cnid, &finder_info);
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

        let recs = fs.list_xattrs(cnid).expect("list_xattrs cnid=17");
        assert_eq!(recs.len(), 1, "expected exactly one xattr record");
        let rec = &recs[0];
        assert_eq!(rec.name, "com.apple.FinderInfo");
        assert_eq!(rec.start_block, 0);
        match &rec.kind {
            XattrKind::Inline(bytes) => assert_eq!(bytes, &finder_info),
            other => panic!("expected Inline xattr, got {other:?}"),
        }

        // Unrelated CNID returns empty.
        let none = fs.list_xattrs(99).expect("list_xattrs cnid=99");
        assert!(none.is_empty(), "expected no xattrs for cnid=99");

        // Volume with no attributes file (the seed image) returns empty too.
        let bare = make_editable_hfsplus_image();
        let mut bare_fs = HfsPlusFilesystem::open(std::io::Cursor::new(bare), 0).unwrap();
        let empty = bare_fs.list_xattrs(cnid).expect("list_xattrs no attr file");
        assert!(empty.is_empty(), "no attributes file → no records");
    }

    #[test]
    fn test_hardlink_resolution_two_links_one_inode() {
        // Step 15: synthesize a volume with two hardlinks pointing at one
        // inode under `HFS+ Private Data`. Both link rows must surface as
        // regular files in `list_directory`, carry `link_target_cnid` set
        // to the inode CNID, and read back the inode's data fork bytes.
        const PAYLOAD: &[u8] = b"INODE_PAYLOAD_42\n";
        const I_NODE_NUM: u32 = 99;

        let mut img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "Links", false);

        // Build the volume contents: private dir, inode, two link stubs.
        // Patch the link stubs' catalog records to set FInfo type='hlnk'
        // creator='hfs+' and bsdInfo.special = I_NODE_NUM. We do this via
        // direct catalog-byte edits while holding the editable handle, then
        // sync once at the end.
        let inode_cnid: u32;
        {
            let cursor = std::io::Cursor::new(&mut img);
            let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open blank");
            fs.prepare_for_edit().expect("prepare_for_edit");
            let root = fs.root().expect("root");

            let private_dir = fs
                .create_directory(
                    &root,
                    &hfsplus_private_dir_name(),
                    &CreateDirectoryOptions::default(),
                )
                .expect("create private dir");

            let mut inode_data = std::io::Cursor::new(PAYLOAD);
            let inode_entry = fs
                .create_file(
                    &private_dir,
                    &format!("iNode{I_NODE_NUM}"),
                    &mut inode_data,
                    PAYLOAD.len() as u64,
                    &CreateFileOptions::default(),
                )
                .expect("create inode file");
            inode_cnid = inode_entry.location as u32;

            for link_name in ["linkA", "linkB"] {
                let mut empty = std::io::Cursor::new(&[][..]);
                fs.create_file(
                    &root,
                    link_name,
                    &mut empty,
                    0,
                    &CreateFileOptions {
                        os_type: Some(*b"hlnk"),
                        os_creator: Some(*b"hfs+"),
                        ..Default::default()
                    },
                )
                .expect("create link stub");

                // Patch bsdInfo.special on the freshly-created stub to point
                // at the inode number. body offset 32+12 = 44.
                let (_node, _rec, abs) = fs
                    .find_catalog_record(2, link_name)
                    .expect("link stub in catalog");
                let key_len = BigEndian::read_u16(&fs.catalog_data[abs..abs + 2]) as usize;
                let mut body_start = abs + 2 + key_len;
                if !body_start.is_multiple_of(2) {
                    body_start += 1;
                }
                BigEndian::write_u32(
                    &mut fs.catalog_data[body_start + 44..body_start + 48],
                    I_NODE_NUM,
                );
            }

            fs.sync_metadata().expect("sync");
        }

        // Re-open, walk root, verify both link stubs resolve to the inode
        // and read back the inode's bytes.
        let cursor = std::io::Cursor::new(&mut img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("re-open");
        let root = fs.root().expect("root");
        let entries = fs.list_directory(&root).expect("list root");
        let link_a = entries
            .iter()
            .find(|e| e.name == "linkA")
            .cloned()
            .expect("linkA");
        let link_b = entries
            .iter()
            .find(|e| e.name == "linkB")
            .cloned()
            .expect("linkB");

        assert_eq!(
            link_a.link_target_cnid,
            Some(inode_cnid as u64),
            "linkA must resolve to inode CNID"
        );
        assert_eq!(
            link_b.link_target_cnid,
            Some(inode_cnid as u64),
            "linkB must resolve to inode CNID"
        );
        // Display size should reflect the inode's data fork, not the empty
        // stub fork.
        assert_eq!(link_a.size, PAYLOAD.len() as u64);
        assert_eq!(link_b.size, PAYLOAD.len() as u64);

        let bytes_a = fs.read_file(&link_a, usize::MAX).expect("read linkA");
        let bytes_b = fs.read_file(&link_b, usize::MAX).expect("read linkB");
        assert_eq!(bytes_a, PAYLOAD);
        assert_eq!(bytes_b, PAYLOAD);

        // Sanity: a file with no hardlink magic stays plain.
        // The private dir itself shows up at root with `link_target_cnid`
        // unset (it's a folder, not a file hardlink).
        let private = entries
            .iter()
            .find(|e| e.name == hfsplus_private_dir_name())
            .expect("private dir at root");
        assert!(private.link_target_cnid.is_none());
    }

    #[test]
    fn test_hardlink_delete_decrements_then_frees_inode() {
        // Step 16: deleting a hardlink decrements `linkCount` on the inode;
        // deleting the last reference frees the inode, drops it from the
        // private directory, and reclaims its data fork blocks.
        const PAYLOAD: &[u8] = b"INODE_DATA_FOR_DELETE\n";
        const I_NODE_NUM: u32 = 7;

        let mut img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "DelLinks", false);

        // Capture initial free-block count after the build, then synthesize
        // private dir + inode (linkCount=2) + two stubs.
        let inode_cnid: u32;
        let private_cnid: u32;
        let payload_blocks_used: u32;
        let free_after_build: u32;
        let free_with_inode: u32;
        {
            let cursor = std::io::Cursor::new(&mut img);
            let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open blank");
            fs.prepare_for_edit().expect("prepare_for_edit");
            free_after_build = fs.vh.free_blocks;
            let root = fs.root().expect("root");
            let private_dir = fs
                .create_directory(
                    &root,
                    &hfsplus_private_dir_name(),
                    &CreateDirectoryOptions::default(),
                )
                .expect("create private dir");
            private_cnid = private_dir.location as u32;

            let mut inode_data = std::io::Cursor::new(PAYLOAD);
            let inode_entry = fs
                .create_file(
                    &private_dir,
                    &format!("iNode{I_NODE_NUM}"),
                    &mut inode_data,
                    PAYLOAD.len() as u64,
                    &CreateFileOptions::default(),
                )
                .expect("create inode file");
            inode_cnid = inode_entry.location as u32;
            free_with_inode = fs.vh.free_blocks;
            payload_blocks_used = free_after_build - free_with_inode;
            assert!(
                payload_blocks_used >= 1,
                "inode payload must consume at least one block"
            );

            // Initialize bsdInfo.special on the inode record to linkCount=2.
            {
                let (_, _, abs) = fs
                    .find_catalog_record(private_cnid, &format!("iNode{I_NODE_NUM}"))
                    .expect("inode catalog record");
                let key_len = BigEndian::read_u16(&fs.catalog_data[abs..abs + 2]) as usize;
                let mut body = abs + 2 + key_len;
                if !body.is_multiple_of(2) {
                    body += 1;
                }
                BigEndian::write_u32(&mut fs.catalog_data[body + 44..body + 48], 2);
            }

            for link_name in ["linkA", "linkB"] {
                let mut empty = std::io::Cursor::new(&[][..]);
                fs.create_file(
                    &root,
                    link_name,
                    &mut empty,
                    0,
                    &CreateFileOptions {
                        os_type: Some(*b"hlnk"),
                        os_creator: Some(*b"hfs+"),
                        ..Default::default()
                    },
                )
                .expect("create stub");
                let (_, _, abs) = fs.find_catalog_record(2, link_name).expect("stub");
                let key_len = BigEndian::read_u16(&fs.catalog_data[abs..abs + 2]) as usize;
                let mut body = abs + 2 + key_len;
                if !body.is_multiple_of(2) {
                    body += 1;
                }
                BigEndian::write_u32(&mut fs.catalog_data[body + 44..body + 48], I_NODE_NUM);
            }
            fs.sync_metadata().expect("sync");
        }

        // Re-open editable, delete linkA. linkB and the inode must remain
        // readable; linkCount must drop to 1.
        let cursor = std::io::Cursor::new(&mut img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("re-open");
        fs.prepare_for_edit().expect("prepare_for_edit");
        let root = fs.root().expect("root");
        let entries = fs.list_directory(&root).expect("list");
        let link_a = entries
            .iter()
            .find(|e| e.name == "linkA")
            .cloned()
            .expect("linkA");
        let link_b = entries
            .iter()
            .find(|e| e.name == "linkB")
            .cloned()
            .expect("linkB");
        let free_before_delete = fs.vh.free_blocks;

        fs.delete_entry(&root, &link_a).expect("delete linkA");
        // linkCount should now be 1; inode + linkB still alive.
        let cnt_after_first = {
            let (_, _, abs) = fs
                .find_catalog_record(private_cnid, &format!("iNode{I_NODE_NUM}"))
                .expect("inode still present");
            let key_len = BigEndian::read_u16(&fs.catalog_data[abs..abs + 2]) as usize;
            let mut body = abs + 2 + key_len;
            if !body.is_multiple_of(2) {
                body += 1;
            }
            BigEndian::read_u32(&fs.catalog_data[body + 44..body + 48])
        };
        assert_eq!(cnt_after_first, 1, "linkCount should decrement to 1");
        assert_eq!(
            fs.vh.free_blocks, free_before_delete,
            "no blocks freed while inode still has refs"
        );
        // linkB still resolves and reads the original payload.
        let bytes_b = fs.read_file(&link_b, usize::MAX).expect("read linkB");
        assert_eq!(bytes_b, PAYLOAD);

        fs.delete_entry(&root, &link_b).expect("delete linkB");
        // Inode must be gone from the private dir, blocks reclaimed.
        let private_children = fs.list_children(private_cnid).expect("list private dir");
        assert!(
            private_children.is_empty(),
            "iNode entry should be removed once linkCount hits 0; got {} children",
            private_children.len()
        );
        assert!(
            fs.find_file_by_id(inode_cnid).is_none(),
            "inode catalog row should be gone"
        );
        assert_eq!(
            fs.vh.free_blocks,
            free_before_delete + payload_blocks_used,
            "inode payload blocks should be reclaimed"
        );
    }

    #[test]
    fn test_hardlink_capture_and_replay_dedupes_inode() {
        // Step 17: source carries 1 inode + 3 file hardlinks. Capture
        // routes the inode into `files` with `is_inode = true` and the
        // three stubs into `hardlinks`. Replay onto a freshly built blank
        // via `create_hardlink_inode` + `create_hardlink` produces a
        // target with one inode + three stub rows (not four independent
        // files), all reading the same payload bytes.
        const PAYLOAD: &[u8] = b"shared inode contents (3 names)\n";
        const I_NODE_NUM: u32 = 17;

        // Build the source.
        let mut source_img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "Src", false);
        let source_inode_cnid: u32;
        {
            let cursor = std::io::Cursor::new(&mut source_img);
            let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open src blank");
            fs.prepare_for_edit().expect("prepare_for_edit");
            let mut data = std::io::Cursor::new(PAYLOAD);
            let inode = fs
                .create_hardlink_inode(
                    I_NODE_NUM,
                    &mut data,
                    PAYLOAD.len() as u64,
                    &CreateFileOptions::default(),
                )
                .expect("create source inode");
            source_inode_cnid = inode.location as u32;
            // Initialize linkCount=0 on the inode then let create_hardlink
            // bump it three times.
            let private_cnid = fs.find_private_dir_cnid().unwrap().expect("private dir");
            let _ = fs
                .adjust_inode_link_count(private_cnid, I_NODE_NUM, 0)
                .expect("init linkCount");
            let root = fs.root().expect("root");
            for name in ["a.txt", "b.txt", "c.txt"] {
                fs.create_hardlink(&root, name, I_NODE_NUM)
                    .expect("create stub");
            }
            fs.sync_metadata().expect("sync src");
        }

        // Capture from the source.
        let cursor = std::io::Cursor::new(&mut source_img);
        let mut src_fs = HfsPlusFilesystem::open(cursor, 0).expect("re-open src");
        let snap =
            crate::hfsplus_clone::SourceCatalogSnapshot::capture(&mut src_fs).expect("capture");

        // Snapshot expectations: exactly one inode, three hardlink stubs.
        let inodes: Vec<_> = snap.files.iter().filter(|f| f.is_inode).collect();
        assert_eq!(inodes.len(), 1, "expected exactly one inode in snapshot");
        let inode = inodes[0];
        assert_eq!(inode.cnid, source_inode_cnid);
        assert_eq!(inode.inode_num, Some(I_NODE_NUM));
        assert_eq!(inode.data_fork_size, PAYLOAD.len() as u64);
        // Stream the inode's data fork off the source and verify byte-equal.
        let inode_payload = {
            use std::io::Read;
            let mut buf = Vec::new();
            src_fs
                .fork_stream_reader(inode.cnid, 0x00, &inode.data_fork_raw)
                .expect("fork reader")
                .read_to_end(&mut buf)
                .expect("read fork");
            buf
        };
        assert_eq!(inode_payload, PAYLOAD);

        let user_files: Vec<_> = snap.files.iter().filter(|f| !f.is_inode).collect();
        assert!(
            user_files.is_empty(),
            "user-tree files should be empty (the three stubs are in `hardlinks`); \
             got {:?}",
            user_files.iter().map(|f| &f.name).collect::<Vec<_>>()
        );

        assert_eq!(snap.hardlinks.len(), 3, "expected 3 hardlink stubs");
        for h in &snap.hardlinks {
            assert_eq!(h.inode_num, I_NODE_NUM);
            assert_eq!(h.inode_source_cnid, source_inode_cnid);
            assert_eq!(h.parent_cnid, 2, "stubs live at root");
        }

        // Replay onto a fresh blank target using the capture data.
        let mut target_img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "Tgt", false);
        let target_inode_cnid: u32;
        {
            let cursor = std::io::Cursor::new(&mut target_img);
            let mut tgt = HfsPlusFilesystem::open(cursor, 0).expect("open tgt blank");
            tgt.prepare_for_edit().expect("prepare_for_edit");

            let mut data = std::io::Cursor::new(&inode_payload);
            let target_inode = tgt
                .create_hardlink_inode(
                    inode.inode_num.unwrap(),
                    &mut data,
                    inode.data_fork_size,
                    &CreateFileOptions::default(),
                )
                .expect("replay inode");
            target_inode_cnid = target_inode.location as u32;

            let root = tgt.root().expect("tgt root");
            for h in &snap.hardlinks {
                tgt.create_hardlink(&root, &h.name, h.inode_num)
                    .expect("replay stub");
            }
            tgt.sync_metadata().expect("sync tgt");
        }

        // Verify the target.
        let cursor = std::io::Cursor::new(&mut target_img);
        let mut tgt_fs = HfsPlusFilesystem::open(cursor, 0).expect("re-open tgt");
        let root = tgt_fs.root().expect("tgt root");
        let entries = tgt_fs.list_directory(&root).expect("list tgt root");

        // Three stubs at root, each pointing at the same inode CNID, each
        // reading back the original payload.
        let stubs: Vec<&FileEntry> = entries
            .iter()
            .filter(|e| ["a.txt", "b.txt", "c.txt"].contains(&e.name.as_str()))
            .collect();
        assert_eq!(stubs.len(), 3);
        for stub in &stubs {
            assert_eq!(
                stub.link_target_cnid,
                Some(target_inode_cnid as u64),
                "stub {} must resolve to the single target inode",
                stub.name
            );
            assert_eq!(stub.size, PAYLOAD.len() as u64);
        }
        for stub in &stubs {
            let bytes = tgt_fs.read_file(stub, usize::MAX).expect("read tgt stub");
            assert_eq!(bytes, PAYLOAD);
        }

        // Inode's linkCount on the target must be 3 (one per stub).
        let private_cnid = tgt_fs
            .find_private_dir_cnid()
            .unwrap()
            .expect("private dir");
        let inode_name = format!("iNode{I_NODE_NUM}");
        let (_, _, abs) = tgt_fs
            .find_catalog_record(private_cnid, &inode_name)
            .expect("inode in private dir");
        let key_len = BigEndian::read_u16(&tgt_fs.catalog_data[abs..abs + 2]) as usize;
        let mut body = abs + 2 + key_len;
        if !body.is_multiple_of(2) {
            body += 1;
        }
        let link_count = BigEndian::read_u32(&tgt_fs.catalog_data[body + 44..body + 48]);
        assert_eq!(link_count, 3, "inode linkCount must equal stub count");
    }

    #[test]
    fn test_dir_hardlink_capture_and_replay_resolves_to_inode() {
        // Step 18: Time-Machine-shaped image — one directory inode under
        // `.HFS+ Private Directory Data\r` with two hardlink stubs at the
        // root. Capture must dedupe the inode (one entry in `dirs` with
        // `is_dir_inode = true`, two entries in `dir_hardlinks`); replay
        // must produce a target whose two link rows resolve to the same
        // directory contents byte-for-byte.
        const PAYLOAD: &[u8] = b"file inside dir-hardlinked folder\n";
        const D_INODE_NUM: u32 = 13;

        // ---- Build the source. ----
        let mut source_img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "DhSrc", false);
        let source_inode_cnid: u32;
        {
            let cursor = std::io::Cursor::new(&mut source_img);
            let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open src");
            fs.prepare_for_edit().expect("prepare_for_edit");
            let inode_dir = fs
                .create_dir_hardlink_inode(D_INODE_NUM, &CreateDirectoryOptions::default())
                .expect("create dir inode");
            source_inode_cnid = inode_dir.location as u32;
            // Put a file inside the inode dir so `list_directory` has
            // something to compare on the replayed side.
            let mut data = std::io::Cursor::new(PAYLOAD);
            fs.create_file(
                &inode_dir,
                "inside.txt",
                &mut data,
                PAYLOAD.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("create file in dir inode");
            // Initialize linkCount=0 then bump per stub.
            let dir_priv = fs
                .find_dir_private_dir_cnid()
                .unwrap()
                .expect("dir private");
            let _ = fs
                .adjust_dir_inode_link_count(dir_priv, D_INODE_NUM, 0)
                .expect("init dir linkCount");
            let root = fs.root().expect("root");
            for name in ["alpha", "beta"] {
                fs.create_dir_hardlink(&root, name, D_INODE_NUM)
                    .expect("create dir hardlink stub");
            }
            fs.sync_metadata().expect("sync src");
        }

        // ---- Capture from the source. ----
        let cursor = std::io::Cursor::new(&mut source_img);
        let mut src_fs = HfsPlusFilesystem::open(cursor, 0).expect("re-open src");
        let snap =
            crate::hfsplus_clone::SourceCatalogSnapshot::capture(&mut src_fs).expect("capture");

        // Snapshot expectations: exactly one directory inode, two stubs.
        let dir_inodes: Vec<_> = snap.dirs.iter().filter(|d| d.is_dir_inode).collect();
        assert_eq!(
            dir_inodes.len(),
            1,
            "expected exactly one dir inode in snapshot; got {}",
            dir_inodes.len()
        );
        let dir_inode = dir_inodes[0];
        assert_eq!(dir_inode.cnid, source_inode_cnid);
        assert_eq!(dir_inode.inode_num, Some(D_INODE_NUM));

        assert_eq!(snap.dir_hardlinks.len(), 2, "expected 2 dir-hardlink stubs");
        for h in &snap.dir_hardlinks {
            assert_eq!(h.inode_num, D_INODE_NUM);
            assert_eq!(h.inode_dir_source_cnid, source_inode_cnid);
            assert_eq!(h.parent_cnid, 2, "stubs live at root");
        }

        // ---- Replay onto a fresh blank target. ----
        let mut target_img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "DhTgt", false);
        let target_inode_cnid: u32;
        {
            let cursor = std::io::Cursor::new(&mut target_img);
            let mut tgt = HfsPlusFilesystem::open(cursor, 0).expect("open tgt");
            tgt.prepare_for_edit().expect("prepare_for_edit");

            // Create the inode directory.
            let inode = tgt
                .create_dir_hardlink_inode(
                    dir_inode.inode_num.unwrap(),
                    &CreateDirectoryOptions::default(),
                )
                .expect("replay dir inode");
            target_inode_cnid = inode.location as u32;

            // Replay the inode's children. (For a real clone Step 21 will
            // recursively walk; here it's just one file.)
            let mut data = std::io::Cursor::new(PAYLOAD);
            tgt.create_file(
                &inode,
                "inside.txt",
                &mut data,
                PAYLOAD.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("replay child file");

            // Replay the stubs.
            let root = tgt.root().expect("tgt root");
            for h in &snap.dir_hardlinks {
                tgt.create_dir_hardlink(&root, &h.name, h.inode_num)
                    .expect("replay dir stub");
            }
            tgt.sync_metadata().expect("sync tgt");
        }

        // ---- Verify the target. ----
        let cursor = std::io::Cursor::new(&mut target_img);
        let mut tgt_fs = HfsPlusFilesystem::open(cursor, 0).expect("re-open tgt");
        let root = tgt_fs.root().expect("tgt root");
        let entries = tgt_fs.list_directory(&root).expect("list tgt root");

        // Both stubs surface as Directory entries pointing at the single
        // inode, and listing either of them returns the same children.
        for stub_name in ["alpha", "beta"] {
            let stub = entries
                .iter()
                .find(|e| e.name == stub_name)
                .cloned()
                .unwrap_or_else(|| panic!("stub {stub_name} missing from target root"));
            assert!(
                stub.is_directory(),
                "stub {stub_name} must surface as a directory"
            );
            assert_eq!(
                stub.link_target_cnid,
                Some(target_inode_cnid as u64),
                "stub {stub_name} must resolve to the single target inode"
            );

            let children = tgt_fs.list_directory(&stub).expect("list stub");
            let inside = children
                .iter()
                .find(|c| c.name == "inside.txt")
                .unwrap_or_else(|| panic!("inside.txt missing under {stub_name}"));
            let bytes = tgt_fs
                .read_file(inside, usize::MAX)
                .expect("read inside.txt via stub");
            assert_eq!(bytes, PAYLOAD);
        }

        // Inode's linkCount on the target must equal stub count (2).
        let dir_priv = tgt_fs
            .find_dir_private_dir_cnid()
            .unwrap()
            .expect("tgt dir private");
        let inode_name = format!("dir_{D_INODE_NUM}");
        let (_, _, abs) = tgt_fs
            .find_catalog_record(dir_priv, &inode_name)
            .expect("dir inode in private dir");
        let key_len = BigEndian::read_u16(&tgt_fs.catalog_data[abs..abs + 2]) as usize;
        let mut body = abs + 2 + key_len;
        if !body.is_multiple_of(2) {
            body += 1;
        }
        let link_count = BigEndian::read_u32(&tgt_fs.catalog_data[body + 44..body + 48]);
        assert_eq!(link_count, 2, "dir inode linkCount must equal stub count");
    }

    #[test]
    fn test_hfsx_case_sensitive_allows_distinct_case_siblings() {
        // Step 19: HFSX volumes with `keyCompareType == 0xBC` (binary)
        // must treat `Foo` and `foo` as distinct names. Plain HFS+ —
        // including HFSX volumes built with `keyCompareType == 0xCF`
        // (case-folding NFD compare) — must reject the second create with
        // `AlreadyExists`.
        const PAYLOAD: &[u8] = b"hi\n";

        // ---- HFSX, case-sensitive: both creates succeed. ----
        {
            let mut img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "HFSX", true);
            let cursor = std::io::Cursor::new(&mut img);
            let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open hfsx");
            assert!(
                fs.case_sensitive(),
                "fresh HFSX blank must be case-sensitive"
            );
            fs.prepare_for_edit().expect("prepare");
            let root = fs.root().expect("root");

            let mut data = std::io::Cursor::new(PAYLOAD);
            fs.create_file(
                &root,
                "Foo",
                &mut data,
                PAYLOAD.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("create Foo");

            let mut data = std::io::Cursor::new(PAYLOAD);
            fs.create_file(
                &root,
                "foo",
                &mut data,
                PAYLOAD.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("create foo on HFSX must succeed");

            fs.sync_metadata().expect("sync");
            // Both must list separately.
            let entries = fs.list_directory(&root).expect("list");
            let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
            assert!(names.contains(&"Foo"), "Foo missing: {names:?}");
            assert!(names.contains(&"foo"), "foo missing: {names:?}");
        }

        // ---- HFS+, case-folding: second create rejects. ----
        {
            let mut img = create_blank_hfsplus(32 * 1024 * 1024, 4096, "HFSPLUS", false);
            let cursor = std::io::Cursor::new(&mut img);
            let mut fs = HfsPlusFilesystem::open(cursor, 0).expect("open hfs+");
            assert!(
                !fs.case_sensitive(),
                "plain HFS+ blank must be case-folding"
            );
            fs.prepare_for_edit().expect("prepare");
            let root = fs.root().expect("root");

            let mut data = std::io::Cursor::new(PAYLOAD);
            fs.create_file(
                &root,
                "Foo",
                &mut data,
                PAYLOAD.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("create Foo");

            let mut data = std::io::Cursor::new(PAYLOAD);
            let err = fs
                .create_file(
                    &root,
                    "foo",
                    &mut data,
                    PAYLOAD.len() as u64,
                    &CreateFileOptions::default(),
                )
                .expect_err("create foo must fail on case-folding HFS+");
            match err {
                FilesystemError::AlreadyExists(_) => {}
                other => panic!("expected AlreadyExists, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_clone_capture_carries_xattrs_byte_equal() {
        // Step 14: SourceCatalogSnapshot::capture must populate
        // SourceFileSnapshot::xattrs / SourceDirSnapshot::xattrs with the
        // inline records found in the attributes B-tree, byte-for-byte.
        //
        // Seed image already places an inline `com.apple.FinderInfo` xattr
        // on a sentinel CNID. We attach a second key on the same CNID via
        // `set_xattr`, sync, then graft a thread+file record into the
        // catalog so the walk associates that CNID with a real file —
        // capture should surface both inline values verbatim.
        let cnid = 99u32;
        let seed_value: Vec<u8> = (0..32u8).collect();
        let extra_value: Vec<u8> = b"\x00bplist00 demo".to_vec();
        let img = make_editable_hfsplus_image_with_inline_xattr(cnid, &seed_value);

        // Open editable, attach a second xattr to the sentinel cnid, attach an
        // xattr to an existing directory (CNID 2 = root), and sync.
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        fs.prepare_for_edit().unwrap();
        fs.set_xattr(cnid, "com.apple.metadata:demo", &extra_value)
            .expect("set extra xattr on sentinel cnid");
        fs.set_xattr(2u32, "com.apple.FinderInfo", &seed_value)
            .expect("set xattr on root dir");
        // Create a real file so the snapshot walk has a file row whose CNID
        // equals our sentinel — we relocate the captured xattrs onto it
        // by overriding the new file's catalog cnid is non-trivial, so
        // instead we capture and just look up by cnid directly.
        let root = fs.root().expect("root");
        let mut data = std::io::Cursor::new(b"hi".as_slice());
        fs.create_file(
            &root,
            "carrier.txt",
            &mut data,
            2,
            &CreateFileOptions::default(),
        )
        .expect("create_file");
        fs.sync_metadata().unwrap();
        let img2 = fs.reader.into_inner();

        let mut cursor2 = std::io::Cursor::new(img2);
        let mut fs2 = HfsPlusFilesystem::open(&mut cursor2, 0).unwrap();
        let snap = crate::hfsplus_clone::SourceCatalogSnapshot::capture(&mut fs2).expect("capture");

        // The freshly-created file should snapshot with no xattrs (we never
        // attached any to its CNID).
        let carrier = snap
            .files
            .iter()
            .find(|f| f.name == "carrier.txt")
            .expect("carrier file in snapshot");
        assert!(
            carrier.xattrs.is_empty(),
            "fresh file should have no xattrs, got {}",
            carrier.xattrs.len()
        );

        // The root dir snapshot must carry the xattr we attached.
        let root_dir = snap
            .dirs
            .iter()
            .find(|d| d.cnid == 2)
            .expect("root dir in snapshot");
        assert_eq!(root_dir.xattrs.len(), 1, "expected 1 xattr on root dir");
        assert_eq!(root_dir.xattrs[0].name, "com.apple.FinderInfo");
        match &root_dir.xattrs[0].kind {
            XattrKind::Inline(bytes) => assert_eq!(bytes, &seed_value),
            other => panic!("expected inline FinderInfo on root, got {other:?}"),
        }

        // Attributes B-tree still carries the sentinel cnid's two records;
        // verify directly via list_xattrs (capture only attaches xattrs to
        // catalog rows it walks, and the sentinel cnid is not catalog-rooted).
        let mut sentinel = fs2.list_xattrs(cnid).expect("list_xattrs sentinel");
        sentinel.sort_by(|a, b| a.name.cmp(&b.name));
        assert_eq!(sentinel.len(), 2, "sentinel should carry 2 xattrs");
        let mut want: Vec<(String, Vec<u8>)> = vec![
            ("com.apple.FinderInfo".into(), seed_value.clone()),
            ("com.apple.metadata:demo".into(), extra_value.clone()),
        ];
        want.sort_by(|a, b| a.0.cmp(&b.0));
        for (rec, (wn, wv)) in sentinel.iter().zip(want.iter()) {
            assert_eq!(rec.name, *wn);
            match &rec.kind {
                XattrKind::Inline(bytes) => assert_eq!(bytes, wv),
                other => panic!("expected inline, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_hfsplus_editable_open_and_free_space() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();
        assert_eq!(fs.fs_type(), "HFS+");
        let free = fs.free_space().unwrap();
        assert!(free > 0);
        // 250 free blocks × 4096 = 1,024,000
        assert_eq!(free, 250 * 4096);
    }

    #[test]
    fn test_hfsplus_defragmented_minimum_size() {
        // The synthetic image has 256 blocks of 4096 bytes total, with 6
        // blocks allocated near the front (VH/bitmap/catalog) and 250 free.
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

        let total = fs.total_size();
        let in_place = fs.last_data_byte().unwrap();
        let defrag = fs.defragmented_minimum_size().unwrap();

        assert_eq!(total, 256 * 4096);
        // Last allocated block is 5 (bits 0..=5 set in bitmap byte 0), plus
        // one block for the alternate VH at the new end: (5+1+1) * 4096.
        assert_eq!(in_place, 7 * 4096);
        // Defrag = (used + catalog_total_blocks*3) blocks * block_size +
        // 1024 alt-VH, rounded up. Synthetic image's catalog_total_blocks
        // is 4 → delta is 12 → 6 + 12 = 18 user blocks + alt-VH = 19.
        assert_eq!(defrag, 19 * 4096);
        assert!(defrag <= total);
    }

    /// R-078: with blocks of 1 KiB or more only the last block is the alternate header's.
    #[test]
    fn last_data_byte_counts_the_block_before_the_alternate_header() {
        let mut img = make_editable_hfsplus_image();
        let block_size = 4096usize;
        let total = 256u32;
        // Block 254 is the last one before the alternate header's block.
        let b = total - 2;
        img[block_size + (b / 8) as usize] |= 0x80 >> (b % 8);
        let mut fs = HfsPlusFilesystem::open(std::io::Cursor::new(img), 0).unwrap();
        assert_eq!(fs.last_data_byte().unwrap(), 256 * 4096);
    }

    #[test]
    fn test_hfsplus_defragmented_min_smaller_on_fragmented() {
        // Take the synthetic image and forge an extra allocation near the END
        // of the bitmap. The in-place trim point must hug the tail; the
        // defragmented minimum must reflect *only* the allocated count, not
        // the position — that's the whole point of the metric.
        let mut img = make_editable_hfsplus_image();
        let block_size = 4096usize;
        // Mark block 200 allocated (MSB-first bitmap, byte index 25, bit 0
        // -> shift 7 to set the most-significant bit).
        let bitmap_byte = block_size + 25; // bitmap lives in block 1
        img[bitmap_byte] |= 0b1000_0000;
        // Reflect the change in the VH so the defragmented calc sees one
        // fewer free block.
        let free_off = 1024 + 48;
        let free = BigEndian::read_u32(&img[free_off..free_off + 4]);
        BigEndian::write_u32(&mut img[free_off..free_off + 4], free - 1);
        // Mirror the change to the alternate VH at the tail.
        let image_size = img.len();
        let alt_free_off = image_size - 1024 + 48;
        BigEndian::write_u32(&mut img[alt_free_off..alt_free_off + 4], free - 1);

        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

        let in_place = fs.last_data_byte().unwrap();
        let defrag = fs.defragmented_minimum_size().unwrap();

        // In-place trim hugs the new tail allocation plus the alternate-VH
        // block: (200+1+1)*4096.
        assert_eq!(in_place, 202 * 4096);
        // Defrag: (7 used + 12 catalog-growth) blocks * 4096 + 1024 alt-VH,
        // rounded up = 20 blocks. Still well under in_place (201 blocks).
        assert_eq!(defrag, 20 * 4096);
        assert!(defrag < in_place);
    }

    #[test]
    fn test_hfsplus_editable_create_file_and_read() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"Hello, HFS+ World!";
        let mut data_reader = std::io::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 we can list and find it
        let entries = fs.list_directory(&root).unwrap();
        assert!(entries.iter().any(|e| e.name == "test.txt"));

        // Verify we can read it back
        let read_back = fs.read_file(&fe, 1024).unwrap();
        assert_eq!(&read_back, test_data);
    }

    #[test]
    fn test_hfsplus_editable_create_directory() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

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

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

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

    #[test]
    fn test_hfsplus_editable_delete_file() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

        let root = fs.root().unwrap();
        let test_data = b"delete me";
        let mut data_reader = std::io::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();

        // Delete it
        fs.delete_entry(&root, &fe).unwrap();

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

        // Verify free space recovered
        let free_after = fs.free_space().unwrap();
        assert!(free_after > free_before);
    }

    #[test]
    fn test_hfsplus_editable_duplicate_name_rejected() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

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

        // Second creation should fail
        let mut r2 = std::io::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_hfsplus_editable_blessed_folder() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::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 Folder", &options)
            .unwrap();

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

        // Verify it's blessed
        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 Folder");
    }

    #[test]
    fn test_hfsplus_editable_type_creator_auto_detect() {
        let img = make_editable_hfsplus_image();
        let cursor = std::io::Cursor::new(img);
        let mut fs = HfsPlusFilesystem::open(cursor, 0).unwrap();

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

        // "txt" extension should auto-detect to TEXT/ttxt
        assert!(fe.type_code.is_some());
        assert_eq!(fe.type_code, Some(*b"TEXT"));
    }

    #[test]
    fn test_hfsplus_catalog_variable_index_keys_grow_multilevel() {
        // P1 (docs/hfsplus_btree_growth_plan.md §4a): the HFS+ catalog B-tree
        // must grow past a single index level without corrupting. The shared
        // split/grow helpers used to force the classic 1-byte-length, fixed-0x25
        // index-key shape onto HFS+ records, so the first leaf split produced a
        // malformed separator (it read the high byte of the 2-byte key length as
        // the whole length) and descent misrouted — the "leaves must be strictly
        // ascending" / mis-routed-descent corruption. With
        // `BTreeKeyFormat::HFSPLUS_CATALOG` the separator is the child's
        // variable-length 2-byte key, verbatim.
        //
        // Driven at the catalog-buffer level through the exact shared
        // `btree_insert_full` path `insert_catalog_record` uses. node_size is
        // 512 (vs the production 4096) so a few thousand multi-parent records
        // reach depth >= 3 in a < 1 MiB buffer; the machinery is node-size
        // agnostic. The volume-level fsck gate lands in P2 once blank catalogs
        // are sized to hold the records (today a blank catalog is only 4 nodes).
        use crate::hfs_common::{
            btree_find_record, btree_insert_full, BTreeHeader, BTreeKeyFormat,
        };
        use byteorder::{BigEndian, ByteOrder};
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;

        let node_size = 512usize;
        // A single-node bitmap (512-byte node) covers ~1872 nodes, so stay under
        // that — no map nodes needed, matching a real blank-built tree.
        let total_nodes = 1800u32;
        let mut buf = vec![0u8; total_nodes as usize * node_size];
        write_blank_btree_header_node(
            &mut buf[0..node_size],
            node_size,
            /* leaf_records= */ 0,
            total_nodes,
            /* free_nodes= */ total_nodes - 2,
            /* max_key_len= */ 516,
            KEY_COMPARE_CASE_FOLDING,
        );
        write_empty_leaf_node(&mut buf[node_size..2 * node_size]);

        let kf = BTreeKeyFormat::HFSPLUS_CATALOG;
        let cmp = |a: &[u8], b: &[u8]| Fs::catalog_compare(a, b, false);

        // ~2500 files in shuffled key order (multiplicative hash is a bijection
        // mod 2^32 — unique names that land mid-leaf, not appended) sprayed
        // across 50 parent directories, so inserts exercise every leaf and
        // index split, not just tail appends.
        const DIRS: u32 = 50;
        const N: u32 = 2500;
        let mut inserted: Vec<(u32, String)> = Vec::with_capacity(N as usize);
        for i in 0..N {
            let hash = i.wrapping_mul(2_654_435_761);
            let parent = 16 + (hash % DIRS); // arbitrary distinct parent CNIDs
            let name = format!("f{hash:08x}");
            let mut rec = Fs::build_catalog_key(parent, &name);
            // Append filler so records have a realistic size (the compare only
            // reads the leading key portion; the body is irrelevant here).
            rec.extend_from_slice(&[0u8; 40]);
            btree_insert_full(&mut buf, &rec, &kf, &cmp)
                .unwrap_or_else(|e| panic!("insert #{i} (parent {parent}, {name}): {e}"));
            inserted.push((parent, name));
        }

        // The tree must have grown past a single index level.
        let header = BTreeHeader::read(&buf);
        assert!(
            header.depth >= 3,
            "catalog did not reach depth >= 3 (got {}); test needs a deeper tree to \
             exercise index-node splits",
            header.depth
        );
        assert_eq!(
            header.leaf_records, N,
            "leaf_records header count drifted from inserts"
        );

        // (a) Every leaf key, walked in sibling-chain order, is strictly
        // ascending — the direct symptom of a malformed separator was
        // out-of-order leaves.
        let mut keys: Vec<Vec<u8>> = Vec::with_capacity(N as usize);
        crate::hfs_common::walk_leaf_records::<(), _>(
            &buf,
            header.first_leaf_node,
            node_size,
            |_n, _r, _o, rec| {
                let kl = BigEndian::read_u16(&rec[0..2]) as usize;
                keys.push(rec[..(2 + kl).min(rec.len())].to_vec());
                None
            },
        );
        assert_eq!(
            keys.len(),
            N as usize,
            "leaf walk recovered {} of {N} records — chain is broken or has cycles",
            keys.len()
        );
        for w in keys.windows(2) {
            assert_eq!(
                cmp(&w[0], &w[1]),
                std::cmp::Ordering::Less,
                "catalog leaves are not strictly ascending — separator/descent corruption"
            );
        }

        // (b) Every inserted record is findable by a root-to-leaf descent, i.e.
        // every index separator routes correctly at every level. (A nested `fn`
        // rather than a closure so it satisfies the `for<'a> Fn(&'a [u8]) ->
        // &'a [u8]` bound `btree_find_record` requires.)
        fn key_extract(rec: &[u8]) -> &[u8] {
            let kl = BigEndian::read_u16(&rec[0..2]) as usize;
            &rec[..(2 + kl).min(rec.len())]
        }
        for (parent, name) in &inserted {
            let search = Fs::build_catalog_key(*parent, name);
            let (found, _chain) = btree_find_record(&buf, &header, &search, &key_extract, &cmp);
            assert!(
                found.is_some(),
                "record (parent {parent}, {name}) not findable by descent — misrouted index"
            );
        }
    }

    #[test]
    fn test_hfsplus_blank_sized_catalog_20k_inserts_fsck_clean() {
        // P2 (docs/hfsplus_btree_growth_plan.md §4c): a fresh HFS+ volume sized
        // to hold the records accepts >= 20k incremental catalog inserts across
        // many parent dirs and stays fsck-clean — the volume-level gate P1
        // deferred. A blank catalog used to be a fixed 4 nodes (exhausting after
        // ~24 files); it is now volume-scaled, and `create_blank_hfsplus_sized`
        // lets this test pin a large catalog into a modest 64 MiB image instead
        // of needing a multi-GiB volume to scale into.
        use crate::hfs_common::BTreeHeader;
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;

        // 64 MiB volume; catalog pinned to 16 MiB (~4096 nodes @ 4096) — ample
        // headroom for 20k file records at the byte-split's ~69% leaf occupancy.
        let img =
            create_blank_hfsplus_sized(64 * 1024 * 1024, 4096, "PutShuffle", false, 16 << 20, 0);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();

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

        // 20k files in shuffled key order (multiplicative hash is a bijection
        // mod 2^32 — unique names landing mid-leaf, not appended), sprayed across
        // the directories. Insert the catalog records directly: `create_file`
        // snapshots the whole catalog per call for rollback, which would make a
        // 20k-record build O(N * catalog_size). fsck doesn't require per-file
        // thread records (only flags orphaned threads), so — like the classic
        // HFS scaling test — we insert just the file records and fix up counts.
        let n: u32 = 20_000;
        let mut per_dir = vec![0i32; DIRS as usize];
        let empty_fork = ForkData::empty();
        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);
            if !kr.len().is_multiple_of(2) {
                kr.push(0);
            }
            kr.extend_from_slice(&Fs::build_file_record_with_dates(
                base_cnid + i,
                &empty_fork,
                &empty_fork,
                &[0u8; 4],
                &[0u8; 4],
                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 maintains so fsck's cross-checks
        // (file_count, next_catalog_id, per-dir valence) pass.
        fs.vh.file_count += n;
        fs.vh.next_catalog_id = base_cnid + n;
        for (d, &cnt) in per_dir.iter().enumerate() {
            fs.update_parent_valence(dir_ids[d], cnt).unwrap();
        }

        // The catalog must have grown several index levels...
        let h = BTreeHeader::read(fs.catalog_data());
        assert!(
            h.depth >= 3,
            "catalog depth {} < 3 after 20k inserts",
            h.depth
        );
        // ...without a premature DiskFull (every insert above succeeded).

        // No IndexSiblingLinkBroken / order / count damage at scale.
        let result = fs.fsck().unwrap().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck found {} errors after 20k inserts: {:?}",
            result.errors.len(),
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hfsplus_catalog_grows_map_nodes_past_cap_phase_c() {
        // §4b Phase C (docs/todo_hfsplus_fork_growth.md): once a B-tree fork
        // grows past the header node's bitmap capacity ((node_size-256)*8 =
        // 30,720 nodes @ 4096), a map node (BTNodeKind=2) must be appended to
        // the node-allocation bitmap chain so the new node indices are
        // addressable. Pre-size the catalog just under the cap, then grow a few
        // times to cross it — exercising the map-node append without needing
        // the millions of records a from-scratch fill would take.
        use crate::hfs_common::{btree_bitmap_segments, BTreeHeader};
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;
        let node_size = 4096usize;
        let header_cap = ((node_size - 256) * 8) as u32; // 30,720

        // Catalog pinned to ~16 nodes below the cap; 180 MiB volume holds it.
        let min_catalog = (header_cap - 16) * node_size as u32;
        let img =
            create_blank_hfsplus_sized(180 * 1024 * 1024, 4096, "MapCap", false, min_catalog, 0);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();

        let start = BTreeHeader::read(fs.catalog_data()).total_nodes;
        assert!(
            start <= header_cap && start > header_cap - 64,
            "blank catalog {start} not near cap"
        );
        // No map node yet — the whole bitmap lives in the header node.
        assert_eq!(
            btree_bitmap_segments(fs.catalog_data(), node_size).len(),
            1,
            "fresh near-cap catalog should have no map nodes"
        );

        // Grow until we cross the header bitmap cap.
        let mut guard = 0;
        while BTreeHeader::read(fs.catalog_data()).total_nodes <= header_cap {
            fs.grow_btree_fork(BTreeFork::Catalog).unwrap();
            guard += 1;
            assert!(guard < 64, "too many grows to cross the cap");
        }
        let h = BTreeHeader::read(fs.catalog_data());
        assert!(
            h.total_nodes > header_cap,
            "did not cross the cap: {}",
            h.total_nodes
        );
        // A map-node segment must now exist in the bitmap chain.
        let segs = btree_bitmap_segments(fs.catalog_data(), node_size);
        assert!(
            segs.len() >= 2,
            "expected a map-node segment after crossing the cap, got {} segment(s)",
            segs.len()
        );

        // fsck-clean with the map node in place.
        fs.sync_metadata().unwrap();
        let result = fs.fsck().unwrap().unwrap();
        assert!(
            result.errors.is_empty(),
            "fsck after map-node grow: {:?}",
            result
                .errors
                .iter()
                .take(8)
                .map(|e| &e.message)
                .collect::<Vec<_>>()
        );

        // Reopen re-reads the grown fork and the map chain.
        let img = fs.reader.get_ref().clone();
        if let Ok(path) = std::env::var("RB_EMIT_MAPC_IMAGE") {
            std::fs::write(&path, &img).unwrap();
        }
        let fs2 = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        assert_eq!(
            BTreeHeader::read(fs2.catalog_data()).total_nodes,
            h.total_nodes,
            "reopen lost grown nodes"
        );
        assert!(
            btree_bitmap_segments(fs2.catalog_data(), node_size).len() >= 2,
            "reopen lost the map node"
        );
    }

    #[test]
    fn test_hfsplus_catalog_grow_spills_to_overflow_phase_b() {
        // §4b Phase B (docs/todo_hfsplus_fork_growth.md): real `create_file`
        // calls interleave a data-block allocation with each catalog grow, so
        // contiguous tail growth fails and the catalog fork fragments. Once it
        // exhausts its 8 inline extents, further growth spills into the
        // extents-overflow B-tree (keyed by the catalog's reserved CNID 4) and
        // is persisted by the overflow-aware write path. The volume stays
        // readable + fsck-clean, and a reopen re-reads the > 8-extent fork.
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;
        let img = create_blank_hfsplus_sized(16 * 1024 * 1024, 4096, "SpillVol", false, 0, 0);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();
        let root = fs.root().unwrap();
        let mut dirs = Vec::new();
        for d in 0..20 {
            dirs.push(
                fs.create_directory(&root, &format!("d{d}"), &Default::default())
                    .unwrap(),
            );
        }
        const N: u32 = 1200;
        for i in 0..N {
            let d = &dirs[(i % 20) as usize];
            let mut data = std::io::Cursor::new(vec![b'x']);
            fs.create_file(
                d,
                &format!("f{i:05}.txt"),
                &mut data,
                1,
                &Default::default(),
            )
            .unwrap_or_else(|e| panic!("create_file #{i} (grow+spill should cover it): {e}"));
        }

        // The catalog fork saturated its 8 inline extents and spilled the rest
        // into the extents-overflow B-tree.
        let inline: u32 = fs
            .vh
            .catalog_file
            .extents
            .iter()
            .map(|e| e.block_count)
            .sum();
        let inline_count = fs
            .vh
            .catalog_file
            .extents
            .iter()
            .filter(|e| e.block_count != 0)
            .count();
        assert_eq!(
            inline_count, 8,
            "catalog should have filled all 8 inline extents"
        );
        assert!(
            fs.vh.catalog_file.total_blocks > inline,
            "catalog total_blocks {} should exceed inline-extent blocks {inline} (overflow used)",
            fs.vh.catalog_file.total_blocks
        );

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

        // Reopen re-reads the > 8-extent catalog fork (inline + overflow) and
        // every file is still enumerable.
        let img = fs.reader.get_ref().clone();
        if let Ok(path) = std::env::var("RB_EMIT_SPILL_IMAGE") {
            std::fs::write(&path, &img).unwrap();
        }
        let mut fs2 = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        let r2 = fs2.root().unwrap();
        let mut total = 0;
        for de in fs2.list_directory(&r2).unwrap() {
            if de.is_directory() {
                total += fs2.list_directory(&de).unwrap().len();
            }
        }
        assert_eq!(total as u32, N, "reopen lost files: {total} != {N}");
    }

    /// H8: with blocks larger than nodes a grow added one block per node,
    /// twice (or four times) what the nodes occupy, on every grow.
    /// H7: the alternate volume header went to total_blocks * block_size - 1024;
    /// fsck_hfs and the Mac read 1024 bytes before the partition end.
    #[test]
    fn the_alternate_volume_header_follows_the_partition_end_when_known() {
        use disk_core::filesystem::{CreateFileOptions, EditableFilesystem, Filesystem};
        const VOLUME: u64 = 8 * 1024 * 1024;
        const PARTITION: u64 = VOLUME + 6 * 1024;
        let mut img = create_blank_hfsplus(VOLUME, 4096, "Slack", false);
        img.resize(PARTITION as usize, 0);
        {
            let mut fs =
                HfsPlusFilesystem::open_sized(std::io::Cursor::new(&mut img), 0, Some(PARTITION))
                    .unwrap();
            fs.prepare_for_edit().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"H+",
            "alternate volume header missing at the partition end"
        );
        assert_eq!(primary, alt);
    }

    /// H14: an imported file's Finder flags had no way into create_file.
    #[test]
    fn create_file_writes_the_finder_flags_it_is_given() {
        use disk_core::filesystem::{CreateFileOptions, EditableFilesystem, Filesystem};
        let mut img = create_blank_hfsplus(8 * 1024 * 1024, 4096, "Flags", false);
        let mut fs = HfsPlusFilesystem::open(std::io::Cursor::new(&mut img), 0).unwrap();
        fs.prepare_for_edit().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 a_grow_allocates_the_blocks_the_new_nodes_occupy() {
        // 4 KiB nodes in 8 KiB blocks: 8 nodes are 4 blocks, not 8.
        assert_eq!(btree_grow_blocks(10, 8, 4096, 8192), 4);
        // 1 KiB nodes in 4 KiB blocks: 8 nodes are 2 blocks.
        assert_eq!(btree_grow_blocks(4, 8, 1024, 4096), 2);
        // An odd node count leaves half a block of slack that the grow uses first.
        assert_eq!(btree_grow_blocks(11, 8, 4096, 8192), 4);
        assert_eq!(btree_grow_blocks(11, 1, 4096, 8192), 0);
        // Nodes larger than blocks keep the old one-node-many-blocks answer.
        assert_eq!(btree_grow_blocks(10, 8, 4096, 512), 64);
        assert_eq!(btree_grow_blocks(10, 8, 4096, 4096), 8);
    }

    #[test]
    fn test_hfsplus_catalog_grows_fork_on_full_phase_a() {
        // §4b Phase A (docs/todo_hfsplus_fork_growth.md): a volume whose catalog
        // fork is *too small* for its eventual record count grows the fork in
        // place through live inserts — no spurious DiskFull while the volume has
        // free blocks — and stays fsck-clean. Contiguous tail growth keeps the
        // catalog fork at a single extent. A reopen re-reads the grown fork.
        use crate::hfs_common::BTreeHeader;
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;

        // 16 MiB volume, minimal (volume-scaled, ~21-node) catalog. Inserting
        // far more records than that forces many grows.
        let img = create_blank_hfsplus_sized(16 * 1024 * 1024, 4096, "GrowVol", false, 0, 0);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();

        let start_nodes = BTreeHeader::read(fs.catalog_data()).total_nodes;

        const DIRS: u32 = 20;
        let root = fs.root().unwrap();
        let mut dir_ids = Vec::with_capacity(DIRS as usize);
        for d in 0..DIRS {
            let de = fs
                .create_directory(&root, &format!("dir{d:03}"), &Default::default())
                .unwrap();
            dir_ids.push(de.location as u32);
        }
        let base_cnid = fs.vh.next_catalog_id;

        let n: u32 = 6_000;
        let mut per_dir = vec![0i32; DIRS as usize];
        let empty_fork = ForkData::empty();
        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);
            if !kr.len().is_multiple_of(2) {
                kr.push(0);
            }
            kr.extend_from_slice(&Fs::build_file_record_with_dates(
                base_cnid + i,
                &empty_fork,
                &empty_fork,
                &[0u8; 4],
                &[0u8; 4],
                None,
                0,
            ));
            fs.insert_catalog_record(&kr)
                .unwrap_or_else(|e| panic!("insert #{i} into dir{d} (grow should cover it): {e}"));
            per_dir[d] += 1;
        }
        fs.vh.file_count += n;
        fs.vh.next_catalog_id = base_cnid + n;
        for (d, &cnt) in per_dir.iter().enumerate() {
            fs.update_parent_valence(dir_ids[d], cnt).unwrap();
        }

        // The fork grew (each grow adds >= 8 nodes; >= 2 grows expected here).
        let end_nodes = BTreeHeader::read(fs.catalog_data()).total_nodes;
        assert!(
            end_nodes >= start_nodes + 16,
            "catalog total_nodes only went {start_nodes} -> {end_nodes}; expected >= 2 grows"
        );
        // Contiguous tail growth keeps the catalog fork at a single extent.
        let cat_extents = fs
            .vh
            .catalog_file
            .extents
            .iter()
            .filter(|e| e.block_count != 0)
            .count();
        assert_eq!(
            cat_extents, 1,
            "contiguous tail growth should keep the catalog fork at 1 extent, got {cat_extents}"
        );

        // Persist the grown fork, bitmap, and VH, then fsck the result.
        fs.sync_metadata().unwrap();

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

        // Reopen re-reads the grown fork (proves the fork extents + header
        // persisted) and every record is still findable.
        let img = fs.reader.get_ref().clone();
        // Optionally emit the grown image so a Mac can fsck_hfs it (the real
        // §4b acceptance test): set RB_EMIT_GROW_IMAGE=/path.
        if let Ok(path) = std::env::var("RB_EMIT_GROW_IMAGE") {
            std::fs::write(&path, &img).unwrap();
        }
        let mut fs2 = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        let reopened_nodes = BTreeHeader::read(fs2.catalog_data()).total_nodes;
        assert_eq!(reopened_nodes, end_nodes, "reopen lost grown nodes");
        let r2 = fs2.root().unwrap();
        let dirs = fs2.list_directory(&r2).unwrap();
        assert_eq!(dirs.len(), DIRS as usize, "reopen lost directories");
    }

    #[test]
    fn test_hfsplus_extents_overflow_grows_multilevel() {
        // P3 (docs/hfsplus_btree_growth_plan.md): the extents-overflow B-tree —
        // 2-byte ("big") keys with *fixed* 10-byte index separators — must split
        // past a single leaf level. It was pinned depth-1 because the shared
        // helpers forced the classic key shape; it now threads
        // `BTreeKeyFormat::HFSPLUS_EXTENTS`. Driven through the same
        // `btree_insert_full` machinery `insert_extents_overflow_record` uses.
        use crate::hfs_common::{
            btree_find_record, btree_insert_full, BTreeHeader, BTreeKeyFormat,
        };
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;

        let node_size = 512usize;
        let total_nodes = 1800u32;
        let mut buf = vec![0u8; total_nodes as usize * node_size];
        write_blank_btree_header_node(
            &mut buf[0..node_size],
            node_size,
            0,
            total_nodes,
            total_nodes - 2,
            /* max_key_len= */ 10,
            /* key_compare_type= */ 0,
        );
        write_empty_leaf_node(&mut buf[node_size..2 * node_size]);

        let kf = BTreeKeyFormat::HFSPLUS_EXTENTS;
        // 600 overflow records keyed by distinct shuffled fileIDs (the multiplier
        // is odd, so it's a bijection mod 2^32 — distinct i give distinct keys
        // that land mid-leaf, not appended).
        const N: u32 = 600;
        let mut ids: Vec<u32> = Vec::with_capacity(N as usize);
        for i in 0..N {
            let file_id = i.wrapping_mul(2_654_435_761);
            let rec = Fs::build_extents_overflow_record(file_id, 0, 8, &[]);
            btree_insert_full(&mut buf, &rec, &kf, &Fs::extents_compare)
                .unwrap_or_else(|e| panic!("extents insert #{i} (file {file_id}): {e}"));
            ids.push(file_id);
        }

        let header = BTreeHeader::read(&buf);
        assert!(
            header.depth >= 2,
            "extents-overflow tree stayed depth {} — split past a leaf level failed",
            header.depth
        );
        assert_eq!(header.leaf_records, N);

        let mut recs: Vec<Vec<u8>> = Vec::with_capacity(N as usize);
        crate::hfs_common::walk_leaf_records::<(), _>(
            &buf,
            header.first_leaf_node,
            node_size,
            |_n, _r, _o, r| {
                recs.push(r.to_vec());
                None
            },
        );
        assert_eq!(recs.len(), N as usize, "leaf walk lost records");
        for w in recs.windows(2) {
            assert_eq!(
                Fs::extents_compare(&w[0], &w[1]),
                std::cmp::Ordering::Less,
                "extents-overflow leaves out of order — bad separator"
            );
        }

        // The extents key portion is always the fixed 12 bytes (2-byte len + 10).
        fn ext_key(rec: &[u8]) -> &[u8] {
            &rec[..12.min(rec.len())]
        }
        let ext_cmp = |a: &[u8], b: &[u8]| Fs::extents_compare(a, b);
        for &file_id in &ids {
            let search = Fs::build_extents_overflow_record(file_id, 0, 8, &[]);
            let (found, _) = btree_find_record(&buf, &header, &search, &ext_key, &ext_cmp);
            assert!(
                found.is_some(),
                "extents record for file {file_id} not findable"
            );
        }
    }

    #[test]
    fn test_hfsplus_attributes_grows_multilevel() {
        // P3: the attributes B-tree — 2-byte keys with *variable*-length index
        // separators — splits past one leaf level via
        // `BTreeKeyFormat::HFSPLUS_ATTRIBUTES`, the same path `insert_xattr_record`
        // uses. (P1 wired the descriptor in; this proves the attribute key layout,
        // distinct from the catalog's, routes correctly at every level.)
        use crate::hfs_common::{
            btree_find_record, btree_insert_full, BTreeHeader, BTreeKeyFormat,
        };
        use byteorder::{BigEndian, ByteOrder};
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;

        let node_size = 512usize;
        let total_nodes = 1800u32;
        let mut buf = vec![0u8; total_nodes as usize * node_size];
        write_blank_btree_header_node(
            &mut buf[0..node_size],
            node_size,
            0,
            total_nodes,
            total_nodes - 2,
            /* max_key_len= */ 264,
            /* key_compare_type= */ 0,
        );
        write_empty_leaf_node(&mut buf[node_size..2 * node_size]);

        let kf = BTreeKeyFormat::HFSPLUS_ATTRIBUTES;
        const N: u32 = 600;
        let value = [0xABu8; 8];
        let mut cnids: Vec<u32> = Vec::with_capacity(N as usize);
        for i in 0..N {
            let cnid = i.wrapping_mul(2_654_435_761);
            let rec = Fs::build_inline_attr_record(cnid, "xattr", &value);
            btree_insert_full(&mut buf, &rec, &kf, &Fs::attr_compare)
                .unwrap_or_else(|e| panic!("attr insert #{i} (cnid {cnid}): {e}"));
            cnids.push(cnid);
        }

        let header = BTreeHeader::read(&buf);
        assert!(
            header.depth >= 2,
            "attributes tree stayed depth {} — split past a leaf level failed",
            header.depth
        );
        assert_eq!(header.leaf_records, N);

        let mut recs: Vec<Vec<u8>> = Vec::with_capacity(N as usize);
        crate::hfs_common::walk_leaf_records::<(), _>(
            &buf,
            header.first_leaf_node,
            node_size,
            |_n, _r, _o, r| {
                recs.push(r.to_vec());
                None
            },
        );
        assert_eq!(recs.len(), N as usize, "leaf walk lost records");
        for w in recs.windows(2) {
            assert_eq!(
                Fs::attr_compare(&w[0], &w[1]),
                std::cmp::Ordering::Less,
                "attributes leaves out of order — bad separator"
            );
        }

        fn attr_key(rec: &[u8]) -> &[u8] {
            let kl = BigEndian::read_u16(&rec[0..2]) as usize;
            &rec[..(2 + kl).min(rec.len())]
        }
        let attr_cmp = |a: &[u8], b: &[u8]| Fs::attr_compare(a, b);
        for &cnid in &cnids {
            let search = Fs::build_inline_attr_record(cnid, "xattr", &value);
            let (found, _) = btree_find_record(&buf, &header, &search, &attr_key, &attr_cmp);
            assert!(found.is_some(), "attr record for cnid {cnid} not findable");
        }
    }

    #[test]
    fn test_hfsplus_fragmented_file_splits_extents_overflow_btree_real_path() {
        // P3 real-path integration: a heavily fragmented file produces enough
        // extents-overflow records to split that B-tree past a single leaf level
        // through the real `insert_extents_overflow_record`, and the file reads
        // back byte-for-byte through the resulting multi-level tree. (Read-back,
        // not fsck, because the all-used-then-free-singletons bitmap trick used to
        // force fragmentation leaves the bitmap deliberately over-allocated; the
        // point here is the overflow B-tree's split + read path, which P3 enabled.)
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;
        // Extents-overflow tree pinned to 256 KiB (64 nodes @ 4096) so it has room
        // to split — the 4-node default could not.
        let img = create_blank_hfsplus_sized(32 << 20, 4096, "Frag", false, 0, 256 << 10);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();

        // Force maximal fragmentation: mark every block used, then free isolated
        // single blocks (every other block) in the user region. A file of N blocks
        // must then use N one-block extents: 8 inline + (N-8) overflow extents =
        // ceil((N-8)/8) overflow records. 520 blocks -> 64 overflow records, well
        // past one 4096-byte extents leaf (~52 records), so the tree must split.
        fs.ensure_bitmap().unwrap();
        let block_size = fs.vh.block_size as usize;
        let n_blocks: u32 = 520;
        let first_free = fs.vh.next_allocation;
        {
            let bitmap = fs.bitmap.as_mut().unwrap();
            for b in bitmap.iter_mut() {
                *b = 0xFF;
            }
            let mut blk = first_free + 1;
            for _ in 0..n_blocks {
                bitmap_clear_bit_be(bitmap, blk);
                blk += 2; // a used block between each free one -> singletons
            }
        }
        fs.vh.free_blocks = n_blocks;

        let payload: Vec<u8> = (0..(n_blocks as usize * block_size))
            .map(|i| (i % 251) as u8)
            .collect();
        let mut reader = std::io::Cursor::new(payload.clone());
        let root = fs.root().unwrap();
        let entry = fs
            .create_file(
                &root,
                "frag.bin",
                &mut reader,
                payload.len() as u64,
                &CreateFileOptions::default(),
            )
            .expect("fragmented file create should succeed via a splitting overflow B-tree");

        // The extents-overflow tree must have grown past a single leaf level.
        let depth =
            crate::hfs_common::BTreeHeader::read(fs.extents_overflow_data.as_ref().unwrap()).depth;
        assert!(
            depth >= 2,
            "extents-overflow tree depth {depth} < 2 — 64 overflow records did not split it"
        );

        // The data fork is the expected single-block-extent shape...
        let cnid = entry.location as u32;
        let (data_fork, _rsrc) = fs.find_file_by_id(cnid).unwrap();
        assert_eq!(data_fork.total_blocks, n_blocks);

        // ...and reads back byte-for-byte through the multi-level overflow tree.
        let got = fs.read_file(&entry, payload.len() + 1).unwrap();
        assert_eq!(got.len(), payload.len());
        assert_eq!(
            got, payload,
            "fragmented read-back mismatch through split overflow tree"
        );
    }

    #[test]
    fn deleting_the_last_overflow_record_retires_the_extents_tree() {
        // fsck_hfs E_BadNode: the audit's H3 delete left the extents tree as a
        // depth-1 root leaf with no records, which Apple never writes.
        use crate::hfs_common::{btree_lonely_empty_leaves, BTreeHeader};
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;
        let img = create_blank_hfsplus_sized(32 << 20, 4096, "Retire", false, 0, 256 << 10);
        let mut fs = Fs::open(std::io::Cursor::new(img), 0).unwrap();
        fs.prepare_for_edit().unwrap();

        // Free singleton blocks only, so the file fragments into the overflow tree.
        fs.ensure_bitmap().unwrap();
        let block_size = fs.vh.block_size as usize;
        let n_blocks: u32 = 520;
        let first_free = fs.vh.next_allocation;
        {
            let bitmap = fs.bitmap.as_mut().unwrap();
            for b in bitmap.iter_mut() {
                *b = 0xFF;
            }
            let mut blk = first_free + 1;
            for _ in 0..n_blocks {
                bitmap_clear_bit_be(bitmap, blk);
                blk += 2;
            }
        }
        fs.vh.free_blocks = n_blocks;
        let payload: Vec<u8> = (0..(n_blocks as usize * block_size))
            .map(|i| (i % 251) as u8)
            .collect();
        let root = fs.root().unwrap();
        let entry = fs
            .create_file(
                &root,
                "frag.bin",
                &mut std::io::Cursor::new(payload.clone()),
                payload.len() as u64,
                &CreateFileOptions::default(),
            )
            .unwrap();
        let before = BTreeHeader::read(fs.extents_overflow_data.as_ref().unwrap());
        assert!(
            before.depth >= 2 && before.leaf_records > 0,
            "depth {} leaf_records {}",
            before.depth,
            before.leaf_records
        );

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

        let tree = fs.extents_overflow_data.as_ref().unwrap();
        let h = BTreeHeader::read(tree);
        assert_eq!((h.leaf_records, h.root_node, h.depth), (0, 0, 0));
        assert_eq!(
            h.free_nodes,
            h.total_nodes - 1,
            "only the header node stays"
        );
        // The hand-made bitmap above never reaches disk, so no fsck here; the
        // audit's verify-fs-macos.sh runs fsck_hfs on the real image instead.
        assert!(btree_lonely_empty_leaves(tree, h.node_size as usize).is_empty());
    }

    #[test]
    fn a_grow_moves_the_alternate_header_blocks_and_the_bitmap() {
        // fsck_hfs on the audit's H7 grow: "orphaned blocks" at the old tail,
        // "under-allocation" at the new one. The 2 KiB case also outgrows its
        // one-block allocation file, which has to move.
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;
        for (bs, old_mib, new_mib) in [(4096u32, 24u64, 30u64), (2048u32, 32u64, 64u64)] {
            let mut img = create_blank_hfsplus(old_mib << 20, bs, "Grow", false);
            img.resize((new_mib << 20) as usize, 0);
            let mut cur = std::io::Cursor::new(img);
            let mut log = |_: &str| {};
            resize_hfsplus_in_place(&mut cur, 0, new_mib << 20, &mut log).unwrap();

            let mut fs = Fs::open_sized(cur, 0, Some(new_mib << 20)).unwrap();
            let total = fs.vh.total_blocks;
            assert_eq!(total as u64, (new_mib << 20) / bs as u64, "bs {bs}");
            let bitmap = fs.read_allocation_bitmap_for_fsck().unwrap();
            let old_total = ((old_mib << 20) / bs as u64) as u32;
            for b in alt_vh_blocks(old_total, bs) {
                assert!(
                    !bitmap_test_bit_be(&bitmap, b),
                    "bs {bs}: old tail block {b} still marked"
                );
            }
            for b in alt_vh_blocks(total, bs) {
                assert!(
                    bitmap_test_bit_be(&bitmap, b),
                    "bs {bs}: new tail block {b} is free"
                );
            }
            let used = (0..total)
                .filter(|&b| bitmap_test_bit_be(&bitmap, b))
                .count() as u32;
            assert_eq!(fs.vh.free_blocks, total - used, "bs {bs}");
            assert!(
                fs.vh.allocation_file.total_blocks as u64 * bs as u64 * 8 >= total as u64,
                "bs {bs}: allocation file too small for {total} blocks"
            );
            let report = fs.fsck().unwrap().unwrap();
            assert!(
                report.errors.is_empty(),
                "bs {bs}: {:?}",
                report
                    .errors
                    .iter()
                    .map(|e| &e.message)
                    .take(4)
                    .collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn test_hfsplus_catalog_shuffled_inserts_pack_densely() {
        // P5 (docs/hfsplus_btree_growth_plan.md §4d): with the B*-style rotation
        // now on the HFS+ catalog insert path (insert_catalog_record ->
        // btree_insert_full), shuffled multi-dir inserts must pack leaves to
        // ~80%+ occupancy, matching the classic-HFS result — not the ~69% a plain
        // split leaves. Measured through the same btree_insert_full the live path
        // uses, with the HFSPLUS_CATALOG (variable-key) format.
        use crate::hfs_common::{btree_insert_full, BTreeHeader, BTreeKeyFormat};
        use byteorder::{BigEndian, ByteOrder};
        type Fs = HfsPlusFilesystem<std::io::Cursor<Vec<u8>>>;

        let node_size = 512usize;
        let total_nodes = 1800u32;
        let mut buf = vec![0u8; total_nodes as usize * node_size];
        write_blank_btree_header_node(
            &mut buf[0..node_size],
            node_size,
            0,
            total_nodes,
            total_nodes - 2,
            516,
            KEY_COMPARE_CASE_FOLDING,
        );
        write_empty_leaf_node(&mut buf[node_size..2 * node_size]);

        let kf = BTreeKeyFormat::HFSPLUS_CATALOG;
        let cmp = |a: &[u8], b: &[u8]| Fs::catalog_compare(a, b, false);
        const DIRS: u32 = 40;
        const N: u32 = 3000;
        for i in 0..N {
            let hash = i.wrapping_mul(2_654_435_761);
            let parent = 16 + (hash % DIRS);
            let name = format!("f{hash:08x}");
            let mut rec = Fs::build_catalog_key(parent, &name);
            rec.extend_from_slice(&[0u8; 40]);
            btree_insert_full(&mut buf, &rec, &kf, &cmp)
                .unwrap_or_else(|e| panic!("insert #{i}: {e}"));
        }

        // Average leaf occupancy across the whole leaf chain.
        let header = BTreeHeader::read(&buf);
        assert!(
            header.depth >= 3,
            "need a multi-level tree to judge packing"
        );
        let mut used_total = 0usize;
        let mut leaves = 0usize;
        let mut node = header.first_leaf_node;
        let mut seen = std::collections::HashSet::new();
        while node != 0 && seen.insert(node) {
            let off = node as usize * node_size;
            let num = BigEndian::read_u16(&buf[off + 10..off + 12]) as usize;
            // Records occupy 14..free_off; the offset table holds num+1 u16s.
            let free_off_pos = off + node_size - 2 * (num + 1);
            let free_off = BigEndian::read_u16(&buf[free_off_pos..free_off_pos + 2]) as usize;
            used_total += free_off + 2 * (num + 1);
            leaves += 1;
            node = BigEndian::read_u32(&buf[off..off + 4]); // forward link
        }
        // ~0.84 with the rotation (was ~0.69 with plain split), matching classic.
        let occupancy = used_total as f64 / (leaves * node_size) as f64;
        assert!(
            occupancy >= 0.80,
            "shuffled multi-dir leaf occupancy {occupancy:.3} (<0.80) over {leaves} leaves — \
             the rotation is not packing densely"
        );
    }
}