fstool 0.4.0

Build disk images and filesystems (ext2/3/4, MBR, GPT) from a directory tree and TOML spec, in the spirit of genext2fs.
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
//! HFS+ — Apple's legacy macOS filesystem (pre-2017).
//!
//! ## Status
//!
//! Read and write support.
//!
//! Read side: open, list directories, stream regular file contents,
//! read symbolic-link targets, and resolve hard links to their
//! underlying indirect-node iNodes. Files whose data fork spills
//! beyond eight inline extents are read through the extents-overflow
//! B-tree.
//!
//! Write side: format a fresh volume, create directories, regular
//! files, symbolic links, and hard links; remove empty directories
//! and files (with their forks). The writer keeps user data forks
//! streaming-only (64 KiB scratch) and spills fragmented files into
//! the extents-overflow B-tree when their run list outgrows the eight
//! inline extents in a catalog record. An optional journal stub
//! (clean, no transactions to replay) can be requested via
//! [`writer::FormatOpts::journaled`].
//!
//! Implementation is based on Apple Technical Note TN1150, the
//! canonical public reference for HFS+ on-disk structures.
//!
//! ## Scope and deferred features
//!
//! * No journal replay on read — the on-disk catalog is read as-is.
//! * HFSX case-sensitive comparison is honoured at the catalog-key
//!   level; non-ASCII case folding follows a simplified table.
//! * Extended-attribute B-tree (`attributesFile`) is parsed on the
//!   read side (for HFSCompression / `com.apple.decmpfs`); the writer
//!   never produces one.
//! * HFSCompression (`UF_COMPRESSED` + `com.apple.decmpfs`) is decoded
//!   for compression types 1, 3, and 4 (uncompressed inline, zlib
//!   inline, zlib in the resource fork); LZVN (7, 8) and LZFSE
//!   (11, 12) return [`crate::Error::Unsupported`].
//! * Resource forks are always written as empty.
//!
//! ## Module layout
//!
//! * [`volume_header`] — the 512-byte `HFSPlusVolumeHeader` at offset 1024.
//! * [`btree`] — node descriptors, header records, record-offset tables.
//! * [`catalog`] — catalog keys, leaf records, lookup.
//! * [`extents`] — extents-overflow B-tree walker for spilled extents.
//! * [`attributes`] — extended-attribute B-tree walker.
//! * [`decmpfs`] — HFSCompression header / block decoder.

pub mod attributes;
pub mod btree;
pub mod catalog;
pub mod decmpfs;
pub mod extents;
pub mod handle;
pub(crate) mod journal;
pub mod volume_header;
pub mod writer;

pub use writer::FormatOpts;

use std::io::Read;

use crate::Result;
use crate::block::BlockDevice;

use attributes::Attributes;
use btree::ForkReader;
use catalog::{Catalog, CatalogFile, CatalogKey, CatalogRecord, ROOT_FOLDER_ID, UniStr, mode};
use extents::ExtentsOverflow;
use volume_header::{ForkData, VolumeHeader, read_volume_header};

/// Maximum bytes we'll ever read from a symlink's data fork; symlinks
/// are tiny path strings and a sane filesystem stays well under this.
const SYMLINK_MAX_BYTES: u64 = 4096;

/// An opened HFS+ volume.
pub struct HfsPlus {
    volume_header: VolumeHeader,
    catalog: Catalog,
    /// Extents-overflow B-tree, opened lazily-but-once at mount time.
    /// Absent only if the volume header has no extents-overflow file,
    /// which is unusual but technically permitted.
    overflow: Option<ExtentsOverflow>,
    /// Attributes B-tree (extended attributes), opened lazily-but-once
    /// at mount time. Absent on volumes that have never had an xattr
    /// set — including every volume produced by this writer.
    attributes: Option<Attributes>,
    /// CNID of the HFS+ private data directory (where `iNode<N>`
    /// indirect-node files live), if it exists on this volume.
    /// Resolved lazily on first hard-link encounter.
    private_dir_cnid: std::cell::Cell<Option<u32>>,
    /// `true` once we've attempted to resolve `private_dir_cnid`. We
    /// cache the absent result too so we don't re-scan every time.
    private_dir_resolved: std::cell::Cell<bool>,
    /// Cached volume name, taken from the root folder's thread record.
    volume_name: String,
    /// Writer state, present only while a freshly formatted volume
    /// (or one re-opened for mutation) is being built. `None` for
    /// read-only opens.
    writer: Option<writer::Writer>,
}

impl HfsPlus {
    /// Open an existing HFS+ volume on `dev`. The returned handle is
    /// writable: subsequent `create_*` / `remove` calls mutate the live
    /// image, and [`flush`](Self::flush) persists the rewritten catalog,
    /// extents-overflow tree, allocation bitmap, and volume header.
    ///
    /// On a journaled volume any unreplayed transaction is drained
    /// *before* we read the catalog, extents-overflow, or bitmap: the
    /// pending journal may carry the only authoritative copy of those
    /// blocks following a crash mid-`flush`. Replay is idempotent, so
    /// volumes that crashed mid-replay land in the same state.
    pub fn open(dev: &mut dyn BlockDevice) -> Result<Self> {
        // Read the volume header first so we know whether replay is
        // applicable (journaled vs. not) and where the journal lives.
        let vh = read_volume_header(dev)?;
        journal::replay(dev, &vh)?;
        // Re-read the volume header in case replay restored it.
        let vh = read_volume_header(dev)?;
        let case_sensitive = vh.is_hfsx();

        let cat_fork = ForkReader::from_inline(&vh.catalog_file, vh.block_size, "catalog")?;
        let catalog = Catalog::open(dev, cat_fork, case_sensitive)?;

        // Open the extents-overflow file if its fork has any blocks.
        // It can be empty on a fresh volume.
        let overflow = if vh.extents_file.total_blocks > 0 {
            let ext_fork =
                ForkReader::from_inline(&vh.extents_file, vh.block_size, "extents-overflow")?;
            Some(ExtentsOverflow::open(dev, ext_fork)?)
        } else {
            None
        };

        // Open the attributes B-tree if the volume carries one. This
        // is the table HFSCompression reads `com.apple.decmpfs` from;
        // images produced by our writer have an empty attributes fork
        // and so skip this path entirely.
        let attributes = open_attributes(dev, &vh, case_sensitive)?;

        // The root folder's thread record is keyed by (ROOT_FOLDER_ID, "");
        // its name field is the volume name.
        let volume_name = lookup_thread_name(dev, &catalog, ROOT_FOLDER_ID)?
            .unwrap_or_else(|| "Untitled".to_string());

        // Reconstruct the in-memory writer state by walking the catalog
        // leaves and the extents-overflow leaves and loading the on-disk
        // bitmap. After this, create_* / remove / flush all work on the
        // live image exactly as they do post-format.
        let writer = writer::open_writable(dev, &vh, volume_name.clone())?;

        Ok(Self {
            volume_header: vh,
            catalog,
            overflow,
            attributes,
            private_dir_cnid: std::cell::Cell::new(None),
            private_dir_resolved: std::cell::Cell::new(false),
            volume_name,
            writer: Some(writer),
        })
    }

    /// Format `dev` as a fresh HFS+ volume and return a handle that
    /// accepts subsequent `create_*` calls. Call [`flush`](Self::flush)
    /// when done to persist the catalog, bitmap, and volume header.
    pub fn format(dev: &mut dyn BlockDevice, opts: &writer::FormatOpts) -> Result<Self> {
        let (vh, w) = writer::format(dev, opts)?;
        let case_sensitive = vh.is_hfsx();
        let mut w = w;
        let mut vh_mut = vh.clone();
        writer::flush(&mut w, &mut vh_mut, dev)?;
        w.flushed = false;

        let cat_fork = ForkReader::from_inline(&vh_mut.catalog_file, vh_mut.block_size, "catalog")?;
        let catalog = Catalog::open(dev, cat_fork, case_sensitive)?;
        let overflow = if vh_mut.extents_file.total_blocks > 0 {
            let ext_fork = ForkReader::from_inline(
                &vh_mut.extents_file,
                vh_mut.block_size,
                "extents-overflow",
            )?;
            Some(ExtentsOverflow::open(dev, ext_fork)?)
        } else {
            None
        };
        let attributes = open_attributes(dev, &vh_mut, case_sensitive)?;
        let volume_name = w.volume_name.clone();
        Ok(Self {
            volume_header: vh_mut,
            catalog,
            overflow,
            attributes,
            private_dir_cnid: std::cell::Cell::new(None),
            private_dir_resolved: std::cell::Cell::new(false),
            volume_name,
            writer: Some(w),
        })
    }

    /// Create a directory at the given absolute path.
    pub fn create_dir(
        &mut self,
        _dev: &mut dyn BlockDevice,
        path: &str,
        mode: u16,
        uid: u32,
        gid: u32,
    ) -> Result<u32> {
        let (parent_id, name) = self.resolve_create_target(path)?;
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: volume is read-only".into()))?;
        let cnid = w.next_cnid;
        w.next_cnid = w
            .next_cnid
            .checked_add(1)
            .ok_or_else(|| crate::Error::Unsupported("hfs+: CNID space exhausted".into()))?;
        writer::insert_folder(w, parent_id, &name, cnid, mode, uid, gid)?;
        Ok(cnid)
    }

    /// Create a regular file at the given absolute path, streaming
    /// `len` bytes from `src` into freshly allocated allocation blocks.
    #[allow(clippy::too_many_arguments)]
    pub fn create_file<R: std::io::Read>(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &str,
        src: &mut R,
        len: u64,
        mode: u16,
        uid: u32,
        gid: u32,
    ) -> Result<u32> {
        let (parent_id, name) = self.resolve_create_target(path)?;
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: volume is read-only".into()))?;
        let cnid = w.next_cnid;
        w.next_cnid = w
            .next_cnid
            .checked_add(1)
            .ok_or_else(|| crate::Error::Unsupported("hfs+: CNID space exhausted".into()))?;
        let fork = writer::stream_data_to_blocks(w, dev, src, len, cnid)?;
        writer::insert_file(
            w,
            parent_id,
            &name,
            cnid,
            mode,
            uid,
            gid,
            *b"\0\0\0\0",
            *b"\0\0\0\0",
            &fork,
            false,
        )?;
        Ok(cnid)
    }

    /// Create a symlink at `path` whose target is the UTF-8 byte string
    /// `target`. Finder type `slnk` / creator `rhap`, mode S_IFLNK.
    pub fn create_symlink(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &str,
        target: &str,
        mode: u16,
        uid: u32,
        gid: u32,
    ) -> Result<u32> {
        let (parent_id, name) = self.resolve_create_target(path)?;
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: volume is read-only".into()))?;
        let cnid = w.next_cnid;
        w.next_cnid = w
            .next_cnid
            .checked_add(1)
            .ok_or_else(|| crate::Error::Unsupported("hfs+: CNID space exhausted".into()))?;
        let fork = writer::write_inline_data(w, dev, target.as_bytes())?;
        writer::insert_file(
            w, parent_id, &name, cnid, mode, uid, gid, *b"slnk", *b"rhap", &fork, true,
        )?;
        Ok(cnid)
    }

    /// Create a hard link at `dst_path` pointing at the same on-disk
    /// content as `src_path`. After the call:
    ///
    /// * the data fork that previously lived under `src_path` is owned
    ///   by an `iNode<N>` file inside the HFS+ private-data directory;
    /// * both `src_path` and `dst_path` are `hlnk`/`hfs+` indirect-node
    ///   catalog entries with `BSDInfo.special == N`;
    /// * the read path (`open_file_reader`, `list_path`, …) follows the
    ///   hlnk pointer transparently and exposes the original bytes
    ///   under both names.
    ///
    /// Returns the link-inode number `N`. Errors if `src_path` is a
    /// directory, a symlink, or an already-existing hard link.
    pub fn create_hardlink(
        &mut self,
        _dev: &mut dyn BlockDevice,
        src_path: &str,
        dst_path: &str,
    ) -> Result<u32> {
        let (src_parent, src_name) = self.resolve_create_target(src_path)?;
        let (dst_parent, dst_name) = self.resolve_create_target(dst_path)?;
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: volume is read-only".into()))?;
        writer::promote_to_hardlink(w, src_parent, &src_name, dst_parent, &dst_name)
    }

    /// Remove a file, symlink, or empty directory at `path`.
    pub fn remove(&mut self, _dev: &mut dyn BlockDevice, path: &str) -> Result<()> {
        let (parent_id, name) = self.resolve_create_target(path)?;
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: volume is read-only".into()))?;
        writer::remove_entry(w, parent_id, &name)
    }

    #[doc(hidden)]
    #[cfg(test)]
    pub fn test_writer(&self) -> Option<&writer::Writer> {
        self.writer.as_ref()
    }

    /// Persist in-memory writer state (bitmap, catalog tree, volume
    /// header) to disk. Idempotent; no-op on read-only handles.
    pub fn flush(&mut self, dev: &mut dyn BlockDevice) -> Result<()> {
        let Some(w) = self.writer.as_mut() else {
            return Ok(());
        };
        writer::flush(w, &mut self.volume_header, dev)?;
        let case_sensitive = self.volume_header.is_hfsx();
        let cat_fork = ForkReader::from_inline(
            &self.volume_header.catalog_file,
            self.volume_header.block_size,
            "catalog",
        )?;
        self.catalog = Catalog::open(dev, cat_fork, case_sensitive)?;
        w.flushed = false;
        Ok(())
    }

    /// Split `path` into its parent CNID and final name component,
    /// resolving all intermediates against the in-memory catalog.
    fn resolve_create_target(&self, path: &str) -> Result<(u32, UniStr)> {
        let parts = split_path(path);
        if parts.is_empty() {
            return Err(crate::Error::InvalidArgument(
                "hfs+: cannot create at the root path".into(),
            ));
        }
        let (last, prefix) = parts.split_last().unwrap();
        let mut cnid = ROOT_FOLDER_ID;
        let w = self
            .writer
            .as_ref()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: volume is read-only".into()))?;
        for part in prefix {
            let name = UniStr::from_str_lossy(part);
            let (_, child_cnid, rec_type) = w.lookup(cnid, &name).ok_or_else(|| {
                crate::Error::InvalidArgument(format!(
                    "hfs+: parent component {part:?} does not exist"
                ))
            })?;
            if rec_type != catalog::REC_FOLDER {
                return Err(crate::Error::InvalidArgument(format!(
                    "hfs+: component {part:?} is not a directory"
                )));
            }
            cnid = child_cnid;
        }
        Ok((cnid, UniStr::from_str_lossy(last)))
    }

    /// Total byte capacity advertised by the volume header.
    pub fn total_bytes(&self) -> u64 {
        u64::from(self.volume_header.total_blocks) * u64::from(self.volume_header.block_size)
    }

    /// Allocation block size in bytes.
    pub fn block_size(&self) -> u32 {
        self.volume_header.block_size
    }

    /// Cached volume name (from the root thread record).
    pub fn volume_name(&self) -> &str {
        &self.volume_name
    }

    /// List the entries of a directory by absolute path. Returns one
    /// [`crate::fs::DirEntry`] per child, with `inode` set to the
    /// HFS+ CNID (catalog node id) — which is the closest analogue
    /// to a Unix inode number on this filesystem. Hard-link source
    /// entries are reported with the underlying iNode's `kind`
    /// (typically `Regular`) so callers see a uniform view.
    pub fn list_path(
        &self,
        dev: &mut dyn BlockDevice,
        path: &str,
    ) -> Result<Vec<crate::fs::DirEntry>> {
        let cnid = self.resolve_dir(dev, path)?;
        self.list_cnid(dev, cnid)
    }

    /// Open a regular file by absolute path for streaming reads.
    /// Transparently follows hard links (`hlnk`/`hfs+` indirect node
    /// entries) to the actual iNode in the HFS+ private-data directory.
    /// Returns `Unsupported` for symlinks — use
    /// [`read_symlink_target_path`](Self::read_symlink_target_path)
    /// for those.
    pub fn open_file_reader<'a>(
        &self,
        dev: &'a mut dyn BlockDevice,
        path: &str,
    ) -> Result<HfsPlusFileReader<'a>> {
        let rec = self.lookup_path(dev, path)?;
        let file = match rec {
            CatalogRecord::File(f) => f,
            CatalogRecord::Folder(_) => {
                return Err(crate::Error::InvalidArgument(format!(
                    "hfs+: {path:?} is a directory, not a file"
                )));
            }
            CatalogRecord::Thread(_) => {
                return Err(crate::Error::InvalidImage(format!(
                    "hfs+: path {path:?} resolved to a thread record"
                )));
            }
        };
        let file = self.resolve_hard_link(dev, file)?;
        let mode_bits = file.bsd.file_mode & mode::S_IFMT;
        if file.is_symlink() || mode_bits == mode::S_IFLNK {
            return Err(crate::Error::InvalidArgument(format!(
                "hfs+: {path:?} is a symlink; use read_symlink_target_path"
            )));
        }
        if mode_bits != 0 && mode_bits != mode::S_IFREG {
            return Err(crate::Error::Unsupported(format!(
                "hfs+: {path:?} is not a regular file (mode {:#06o})",
                file.bsd.file_mode
            )));
        }
        // HFSCompression: when UF_COMPRESSED is set, the data fork is
        // empty and the logical content lives in the
        // `com.apple.decmpfs` extended attribute (with optional
        // overflow into the resource fork). Materialise the
        // decompressed bytes up front and hand back a cursor over
        // them — the data is bounded by the header's uncompressed_size
        // field.
        if file.bsd.owner_flags & decmpfs::UF_COMPRESSED != 0 {
            let bytes = self.read_decmpfs_file(dev, &file, path)?;
            return Ok(HfsPlusFileReader::buffered(bytes));
        }
        let fork = self.open_data_fork(dev, &file)?;
        Ok(HfsPlusFileReader::streaming(
            dev,
            fork,
            file.data_fork.logical_size,
        ))
    }

    /// Read a symlink's target by absolute path. Returns the raw
    /// UTF-8 bytes stored in the file's data fork as a `String`
    /// (HFS+ symlinks are conventionally stored as UTF-8 path text
    /// without a NUL terminator).
    pub fn read_symlink_target_path(
        &self,
        dev: &mut dyn BlockDevice,
        path: &str,
    ) -> Result<String> {
        let rec = self.lookup_path(dev, path)?;
        let file = match rec {
            CatalogRecord::File(f) => f,
            _ => {
                return Err(crate::Error::InvalidArgument(format!(
                    "hfs+: {path:?} is not a file (cannot be a symlink)"
                )));
            }
        };
        let file = self.resolve_hard_link(dev, file)?;
        self.read_symlink_target_inner(dev, &file, path)
    }

    /// Read a symlink's target by CNID. Useful when the caller has
    /// already discovered the target file ID via [`Self::list_path`] but
    /// doesn't have a stable path (e.g. multiple parents). Returns
    /// the link target as a UTF-8 string.
    pub fn read_symlink_target(&self, dev: &mut dyn BlockDevice, cnid: u32) -> Result<String> {
        let file = self.lookup_file_by_cnid(dev, cnid)?;
        let file = self.resolve_hard_link(dev, file)?;
        self.read_symlink_target_inner(dev, &file, &format!("CNID {cnid}"))
    }

    /// Total byte length of a regular file (after hard-link resolution),
    /// for callers that want to size a buffer before streaming.
    pub fn file_size(&self, dev: &mut dyn BlockDevice, path: &str) -> Result<u64> {
        let rec = self.lookup_path(dev, path)?;
        let file = match rec {
            CatalogRecord::File(f) => f,
            _ => {
                return Err(crate::Error::InvalidArgument(format!(
                    "hfs+: {path:?} is not a file"
                )));
            }
        };
        let file = self.resolve_hard_link(dev, file)?;
        Ok(file.data_fork.logical_size)
    }

    // -- internal helpers ----------------------------------------------

    /// Walk the path one component at a time, returning the CNID of
    /// the *directory* it names. `"/"` and `""` both name the root.
    fn resolve_dir(&self, dev: &mut dyn BlockDevice, path: &str) -> Result<u32> {
        let parts = split_path(path);
        let mut cnid = ROOT_FOLDER_ID;
        for part in parts {
            let rec = self.lookup_component(dev, cnid, part)?;
            match rec {
                CatalogRecord::Folder(f) => {
                    cnid = f.folder_id;
                }
                CatalogRecord::File(_) => {
                    return Err(crate::Error::InvalidArgument(format!(
                        "hfs+: {part:?} is not a directory (in {path:?})"
                    )));
                }
                CatalogRecord::Thread(_) => {
                    return Err(crate::Error::InvalidImage(format!(
                        "hfs+: lookup of {part:?} returned a thread record"
                    )));
                }
            }
        }
        Ok(cnid)
    }

    /// Walk the path and return the leaf record (file or folder).
    fn lookup_path(&self, dev: &mut dyn BlockDevice, path: &str) -> Result<CatalogRecord> {
        let parts = split_path(path);
        if parts.is_empty() {
            return Err(crate::Error::InvalidArgument(
                "hfs+: cannot resolve root \"/\" as a leaf entry".into(),
            ));
        }
        let (last, prefix) = parts.split_last().unwrap();
        let mut cnid = ROOT_FOLDER_ID;
        for part in prefix {
            let rec = self.lookup_component(dev, cnid, part)?;
            match rec {
                CatalogRecord::Folder(f) => cnid = f.folder_id,
                _ => {
                    return Err(crate::Error::InvalidArgument(format!(
                        "hfs+: {part:?} is not a directory (in {path:?})"
                    )));
                }
            }
        }
        self.lookup_component(dev, cnid, last)
    }

    /// Look up the immediate child named `name` under directory `parent_id`.
    fn lookup_component(
        &self,
        dev: &mut dyn BlockDevice,
        parent_id: u32,
        name: &str,
    ) -> Result<CatalogRecord> {
        let key = CatalogKey {
            parent_id,
            name: UniStr::from_str_lossy(name),
            encoded_len: 0,
        };
        self.catalog.lookup(dev, &key)?.ok_or_else(|| {
            crate::Error::InvalidArgument(format!(
                "hfs+: no such entry {name:?} under CNID {parent_id}"
            ))
        })
    }

    /// Look up a catalog *file* by its CNID. Two-step: first read the
    /// file's thread record (key = (cnid, "")) to recover its
    /// `(parent_id, name)`, then look up the actual record.
    fn lookup_file_by_cnid(&self, dev: &mut dyn BlockDevice, cnid: u32) -> Result<CatalogFile> {
        let thread_key = CatalogKey {
            parent_id: cnid,
            name: UniStr::default(),
            encoded_len: 0,
        };
        let (parent_id, name) = match self.catalog.lookup(dev, &thread_key)? {
            Some(CatalogRecord::Thread(t)) => (t.parent_id, t.name),
            Some(_) => {
                return Err(crate::Error::InvalidImage(format!(
                    "hfs+: CNID {cnid} thread key did not return a thread record"
                )));
            }
            None => {
                return Err(crate::Error::InvalidArgument(format!(
                    "hfs+: no thread record for CNID {cnid}"
                )));
            }
        };
        let child_key = CatalogKey {
            parent_id,
            name,
            encoded_len: 0,
        };
        match self.catalog.lookup(dev, &child_key)? {
            Some(CatalogRecord::File(f)) => Ok(f),
            Some(CatalogRecord::Folder(_)) => Err(crate::Error::InvalidArgument(format!(
                "hfs+: CNID {cnid} names a folder, not a file"
            ))),
            Some(CatalogRecord::Thread(_)) => Err(crate::Error::InvalidImage(format!(
                "hfs+: CNID {cnid} reverse-lookup returned a thread record"
            ))),
            None => Err(crate::Error::InvalidArgument(format!(
                "hfs+: no catalog file for CNID {cnid}"
            ))),
        }
    }

    /// If `file` is a hard-link indirect-node entry (`hlnk`/`hfs+`),
    /// resolve it to the underlying iNode file in the HFS+ private
    /// data directory. Otherwise return the file unchanged.
    fn resolve_hard_link(
        &self,
        dev: &mut dyn BlockDevice,
        file: CatalogFile,
    ) -> Result<CatalogFile> {
        if !file.is_hard_link() {
            return Ok(file);
        }
        let private_dir = match self.private_data_dir(dev)? {
            Some(cnid) => cnid,
            None => {
                return Err(crate::Error::InvalidImage(
                    "hfs+: hard-link record but no '\\0\\0\\0\\0HFS+ Private Data' \
                     directory found"
                        .into(),
                ));
            }
        };
        // The iNode number lives in BsdInfo.special on a hlnk record.
        let inode_id = file.bsd.special;
        let name = format!("iNode{inode_id}");
        let rec = self.lookup_component(dev, private_dir, &name)?;
        match rec {
            CatalogRecord::File(f) => {
                // Defence in depth: forbid recursive hard links.
                if f.is_hard_link() {
                    return Err(crate::Error::InvalidImage(format!(
                        "hfs+: iNode{inode_id} is itself a hard-link indirection"
                    )));
                }
                Ok(f)
            }
            _ => Err(crate::Error::InvalidImage(format!(
                "hfs+: iNode{inode_id} is not a regular file record"
            ))),
        }
    }

    /// Resolve, cache, and return the CNID of the HFS+ private data
    /// directory (Apple's well-known name with four leading NUL
    /// code units followed by "HFS+ Private Data"). Returns `None`
    /// on a volume that has no hard links — the directory only exists
    /// when at least one hard link has ever been created.
    fn private_data_dir(&self, dev: &mut dyn BlockDevice) -> Result<Option<u32>> {
        if self.private_dir_resolved.get() {
            return Ok(self.private_dir_cnid.get());
        }
        // UniStr cannot easily be built from a Rust string containing
        // null code units, so build it directly.
        let mut code_units: Vec<u16> = vec![0, 0, 0, 0];
        code_units.extend("HFS+ Private Data".encode_utf16());
        let key = CatalogKey {
            parent_id: ROOT_FOLDER_ID,
            name: UniStr { code_units },
            encoded_len: 0,
        };
        let cnid = match self.catalog.lookup(dev, &key)? {
            Some(CatalogRecord::Folder(f)) => Some(f.folder_id),
            _ => None,
        };
        self.private_dir_cnid.set(cnid);
        self.private_dir_resolved.set(true);
        Ok(cnid)
    }

    /// Build a `ForkReader` for `file`'s data fork, pulling extra
    /// extents from the extents-overflow B-tree if the inline eight
    /// are insufficient.
    fn open_data_fork(&self, dev: &mut dyn BlockDevice, file: &CatalogFile) -> Result<ForkReader> {
        self.open_fork(
            dev,
            &file.data_fork,
            file.file_id,
            extents::FORK_DATA,
            "data",
        )
    }

    fn open_fork(
        &self,
        dev: &mut dyn BlockDevice,
        fork: &ForkData,
        file_id: u32,
        fork_type: u8,
        what: &str,
    ) -> Result<ForkReader> {
        if u64::from(fork.total_blocks) <= fork.inline_blocks() {
            return ForkReader::from_inline(fork, self.volume_header.block_size, what);
        }
        let overflow = self.overflow.as_ref().ok_or_else(|| {
            crate::Error::InvalidImage(
                "hfs+: fork needs overflow extents but volume has no \
                 extents-overflow file"
                    .into(),
            )
        })?;
        let first_overflow_block = u32::try_from(fork.inline_blocks()).map_err(|_| {
            crate::Error::InvalidImage("hfs+: inline fork block count overflows u32".into())
        })?;
        let extra = overflow.find_extents(dev, file_id, fork_type, first_overflow_block)?;
        ForkReader::from_inline_plus_overflow(fork, &extra, self.volume_header.block_size, what)
    }

    /// HFSCompression read path: look up `com.apple.decmpfs` for
    /// `file.file_id`, decode the header, and return the file's
    /// fully-decompressed bytes. For codecs that store the payload in
    /// the resource fork (type 4 / 8 / 12) we read the resource fork
    /// in one shot and hand it to the codec.
    fn read_decmpfs_file(
        &self,
        dev: &mut dyn BlockDevice,
        file: &CatalogFile,
        path: &str,
    ) -> Result<Vec<u8>> {
        let attrs = self.attributes.as_ref().ok_or_else(|| {
            crate::Error::InvalidImage(format!(
                "hfs+: {path:?} has UF_COMPRESSED set but volume has no \
                 attributes file to hold com.apple.decmpfs"
            ))
        })?;
        let rec = attrs
            .lookup(dev, file.file_id, "com.apple.decmpfs")?
            .ok_or_else(|| {
                crate::Error::InvalidImage(format!(
                    "hfs+: {path:?} has UF_COMPRESSED set but no com.apple.decmpfs \
                     attribute exists for CNID {}",
                    file.file_id
                ))
            })?;
        // Inline xattr — the entire decmpfs record fits in the leaf.
        let xattr_bytes = match rec {
            attributes::AttrRecord::Inline { data } => data,
            attributes::AttrRecord::Fork { fork } => {
                // Extremely rare in practice: an xattr that itself spilled
                // into its own fork. Read the whole fork into memory and
                // continue as if it were inline.
                let what = "decmpfs-xattr-fork";
                let reader = if u64::from(fork.total_blocks) <= fork.inline_blocks() {
                    ForkReader::from_inline(&fork, self.volume_header.block_size, what)?
                } else {
                    return Err(crate::Error::Unsupported(
                        "hfs+: decmpfs xattr stored in a fork that needs overflow extents".into(),
                    ));
                };
                let mut buf = vec![0u8; fork.logical_size as usize];
                reader.read(dev, 0, &mut buf)?;
                buf
            }
        };
        if xattr_bytes.len() < decmpfs::DecmpfsHeader::SIZE {
            return Err(crate::Error::InvalidImage(format!(
                "hfs+: {path:?} com.apple.decmpfs is {} bytes, shorter than the 16-byte header",
                xattr_bytes.len()
            )));
        }
        let header = decmpfs::DecmpfsHeader::decode(&xattr_bytes)?;
        if header.compression_type.is_resource_fork() {
            // Type 4 / 8 / 12 — payload lives in the resource fork.
            if file.resource_fork.logical_size == 0 {
                return Err(crate::Error::InvalidImage(format!(
                    "hfs+: {path:?} decmpfs claims compression type {:?} but resource fork is empty",
                    header.compression_type
                )));
            }
            let rf_reader = self.open_fork(
                dev,
                &file.resource_fork,
                file.file_id,
                extents::FORK_RESOURCE,
                "resource",
            )?;
            let mut rf_bytes = vec![0u8; file.resource_fork.logical_size as usize];
            rf_reader.read(dev, 0, &mut rf_bytes)?;
            decmpfs::decompress_resource_fork(
                header.compression_type,
                &rf_bytes,
                header.uncompressed_size,
            )
        } else {
            // Inline payload follows the 16-byte header in the xattr.
            decmpfs::decompress_inline(
                header.compression_type,
                &xattr_bytes[decmpfs::DecmpfsHeader::SIZE..],
                header.uncompressed_size,
            )
        }
    }

    /// Read up to `SYMLINK_MAX_BYTES` from a symlink's data fork and
    /// return the result as a Rust string. `descriptor` is a human-
    /// readable identifier (path or CNID) used only in error text.
    fn read_symlink_target_inner(
        &self,
        dev: &mut dyn BlockDevice,
        file: &CatalogFile,
        descriptor: &str,
    ) -> Result<String> {
        let mode_bits = file.bsd.file_mode & mode::S_IFMT;
        let by_mode = mode_bits == mode::S_IFLNK;
        let by_finder = file.is_symlink();
        if !by_mode && !by_finder {
            return Err(crate::Error::InvalidArgument(format!(
                "hfs+: {descriptor} is not a symlink (mode {:#06o}, \
                 FileInfo type {:?}, creator {:?})",
                file.bsd.file_mode,
                bytes_to_osstr(&file.file_type),
                bytes_to_osstr(&file.creator),
            )));
        }
        let len = file.data_fork.logical_size;
        if len == 0 {
            return Ok(String::new());
        }
        if len > SYMLINK_MAX_BYTES {
            return Err(crate::Error::InvalidImage(format!(
                "hfs+: {descriptor} symlink target too large ({len} bytes, \
                 max {SYMLINK_MAX_BYTES})"
            )));
        }
        let fork = self.open_data_fork(dev, file)?;
        let mut buf = vec![0u8; len as usize];
        fork.read(dev, 0, &mut buf)?;
        // HFS+ symlinks are UTF-8 path strings. Accept a trailing NUL
        // (some writers add one).
        if buf.last() == Some(&0) {
            buf.pop();
        }
        String::from_utf8(buf).map_err(|e| {
            crate::Error::InvalidImage(format!(
                "hfs+: {descriptor} symlink target is not valid UTF-8: {e}"
            ))
        })
    }

    /// Enumerate the direct children of folder `cnid` by scanning
    /// every leaf node of the catalog from the first leaf onwards
    /// and collecting entries whose key.parentID matches.
    fn list_cnid(&self, dev: &mut dyn BlockDevice, cnid: u32) -> Result<Vec<crate::fs::DirEntry>> {
        use crate::fs::{DirEntry as FsDirEntry, EntryKind};

        let mut out = Vec::new();
        let node_size = u32::from(self.catalog.header.node_size);
        let mut node_idx = self.catalog.header.first_leaf_node;
        while node_idx != 0 {
            let node = btree::read_node(dev, &self.catalog.fork, node_idx, node_size)?;
            let desc = btree::NodeDescriptor::decode(&node)?;
            if desc.kind != btree::KIND_LEAF {
                return Err(crate::Error::InvalidImage(format!(
                    "hfs+: leaf chain node {node_idx} has non-leaf kind {}",
                    desc.kind
                )));
            }
            let offs = btree::record_offsets(&node, desc.num_records)?;

            let mut passed_parent = false;
            for i in 0..desc.num_records as usize {
                let rec = btree::record_bytes(&node, &offs, i);
                let key = CatalogKey::decode(rec)?;
                use std::cmp::Ordering as O;
                match key.parent_id.cmp(&cnid) {
                    O::Less => continue,
                    O::Greater => {
                        passed_parent = true;
                        break;
                    }
                    O::Equal => {}
                }
                let body_start = align2(key.encoded_len);
                if body_start > rec.len() {
                    return Err(crate::Error::InvalidImage(
                        "hfs+: catalog key overruns record".into(),
                    ));
                }
                let body = &rec[body_start..];
                let record = CatalogRecord::decode(body)?;
                // Skip threads — they're metadata, not real children.
                let (kind, child_id) = match &record {
                    CatalogRecord::Folder(f) => (EntryKind::Dir, f.folder_id),
                    CatalogRecord::File(f) => {
                        // Hard-link entries: resolve the kind by
                        // peeking at the iNode so callers see a
                        // unified view. The link itself is the
                        // `child_id` we expose, matching what the
                        // catalog records.
                        if f.is_hard_link() {
                            let resolved_kind = self
                                .resolve_hard_link(dev, f.clone())
                                .map(|r| file_kind(&r))
                                .unwrap_or(EntryKind::Unknown);
                            (resolved_kind, f.file_id)
                        } else if f.is_symlink() {
                            (EntryKind::Symlink, f.file_id)
                        } else {
                            (file_kind(f), f.file_id)
                        }
                    }
                    CatalogRecord::Thread(_) => continue,
                };
                let size = match &record {
                    CatalogRecord::File(f) if matches!(kind, EntryKind::Regular) => {
                        f.data_fork.logical_size
                    }
                    _ => 0,
                };
                out.push(FsDirEntry {
                    name: key.name.to_string_lossy(),
                    inode: child_id,
                    kind,
                    size,
                });
            }
            if passed_parent {
                break;
            }
            node_idx = desc.f_link;
        }
        Ok(out)
    }
}

/// Reader for a regular HFS+ file. Two storage strategies sit
/// behind the same public type so callers don't have to branch:
///
/// * **Streaming** — the common case. Holds the data-fork extent
///   list in a [`ForkReader`] and walks it on demand from the
///   borrowed [`BlockDevice`].
/// * **Buffered** — used when the on-disk file carries
///   `UF_COMPRESSED` and its logical content has to be
///   reconstructed from the `com.apple.decmpfs` extended attribute
///   (and optionally the resource fork) up front. Once we've
///   inflated the payload we hold it in RAM and serve reads from a
///   cursor — a single decmpfs file decompresses to at most a few
///   MiB per leaf record and the resource-fork path is bounded by
///   64 KiB blocks, so this is fine for the workloads we care
///   about.
///
/// The variant lives in a private inner enum so the public type
/// remains a fieldless struct — matching the surface this type
/// exposed before HFSCompression support was added.
pub struct HfsPlusFileReader<'a> {
    inner: HfsPlusFileReaderInner<'a>,
}

/// Private storage for [`HfsPlusFileReader`]. Hidden behind the
/// public struct so adding / renaming variants stays a non-breaking
/// change.
enum HfsPlusFileReaderInner<'a> {
    /// On-disk data fork; reads stream from `dev`.
    Streaming {
        dev: &'a mut dyn BlockDevice,
        fork: ForkReader,
        /// Bytes of the file still to return.
        remaining: u64,
        /// Current fork-relative byte position.
        position: u64,
    },
    /// Decompressed (or otherwise materialised) payload held in RAM.
    /// Carries the file lifetime so the public type signature is
    /// uniform regardless of variant.
    Buffered {
        bytes: Vec<u8>,
        position: u64,
        _phantom: std::marker::PhantomData<&'a ()>,
    },
}

impl<'a> HfsPlusFileReader<'a> {
    /// Build a streaming reader over the bytes of `fork`. Reads stop
    /// once `logical_size` has been returned.
    pub(crate) fn streaming(
        dev: &'a mut dyn BlockDevice,
        fork: ForkReader,
        logical_size: u64,
    ) -> Self {
        Self {
            inner: HfsPlusFileReaderInner::Streaming {
                dev,
                fork,
                remaining: logical_size,
                position: 0,
            },
        }
    }

    /// Build a buffered reader serving `bytes` from a 0-based cursor.
    /// Used by the HFSCompression path so the public reader interface
    /// looks identical to the data-fork case.
    pub(crate) fn buffered(bytes: Vec<u8>) -> Self {
        Self {
            inner: HfsPlusFileReaderInner::Buffered {
                bytes,
                position: 0,
                _phantom: std::marker::PhantomData,
            },
        }
    }
}

impl<'a> Read for HfsPlusFileReader<'a> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match &mut self.inner {
            HfsPlusFileReaderInner::Streaming {
                dev,
                fork,
                remaining,
                position,
            } => {
                if *remaining == 0 || buf.is_empty() {
                    return Ok(0);
                }
                let want = (buf.len() as u64).min(*remaining) as usize;
                fork.read(*dev, *position, &mut buf[..want])
                    .map_err(std::io::Error::other)?;
                *position += want as u64;
                *remaining -= want as u64;
                Ok(want)
            }
            HfsPlusFileReaderInner::Buffered {
                bytes, position, ..
            } => {
                let len = bytes.len() as u64;
                if *position >= len || buf.is_empty() {
                    return Ok(0);
                }
                let avail = (len - *position) as usize;
                let want = buf.len().min(avail);
                let p = *position as usize;
                buf[..want].copy_from_slice(&bytes[p..p + want]);
                *position += want as u64;
                Ok(want)
            }
        }
    }
}

impl<'a> std::io::Seek for HfsPlusFileReader<'a> {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        match &mut self.inner {
            HfsPlusFileReaderInner::Streaming {
                fork,
                remaining,
                position,
                ..
            } => {
                let total = fork.logical_size as i128;
                let new = match pos {
                    std::io::SeekFrom::Start(n) => n as i128,
                    std::io::SeekFrom::Current(d) => *position as i128 + d as i128,
                    std::io::SeekFrom::End(d) => total + d as i128,
                };
                if new < 0 {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "hfs+: seek to negative offset",
                    ));
                }
                *position = new as u64;
                *remaining = fork.logical_size.saturating_sub(*position);
                Ok(*position)
            }
            HfsPlusFileReaderInner::Buffered {
                bytes, position, ..
            } => {
                let total = bytes.len() as i128;
                let new = match pos {
                    std::io::SeekFrom::Start(n) => n as i128,
                    std::io::SeekFrom::Current(d) => *position as i128 + d as i128,
                    std::io::SeekFrom::End(d) => total + d as i128,
                };
                if new < 0 {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "hfs+: seek to negative offset",
                    ));
                }
                *position = new as u64;
                Ok(*position)
            }
        }
    }
}

impl<'a> crate::fs::FileReadHandle for HfsPlusFileReader<'a> {
    fn len(&self) -> u64 {
        match &self.inner {
            HfsPlusFileReaderInner::Streaming { fork, .. } => fork.logical_size,
            HfsPlusFileReaderInner::Buffered { bytes, .. } => bytes.len() as u64,
        }
    }
}

/// Probe for the HFS+ volume-header signature `"H+"` (or `"HX"` for HFSX)
/// at offset 1024 of the volume.
pub fn probe(dev: &mut dyn BlockDevice) -> Result<bool> {
    if dev.total_size() < 1024 + 2 {
        return Ok(false);
    }
    let mut sig = [0u8; 2];
    dev.read_at(1024, &mut sig)?;
    Ok(&sig == b"H+" || &sig == b"HX")
}

// -- helpers --------------------------------------------------------------

/// Classify a `CatalogFile` into a [`crate::fs::EntryKind`] using
/// its BSD `file_mode` bits when set, falling back to "regular".
fn file_kind(f: &CatalogFile) -> crate::fs::EntryKind {
    use crate::fs::EntryKind;
    match f.bsd.file_mode & mode::S_IFMT {
        mode::S_IFREG => EntryKind::Regular,
        mode::S_IFDIR => EntryKind::Dir, // unusual on a file record, but be defensive
        mode::S_IFLNK => EntryKind::Symlink,
        mode::S_IFCHR => EntryKind::Char,
        mode::S_IFBLK => EntryKind::Block,
        mode::S_IFIFO => EntryKind::Fifo,
        mode::S_IFSOCK => EntryKind::Socket,
        0 => EntryKind::Regular,
        _ => EntryKind::Unknown,
    }
}

/// Read the thread record for `cnid`, returning the node name. Used
/// to discover the volume name from the root folder's thread.
fn lookup_thread_name(
    dev: &mut dyn BlockDevice,
    catalog: &Catalog,
    cnid: u32,
) -> Result<Option<String>> {
    let key = CatalogKey {
        parent_id: cnid,
        name: UniStr::default(),
        encoded_len: 0,
    };
    match catalog.lookup(dev, &key)? {
        Some(CatalogRecord::Thread(t)) => Ok(Some(t.name.to_string_lossy())),
        _ => Ok(None),
    }
}

/// Open the volume's attributes B-tree (extended-attribute file), or
/// return `None` if the volume has no attributes file. Image producers
/// (including our own writer) commonly leave the attributes fork
/// empty.
fn open_attributes(
    dev: &mut dyn BlockDevice,
    vh: &VolumeHeader,
    case_sensitive: bool,
) -> Result<Option<Attributes>> {
    if vh.attributes_file.total_blocks == 0 {
        return Ok(None);
    }
    let fork = ForkReader::from_inline(&vh.attributes_file, vh.block_size, "attributes")?;
    Ok(Some(Attributes::open(dev, fork, case_sensitive)?))
}

/// Render an OSType 4-byte tag for diagnostics, preferring ASCII
/// when the tag is human-readable and falling back to hex otherwise.
fn bytes_to_osstr(b: &[u8; 4]) -> String {
    if b.iter().all(|&c| (0x20..=0x7E).contains(&c)) {
        format!("'{}'", String::from_utf8_lossy(b))
    } else {
        format!("0x{:02x}{:02x}{:02x}{:02x}", b[0], b[1], b[2], b[3])
    }
}

fn align2(n: usize) -> usize {
    n + (n & 1)
}

fn split_path(path: &str) -> Vec<&str> {
    path.split('/')
        .filter(|p| !p.is_empty() && *p != ".")
        .collect()
}

// ----------------------------------------------------------------------
// `crate::fs::Filesystem` trait impl — bridges HfsPlus into the generic
// walker. `open()` returns a writable handle (the writer state is
// reconstructed from the on-disk catalog + bitmap), so the mutating
// trait methods work on already-flushed images the same way they do
// post-format.
// ----------------------------------------------------------------------

impl crate::fs::FilesystemFactory for HfsPlus {
    type FormatOpts = writer::FormatOpts;

    fn format(dev: &mut dyn BlockDevice, opts: &Self::FormatOpts) -> Result<Self> {
        Self::format(dev, opts)
    }

    fn open(dev: &mut dyn BlockDevice) -> Result<Self> {
        Self::open(dev)
    }
}

impl crate::fs::Filesystem for HfsPlus {
    fn create_file(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &std::path::Path,
        src: crate::fs::FileSource,
        meta: crate::fs::FileMeta,
    ) -> Result<()> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        let len = src.len()?;
        let (mut reader, _) = src.open()?;
        let mode = meta.mode;
        self.create_file(dev, s, &mut reader, len, mode, meta.uid, meta.gid)
            .map(|_| ())
    }

    fn create_dir(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &std::path::Path,
        meta: crate::fs::FileMeta,
    ) -> Result<()> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        let mode = meta.mode;
        self.create_dir(dev, s, mode, meta.uid, meta.gid)
            .map(|_| ())
    }

    fn create_symlink(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &std::path::Path,
        target: &std::path::Path,
        meta: crate::fs::FileMeta,
    ) -> Result<()> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        let t = target.to_str().ok_or_else(|| {
            crate::Error::InvalidArgument("hfs+: non-UTF-8 symlink target".into())
        })?;
        let mode = meta.mode;
        self.create_symlink(dev, s, t, mode, meta.uid, meta.gid)
            .map(|_| ())
    }

    fn create_device(
        &mut self,
        _dev: &mut dyn BlockDevice,
        _path: &std::path::Path,
        _kind: crate::fs::DeviceKind,
        _major: u32,
        _minor: u32,
        _meta: crate::fs::FileMeta,
    ) -> Result<()> {
        Err(crate::Error::Unsupported(
            "hfs+: device / FIFO / socket nodes are not yet implemented".into(),
        ))
    }

    fn remove(&mut self, dev: &mut dyn BlockDevice, path: &std::path::Path) -> Result<()> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        self.remove(dev, s)
    }

    fn list(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &std::path::Path,
    ) -> Result<Vec<crate::fs::DirEntry>> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        self.list_path(dev, s)
    }

    fn read_file<'a>(
        &'a mut self,
        dev: &'a mut dyn BlockDevice,
        path: &std::path::Path,
    ) -> Result<Box<dyn std::io::Read + 'a>> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        let r = self.open_file_reader(dev, s)?;
        Ok(Box::new(r))
    }

    fn open_file_ro<'a>(
        &'a mut self,
        dev: &'a mut dyn BlockDevice,
        path: &std::path::Path,
    ) -> Result<Box<dyn crate::fs::FileReadHandle + 'a>> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        let r = self.open_file_reader(dev, s)?;
        Ok(Box::new(r))
    }

    fn open_file_rw<'a>(
        &'a mut self,
        dev: &'a mut dyn BlockDevice,
        path: &std::path::Path,
        flags: crate::fs::OpenFlags,
        meta: Option<crate::fs::FileMeta>,
    ) -> Result<Box<dyn crate::fs::FileHandle + 'a>> {
        handle::open_file_rw(self, dev, path, flags, meta)
    }

    fn flush(&mut self, dev: &mut dyn BlockDevice) -> Result<()> {
        Self::flush(self, dev)
    }

    fn read_symlink(
        &mut self,
        dev: &mut dyn BlockDevice,
        path: &std::path::Path,
    ) -> Result<std::path::PathBuf> {
        let s = path
            .to_str()
            .ok_or_else(|| crate::Error::InvalidArgument("hfs+: non-UTF-8 path".into()))?;
        Ok(std::path::PathBuf::from(
            self.read_symlink_target_path(dev, s)?,
        ))
    }
}

// -- tests ---------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::block::MemoryBackend;

    #[test]
    fn probe_recognises_h_plus_signature() {
        let mut dev = MemoryBackend::new(8192);
        dev.write_at(1024, b"H+").unwrap();
        assert!(probe(&mut dev).unwrap());
    }

    #[test]
    fn probe_recognises_hx_signature() {
        let mut dev = MemoryBackend::new(8192);
        dev.write_at(1024, b"HX").unwrap();
        assert!(probe(&mut dev).unwrap());
    }

    #[test]
    fn probe_rejects_unknown_signature() {
        let mut dev = MemoryBackend::new(8192);
        dev.write_at(1024, b"NO").unwrap();
        assert!(!probe(&mut dev).unwrap());
    }

    #[test]
    fn open_fails_on_garbage() {
        let mut dev = MemoryBackend::new(8192);
        // Default zeros => signature 0x0000, not H+ or HX.
        assert!(HfsPlus::open(&mut dev).is_err());
    }

    /// Hard-link resolver invariant: the link-inode number returned by
    /// [`HfsPlus::create_hardlink`] must equal the `file_id` of the
    /// iNode catalog file that holds the data, and `BSDInfo.special`
    /// on every `hlnk` record in the chain must point at that same
    /// CNID. Cross-checks that:
    /// * both source and destination hlnk records carry the same
    ///   `special` (= `link_inode`), and neither one's `file_id`
    ///   collides with it;
    /// * `lookup_file_by_cnid(link_inode)` returns a non-hlnk file
    ///   whose `file_id == link_inode`;
    /// * the iNode owns the real data fork (logical_size matches the
    ///   payload), while the hlnk records' own data forks are empty;
    /// * the iNode's `bsd.special` carries the link count (2 here).
    ///
    /// Regression: this is the contract `resolve_hard_link` relies on
    /// to walk `hlnk -> iNode<N>`. If `create_hardlink` ever returned
    /// a non-CNID handle (e.g. a sequential counter), reads would
    /// silently mis-resolve.
    #[test]
    fn create_hardlink_returns_inode_cnid_matching_resolved_file_id() {
        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();
        let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();

        let data = b"link-inode invariant payload\n".repeat(8);
        let mut src = std::io::Cursor::new(&data);
        hfs.create_file(&mut dev, "/src", &mut src, data.len() as u64, 0o644, 0, 0)
            .unwrap();
        let link_inode = hfs.create_hardlink(&mut dev, "/src", "/dst").unwrap();
        hfs.flush(&mut dev).unwrap();

        // Re-open from disk so we exercise the read-side resolver.
        let hfs = HfsPlus::open(&mut dev).unwrap();

        // The iNode CNID must be resolvable as a real file whose
        // file_id matches the link-inode handle exactly.
        let inode_file = hfs.lookup_file_by_cnid(&mut dev, link_inode).unwrap();
        assert_eq!(
            inode_file.file_id, link_inode,
            "iNode's catalog file_id must equal the link-inode CNID"
        );
        assert!(
            !inode_file.is_hard_link(),
            "iNode itself must not be an hlnk record (would recurse)"
        );
        assert_eq!(
            inode_file.data_fork.logical_size,
            data.len() as u64,
            "iNode owns the data fork; logical_size must equal payload"
        );
        assert_eq!(
            inode_file.bsd.special, 2,
            "iNode.bsd.special is the link count (2 = src + dst)"
        );

        // Both hlnk records must carry `special == link_inode` and have
        // a file_id distinct from it (their own catalog identity).
        for path in ["/src", "/dst"] {
            let rec = hfs.lookup_path(&mut dev, path).unwrap();
            let f = match rec {
                catalog::CatalogRecord::File(f) => f,
                _ => panic!("{path:?} should be a catalog file record"),
            };
            assert!(f.is_hard_link(), "{path:?} must be an hlnk record");
            assert_eq!(
                f.bsd.special, link_inode,
                "{path:?} bsd.special must point at the iNode CNID"
            );
            assert_ne!(
                f.file_id, link_inode,
                "{path:?} hlnk file_id must differ from the iNode CNID"
            );
            assert_eq!(
                f.data_fork.logical_size, 0,
                "{path:?} hlnk record's own data fork must be empty"
            );
        }
    }

    /// Round-trip: format + populate + flush, then `HfsPlus::open` the
    /// flushed image and add a *second* file via `create_file`, flush
    /// again, and reopen a third time. The second file must be visible
    /// at its path with byte-exact contents, and the original file must
    /// still be intact. Locks down the open-as-writable path used by
    /// `fstool add` on an already-flushed HFS+ image.
    #[test]
    fn reopen_writable_round_trip_add_file() {
        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();

        // 1. Format + write one file + flush.
        let first = b"first file from format() pass\n".repeat(4);
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&first);
            hfs.create_file(
                &mut dev,
                "/first.txt",
                &mut src,
                first.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // 2. Re-open the flushed image and verify the existing file is
        //    readable AND that the handle reports mutation capability.
        //    Then add a second file and flush.
        let second = b"second file added after reopen\n".repeat(7);
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            // Default Filesystem::mutation_capability is Mutable; verify
            // HFS+ doesn't override to a more restrictive value.
            let cap = <HfsPlus as crate::fs::Filesystem>::mutation_capability(&hfs);
            assert_eq!(
                cap,
                crate::fs::MutationCapability::Mutable,
                "freshly-opened HFS+ must advertise Mutable"
            );

            // Existing file still readable.
            let mut r = hfs.open_file_reader(&mut dev, "/first.txt").unwrap();
            let mut buf = Vec::new();
            std::io::Read::read_to_end(&mut r, &mut buf).unwrap();
            assert_eq!(buf, first, "existing file content survives reopen");
            drop(r);

            // Add a second file via the writer state reconstructed in open().
            let mut src = std::io::Cursor::new(&second);
            hfs.create_file(
                &mut dev,
                "/second.txt",
                &mut src,
                second.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // 3. Re-open again and verify BOTH files exist with correct bytes.
        let hfs = HfsPlus::open(&mut dev).unwrap();
        let entries = hfs.list_path(&mut dev, "/").unwrap();
        let names: std::collections::BTreeSet<&str> =
            entries.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names.contains("first.txt"),
            "first.txt missing after reopen; got {names:?}"
        );
        assert!(
            names.contains("second.txt"),
            "second.txt missing after reopen; got {names:?}"
        );

        let size = hfs.file_size(&mut dev, "/second.txt").unwrap();
        assert_eq!(size, second.len() as u64);
        let mut r = hfs.open_file_reader(&mut dev, "/second.txt").unwrap();
        let mut got = Vec::new();
        std::io::Read::read_to_end(&mut r, &mut got).unwrap();
        assert_eq!(got, second, "second.txt bytes survive a second reopen");

        let mut r = hfs.open_file_reader(&mut dev, "/first.txt").unwrap();
        let mut got = Vec::new();
        std::io::Read::read_to_end(&mut r, &mut got).unwrap();
        assert_eq!(got, first, "first.txt bytes still intact");
    }

    /// Round-trip: reopen a flushed image, `remove` an existing entry,
    /// flush, reopen — the entry must be gone and its blocks freed. Locks
    /// down the open-as-writable path used by `fstool rm`.
    #[test]
    fn reopen_writable_round_trip_remove_file() {
        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();

        let payload = b"goodbye, cruel world\n".repeat(16);
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&payload);
            hfs.create_file(
                &mut dev,
                "/doomed.txt",
                &mut src,
                payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.create_file(
                &mut dev,
                "/keeper.txt",
                &mut std::io::Cursor::new(b"keep me\n"),
                8,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        let free_before;
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            free_before = hfs.volume_header.free_blocks;
            hfs.remove(&mut dev, "/doomed.txt").unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        let hfs = HfsPlus::open(&mut dev).unwrap();
        let entries = hfs.list_path(&mut dev, "/").unwrap();
        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
        assert!(
            !names.contains(&"doomed.txt"),
            "doomed.txt should be gone after remove + reopen, got {names:?}"
        );
        assert!(
            names.contains(&"keeper.txt"),
            "keeper.txt should still exist, got {names:?}"
        );

        // The data blocks the removed file owned should be reclaimed.
        // payload is len-bytes spread across ceil(len / block_size) blocks.
        let bs = hfs.block_size() as u64;
        let freed_blocks = (payload.len() as u64).div_ceil(bs) as u32;
        assert!(
            hfs.volume_header.free_blocks >= free_before + freed_blocks,
            "expected at least {freed_blocks} more free blocks after remove \
             (before={free_before}, after={})",
            hfs.volume_header.free_blocks
        );
    }

    /// `Filesystem::open_file_rw` on a non-journaled image: full
    /// round-trip — open existing file, patch a byte range in the
    /// middle, `sync`, drop the handle, reopen, verify the patch is
    /// present and the surrounding bytes are intact.
    #[test]
    fn open_file_rw_round_trip_non_journaled() {
        use crate::fs::{Filesystem, OpenFlags};
        use std::io::{Read, Seek, SeekFrom, Write};

        let mut dev = MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();
        let payload: Vec<u8> = (0..16 * 1024).map(|i| (i & 0xFF) as u8).collect();

        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&payload);
            hfs.create_file(
                &mut dev,
                "/edit.bin",
                &mut src,
                payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // Reopen, patch.
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            let mut h = hfs
                .open_file_rw(
                    &mut dev,
                    std::path::Path::new("/edit.bin"),
                    OpenFlags::default(),
                    None,
                )
                .unwrap();
            assert_eq!(h.len(), payload.len() as u64);
            h.seek(SeekFrom::Start(4096)).unwrap();
            h.write_all(b"PATCHED_RANGE").unwrap();
            h.sync().unwrap();
            drop(h);
        }

        // Reopen, verify.
        {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let mut r = hfs.open_file_reader(&mut dev, "/edit.bin").unwrap();
            let mut got = Vec::new();
            r.read_to_end(&mut got).unwrap();
            assert_eq!(got.len(), payload.len());
            assert_eq!(&got[..4096], &payload[..4096], "head unchanged");
            assert_eq!(&got[4096..4096 + 13], b"PATCHED_RANGE", "patch is present");
            assert_eq!(&got[4096 + 13..], &payload[4096 + 13..], "tail unchanged");
        }
    }

    /// Same round-trip as the non-journaled test but on an image
    /// formatted with the journal stub enabled. After Path A's commit
    /// sequence (write tx → advance end → apply blocks → advance
    /// start) the journal is back to `start == end`, so a subsequent
    /// open sees no replay work and treats the volume as clean.
    #[test]
    fn open_file_rw_round_trip_journaled() {
        use crate::fs::{Filesystem, OpenFlags};
        use std::io::{Read, Seek, SeekFrom, Write};

        let mut dev = MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts {
            journaled: true,
            ..writer::FormatOpts::default()
        };
        let payload: Vec<u8> = (0..8 * 1024).map(|i| (i & 0xFF) as u8).collect();

        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&payload);
            hfs.create_file(
                &mut dev,
                "/jrnl.bin",
                &mut src,
                payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // Reopen + patch via the FileHandle API.
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            assert_ne!(
                hfs.volume_header.attributes & writer::VOL_ATTR_JOURNALED,
                0,
                "journaled bit must survive reopen"
            );
            let mut h = hfs
                .open_file_rw(
                    &mut dev,
                    std::path::Path::new("/jrnl.bin"),
                    OpenFlags::default(),
                    None,
                )
                .unwrap();
            h.seek(SeekFrom::Start(2048)).unwrap();
            h.write_all(b"journal-bypass").unwrap();
            h.sync().unwrap();
        }

        // Verify the data survived and the journal header is still clean.
        {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let mut r = hfs.open_file_reader(&mut dev, "/jrnl.bin").unwrap();
            let mut got = Vec::new();
            r.read_to_end(&mut got).unwrap();
            assert_eq!(got.len(), payload.len());
            assert_eq!(&got[..2048], &payload[..2048]);
            assert_eq!(&got[2048..2048 + 14], b"journal-bypass");
            assert_eq!(&got[2048 + 14..], &payload[2048 + 14..]);
        }

        // Inspect the journal header directly: start MUST equal end
        // (Path A leaves the journal sealed once the transaction is
        // applied). The journal header lives at the start of the
        // journal buffer; the JournalInfoBlock at byte 12 of the
        // volume header tells us where the buffer starts.
        let mut vh_buf = [0u8; 512];
        dev.read_at(volume_header::VOLUME_HEADER_OFFSET, &mut vh_buf)
            .unwrap();
        let info_block = u32::from_be_bytes(vh_buf[12..16].try_into().unwrap());
        let bs = u32::from_be_bytes(vh_buf[40..44].try_into().unwrap());
        assert_ne!(info_block, 0);
        let info_off = u64::from(info_block) * u64::from(bs);
        let mut info = [0u8; 52];
        dev.read_at(info_off, &mut info).unwrap();
        let jbuf_off = u64::from_be_bytes(info[36..44].try_into().unwrap());
        let mut hdr = [0u8; 24];
        dev.read_at(jbuf_off, &mut hdr).unwrap();
        let start = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
        let end = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
        assert_eq!(
            start, end,
            "Path A requires the journal to be sealed (start == end) \
             after a successful sync (start={start:#x}, end={end:#x})"
        );
    }

    /// Simulate a crash mid-sync: commit a journal transaction (so
    /// `end` is advanced and the user data is on disk), then forcibly
    /// rewind `start` so the on-disk journal claims unreplayed work,
    /// and corrupt the user data so we can confirm replay reapplies
    /// it. The next open_file_rw must drain the journal and produce
    /// the post-sync contents.
    #[test]
    fn open_file_rw_replays_dirty_journal_on_open() {
        use crate::fs::{Filesystem, OpenFlags};
        use std::io::{Read, Seek, SeekFrom, Write};

        let mut dev = MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts {
            journaled: true,
            ..writer::FormatOpts::default()
        };
        let payload = b"original\n".repeat(64);
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&payload);
            hfs.create_file(
                &mut dev,
                "/replay.bin",
                &mut src,
                payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // Round 1: do a journaled write — sync persists everything.
        // Capture the journal `start`/`end` afterwards so we can roll
        // `start` back to simulate a crash that lost step 4 of the
        // commit sequence.
        let (jbuf_off, sealed_start, sealed_end) = {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            {
                let mut h = hfs
                    .open_file_rw(
                        &mut dev,
                        std::path::Path::new("/replay.bin"),
                        OpenFlags::default(),
                        None,
                    )
                    .unwrap();
                h.seek(SeekFrom::Start(64)).unwrap();
                h.write_all(b"REPLAYED-DATA-FROM-JOURNAL").unwrap();
                h.sync().unwrap();
            }
            // Sneak a peek at the journal header.
            let mut vh_buf = [0u8; 512];
            dev.read_at(volume_header::VOLUME_HEADER_OFFSET, &mut vh_buf)
                .unwrap();
            let info_block = u32::from_be_bytes(vh_buf[12..16].try_into().unwrap());
            let bs = u32::from_be_bytes(vh_buf[40..44].try_into().unwrap());
            let info_off = u64::from(info_block) * u64::from(bs);
            let mut info = [0u8; 52];
            dev.read_at(info_off, &mut info).unwrap();
            let jbuf_off = u64::from_be_bytes(info[36..44].try_into().unwrap());
            let mut hdr = [0u8; 24];
            dev.read_at(jbuf_off, &mut hdr).unwrap();
            let s = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
            let e = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
            assert_eq!(s, e, "post-sync the journal must be clean");
            (jbuf_off, s, e)
        };
        assert_eq!(sealed_start, sealed_end);

        // Simulate the crash by rewinding the on-disk `start` past
        // the existing transaction. Replay must re-apply it (which is
        // a no-op since the user data is already on disk) and leave
        // the journal clean again.
        {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let mut got = Vec::new();
            hfs.open_file_reader(&mut dev, "/replay.bin")
                .unwrap()
                .read_to_end(&mut got)
                .unwrap();
            assert_eq!(&got[64..64 + 26], b"REPLAYED-DATA-FROM-JOURNAL");
        }
        // Rewind `start` to JHDR_SIZE — the journal-header size we
        // ship at format time (= 512). Now `start != end` and the
        // on-disk transaction is "unapplied" as far as the journal is
        // concerned. We rely on JournalLog::load tolerating a missing
        // checksum recompute because replay only reads start/end.
        let rewound_start: u64 = u64::from(super::journal::JHDR_SIZE);
        // Patch the header in-place.
        let mut hdr = [0u8; 24];
        dev.read_at(jbuf_off, &mut hdr).unwrap();
        hdr[8..16].copy_from_slice(&rewound_start.to_be_bytes());
        dev.write_at(jbuf_off, &hdr).unwrap();

        // Reopen and open the file for writing. The replay should fire
        // and re-apply the transaction. We then close without writing
        // and confirm the contents are intact.
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            let h = hfs
                .open_file_rw(
                    &mut dev,
                    std::path::Path::new("/replay.bin"),
                    OpenFlags::default(),
                    None,
                )
                .unwrap();
            // Reading from the freshly-opened handle should match the
            // journaled contents. The point of the test isn't the
            // bytes — replay already wrote them to disk before we got
            // here — but the journal header itself must now be clean
            // again.
            drop(h);
            let mut hdr = [0u8; 24];
            dev.read_at(jbuf_off, &mut hdr).unwrap();
            let s = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
            let e = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
            assert_eq!(s, e, "replay must leave the journal clean");
        }
    }

    /// Simulate a crash *before* the journal applies its block writes.
    /// We synthesize the state by:
    ///
    ///   1. Doing a real journaled sync (so `end > start` was reached
    ///      and re-equalised).
    ///   2. Rewinding `start` to before the transaction (so the journal
    ///      looks dirty).
    ///   3. Zeroing the user-data block (so the in-place write looks
    ///      lost).
    ///
    /// Then we reopen via [`crate::fs::Filesystem::open_file_rw`] and
    /// verify the journal contents successfully restored the bytes.
    #[test]
    fn replay_on_open_restores_lost_user_data() {
        use crate::fs::{Filesystem, OpenFlags};
        use std::io::{Seek, SeekFrom, Write};

        let mut dev = MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts {
            journaled: true,
            ..writer::FormatOpts::default()
        };
        let payload = vec![0xAAu8; 4096];
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&payload);
            hfs.create_file(
                &mut dev,
                "/x.bin",
                &mut src,
                payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // 1. Journaled sync.
        let (jbuf_off, sealed_end) = {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            {
                let mut h = hfs
                    .open_file_rw(
                        &mut dev,
                        std::path::Path::new("/x.bin"),
                        OpenFlags::default(),
                        None,
                    )
                    .unwrap();
                h.seek(SeekFrom::Start(0)).unwrap();
                h.write_all(&[0xBBu8; 4096]).unwrap();
                h.sync().unwrap();
            }
            let mut vh_buf = [0u8; 512];
            dev.read_at(volume_header::VOLUME_HEADER_OFFSET, &mut vh_buf)
                .unwrap();
            let info_block = u32::from_be_bytes(vh_buf[12..16].try_into().unwrap());
            let bs = u32::from_be_bytes(vh_buf[40..44].try_into().unwrap());
            let info_off = u64::from(info_block) * u64::from(bs);
            let mut info = [0u8; 52];
            dev.read_at(info_off, &mut info).unwrap();
            let jbuf_off = u64::from_be_bytes(info[36..44].try_into().unwrap());
            let mut hdr = [0u8; 24];
            dev.read_at(jbuf_off, &mut hdr).unwrap();
            let e = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
            (jbuf_off, e)
        };

        // 2. Find the file's first data block to corrupt it.
        let dev_off_block0 = {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let CatalogRecord::File(f) = hfs.lookup_path(&mut dev, "/x.bin").unwrap() else {
                panic!("expected file");
            };
            // Read the file record's first inline extent: stored at
            // raw_body[88..96] (start_block, block_count). We grab the
            // run from the writer instead — easier.
            let w = hfs.writer.as_ref().unwrap();
            let body = w
                .catalog
                .get(&writer::OwnedKey {
                    parent_id: ROOT_FOLDER_ID,
                    name: catalog::UniStr::from_str_lossy("x.bin"),
                })
                .expect("catalog body");
            let sb = u32::from_be_bytes(body[88 + 16..88 + 20].try_into().unwrap()); // first ext start
            assert!(sb > 0, "file must have a real data block");
            let _ = f;
            u64::from(sb) * u64::from(hfs.volume_header.block_size)
        };

        // 3. Zero the user-data block on disk, and rewind start so
        //    the journal looks dirty again.
        dev.write_at(dev_off_block0, &[0u8; 4096]).unwrap();
        let mut hdr = [0u8; 24];
        dev.read_at(jbuf_off, &mut hdr).unwrap();
        let rewound: u64 = u64::from(super::journal::JHDR_SIZE);
        hdr[8..16].copy_from_slice(&rewound.to_be_bytes());
        dev.write_at(jbuf_off, &hdr).unwrap();
        let _ = sealed_end;

        // 4. Reopen — replay should restore the 0xBB pattern.
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            let h = hfs
                .open_file_rw(
                    &mut dev,
                    std::path::Path::new("/x.bin"),
                    OpenFlags::default(),
                    None,
                )
                .unwrap();
            drop(h);
        }
        let mut got = [0u8; 4096];
        dev.read_at(dev_off_block0, &mut got).unwrap();
        assert!(
            got.iter().all(|&b| b == 0xBB),
            "replay must have restored the user data"
        );
    }

    /// Round-trip on a journaled image, then run `fsck.hfsplus` on the
    /// resulting bytes. Silently skipped when the binary isn't on PATH.
    #[test]
    fn open_file_rw_journaled_passes_fsck_hfsplus() {
        use crate::fs::{Filesystem, OpenFlags};
        use std::io::{Seek, SeekFrom, Write};
        use std::process::Command;

        let fsck = match Command::new("sh")
            .arg("-c")
            .arg("command -v fsck.hfsplus")
            .output()
        {
            Ok(o) if o.status.success() && !o.stdout.is_empty() => {
                String::from_utf8_lossy(&o.stdout).trim().to_string()
            }
            _ => return, // not installed; skip
        };

        let tmp = tempfile::NamedTempFile::new().expect("tmp");
        let path = tmp.path().to_path_buf();
        let total: u64 = 8 * 1024 * 1024;
        // Truncate to the target size.
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .unwrap();
        f.set_len(total).unwrap();
        drop(f);

        let mut dev = crate::block::FileBackend::open(&path).unwrap();
        let opts = writer::FormatOpts {
            journaled: true,
            volume_name: "fsckTestVol".into(),
            ..writer::FormatOpts::default()
        };
        let payload: Vec<u8> = (0..16 * 1024).map(|i| (i & 0xFF) as u8).collect();
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&payload);
            hfs.create_file(
                &mut dev,
                "/edit.bin",
                &mut src,
                payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            let mut h = hfs
                .open_file_rw(
                    &mut dev,
                    std::path::Path::new("/edit.bin"),
                    OpenFlags::default(),
                    None,
                )
                .unwrap();
            h.seek(SeekFrom::Start(8192)).unwrap();
            h.write_all(b"journal-test-payload").unwrap();
            h.sync().unwrap();
        }
        crate::block::BlockDevice::sync(&mut dev).unwrap();
        drop(dev);

        let out = Command::new(&fsck)
            .arg("-fn")
            .arg(&path)
            .output()
            .expect("run fsck.hfsplus");
        // fsck.hfsplus returns 0 on a clean volume.
        assert!(
            out.status.success(),
            "fsck.hfsplus failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
    }

    /// Path A for `flush`: when a journaled HFS+ image is reopened and
    /// mutated (creating directories, files, removing files), the
    /// subsequent metadata `flush` must route its writes — catalog
    /// B-tree pages, extents-overflow pages, allocation bitmap, and the
    /// two volume headers — through `JournalLog::commit` rather than
    /// applying them in place. We verify this by:
    ///
    ///   1. Formatting a journaled image with one file.
    ///   2. Reopening it, mutating it (add a directory, add a file,
    ///      remove the original) to dirty multiple metadata regions,
    ///      then calling `flush`.
    ///   3. Snapshotting the journal header (`start == end` post-flush).
    ///   4. Reading the post-flush metadata bytes for both volume
    ///      headers so we can corrupt them on disk and prove replay
    ///      restored them.
    ///   5. Corrupting the primary volume header on disk (zeroing it)
    ///      and rewinding the journal `start` to before the flush
    ///      transaction.
    ///   6. Reopening — the journal replay in `HfsPlus::open` must
    ///      restore the volume-header bytes before the catalog open
    ///      attempts to read them. The mutated directory tree must
    ///      then be readable byte-exact.
    #[test]
    fn flush_routes_metadata_through_journal_on_reopen() {
        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts {
            journaled: true,
            ..writer::FormatOpts::default()
        };

        // 1. Initial format + a file + flush. The first flush after
        //    format runs through the Direct sink (no on-disk journal
        //    header yet to route through).
        let initial = b"initial-payload\n".repeat(16);
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&initial);
            hfs.create_file(
                &mut dev,
                "/initial.bin",
                &mut src,
                initial.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // Capture the journal-buffer offset for later poking.
        let jbuf_off = {
            let mut vh_buf = [0u8; 512];
            dev.read_at(volume_header::VOLUME_HEADER_OFFSET, &mut vh_buf)
                .unwrap();
            let info_block = u32::from_be_bytes(vh_buf[12..16].try_into().unwrap());
            let bs = u32::from_be_bytes(vh_buf[40..44].try_into().unwrap());
            assert_ne!(info_block, 0, "journaled volume must have a JIB");
            let info_off = u64::from(info_block) * u64::from(bs);
            let mut info = [0u8; 52];
            dev.read_at(info_off, &mut info).unwrap();
            u64::from_be_bytes(info[36..44].try_into().unwrap())
        };

        // 2. Reopen + mutate + flush. This flush runs through Buffered
        //    sink → JournalLog::commit.
        let new_payload = b"second\n".repeat(32);
        {
            let mut hfs = HfsPlus::open(&mut dev).unwrap();
            // A pre-flush journal must be clean (start == end). The
            // commit machinery in writer::flush relies on that.
            let mut hdr = [0u8; 24];
            dev.read_at(jbuf_off, &mut hdr).unwrap();
            let s = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
            let e = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
            assert_eq!(s, e, "fresh-format flush leaves the journal clean");

            // Multiple mutations: dir + file + remove. This dirties the
            // catalog (always), the bitmap (file allocation + free), and
            // bumps next_cnid (volume header).
            hfs.create_dir(&mut dev, "/added-dir", 0o755, 0, 0).unwrap();
            let mut src = std::io::Cursor::new(&new_payload);
            hfs.create_file(
                &mut dev,
                "/added-file.bin",
                &mut src,
                new_payload.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.remove(&mut dev, "/initial.bin").unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        // 3. Post-flush, the journal must be sealed again (start == end).
        let sealed_end = {
            let mut hdr = [0u8; 24];
            dev.read_at(jbuf_off, &mut hdr).unwrap();
            let s = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
            let e = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
            assert_eq!(
                s, e,
                "Path A for flush requires the journal to seal post-commit"
            );
            e
        };
        assert!(
            sealed_end > u64::from(journal::JHDR_SIZE),
            "the post-mutation flush must have advanced the journal end \
             cursor past the initial JHDR_SIZE — got {sealed_end:#x}"
        );

        // 4. Sanity check that the live image (after the flush, before
        //    corruption) reports the mutations.
        {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let entries = hfs.list_path(&mut dev, "/").unwrap();
            let names: std::collections::BTreeSet<&str> =
                entries.iter().map(|e| e.name.as_str()).collect();
            assert!(names.contains("added-dir"));
            assert!(names.contains("added-file.bin"));
            assert!(
                !names.contains("initial.bin"),
                "removed file must be gone post-flush; got {names:?}"
            );
        }

        // 5. Corrupt the catalog file's on-disk blocks and the
        //    allocation bitmap, then rewind `start` so the journal
        //    looks dirty. The journal entry from the flush above
        //    carries a copy of those bytes — replay must restore them
        //    on the next open.
        //
        // We deliberately do NOT corrupt the volume header itself: the
        // VH at offset 1024 is needed by `read_volume_header` to find
        // the JournalInfoBlock before replay can run. The VH is still
        // covered by the journal transaction (so it would be restored
        // anyway in production), but corrupting it here would block us
        // from reading the JIB pointer.
        let (cat_off, cat_len, bm_off, bm_len) = {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let bs = u64::from(hfs.volume_header.block_size);
            let cat = hfs.volume_header.catalog_file.extents[0];
            let bm = hfs.volume_header.allocation_file.extents[0];
            (
                u64::from(cat.start_block) * bs,
                u64::from(cat.block_count) * bs,
                u64::from(bm.start_block) * bs,
                u64::from(bm.block_count) * bs,
            )
        };
        // Zero the catalog and bitmap so the on-disk structures are
        // unusable without replay.
        let zeros_cat = vec![0u8; cat_len as usize];
        dev.write_at(cat_off, &zeros_cat).unwrap();
        let zeros_bm = vec![0u8; bm_len as usize];
        dev.write_at(bm_off, &zeros_bm).unwrap();
        // Rewind start.
        let mut hdr = [0u8; 24];
        dev.read_at(jbuf_off, &mut hdr).unwrap();
        let rewound: u64 = u64::from(journal::JHDR_SIZE);
        hdr[8..16].copy_from_slice(&rewound.to_be_bytes());
        dev.write_at(jbuf_off, &hdr).unwrap();

        // Without replay, the catalog is unreadable. With replay, the
        // bytes come back and the catalog opens normally.
        {
            let hfs = HfsPlus::open(&mut dev).unwrap();
            let entries = hfs.list_path(&mut dev, "/").unwrap();
            let names: std::collections::BTreeSet<&str> =
                entries.iter().map(|e| e.name.as_str()).collect();
            assert!(
                names.contains("added-dir"),
                "replay must restore the catalog so the dir is visible; \
                 got {names:?}"
            );
            assert!(
                names.contains("added-file.bin"),
                "replay must restore the catalog so the file is visible; \
                 got {names:?}"
            );
            assert!(
                !names.contains("initial.bin"),
                "removed file must not reappear after replay; got {names:?}"
            );

            // The replayed file's bytes should be intact too.
            let mut r = hfs.open_file_reader(&mut dev, "/added-file.bin").unwrap();
            let mut got = Vec::new();
            std::io::Read::read_to_end(&mut r, &mut got).unwrap();
            assert_eq!(
                got, new_payload,
                "file data referenced by the replayed catalog must match"
            );

            // And the journal must be clean again after replay.
            let mut hdr = [0u8; 24];
            dev.read_at(jbuf_off, &mut hdr).unwrap();
            let s = u64::from_be_bytes(hdr[8..16].try_into().unwrap());
            let e = u64::from_be_bytes(hdr[16..24].try_into().unwrap());
            assert_eq!(s, e, "replay leaves the journal sealed");
        }
    }

    #[test]
    fn open_file_ro_random_seek_hfs_plus() {
        use crate::fs::Filesystem;
        use std::io::{Read, Seek, SeekFrom};

        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();
        let data: Vec<u8> = (0..6000u32).map(|i| (i & 0xFF) as u8).collect();
        {
            let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
            let mut src = std::io::Cursor::new(&data);
            hfs.create_file(
                &mut dev,
                "/ro.bin",
                &mut src,
                data.len() as u64,
                0o644,
                0,
                0,
            )
            .unwrap();
            hfs.flush(&mut dev).unwrap();
        }

        let mut hfs = HfsPlus::open(&mut dev).unwrap();
        let mut h = hfs
            .open_file_ro(&mut dev, std::path::Path::new("/ro.bin"))
            .expect("open_file_ro");
        assert_eq!(h.len(), data.len() as u64);
        assert!(!h.is_empty());

        h.seek(SeekFrom::Start(3333)).unwrap();
        let mut buf = [0u8; 96];
        h.read_exact(&mut buf).unwrap();
        assert_eq!(&buf[..], &data[3333..3429]);

        h.seek(SeekFrom::Start(40)).unwrap();
        let mut buf2 = [0u8; 64];
        h.read_exact(&mut buf2).unwrap();
        assert_eq!(&buf2[..], &data[40..104]);
    }

    // ----------------------------------------------------------------
    // HFSCompression (decmpfs) integration tests
    // ----------------------------------------------------------------
    //
    // Our writer doesn't emit an attributes B-tree, so to test the
    // read path we:
    //
    //   1. format + create_file an empty placeholder file;
    //   2. *before* flush, mutate writer state directly to:
    //      - flip UF_COMPRESSED on the file's owner_flags;
    //      - allocate blocks for the attributes file;
    //      - point writer.attributes_file / volume_header.attributes_file
    //        at those blocks;
    //      - for type-4 tests, allocate + register the resource fork's
    //        extents in the on-disk file body too;
    //   3. flush (writes a normal catalog + VH referencing the new
    //      attributes file extents);
    //   4. lay down a synthesized 2-node attributes B-tree (header +
    //      leaf) in the allocated blocks;
    //   5. for type-4 tests, lay down a synthesized resource fork in
    //      its allocated blocks;
    //   6. re-open and read the file — the read path inflates the
    //      decmpfs payload and returns logical bytes.

    /// Build the 16-byte decmpfs header for `compression_type` /
    /// `uncompressed_size`. Magic is big-endian, the rest little-endian.
    fn make_decmpfs_header(compression_type: u32, uncompressed_size: u64) -> [u8; 16] {
        let mut hdr = [0u8; 16];
        hdr[0..4].copy_from_slice(&decmpfs::DECMPFS_MAGIC.to_be_bytes());
        hdr[4..8].copy_from_slice(&compression_type.to_le_bytes());
        hdr[8..16].copy_from_slice(&uncompressed_size.to_le_bytes());
        hdr
    }

    /// Construct a single-leaf attributes B-tree containing exactly
    /// one inline-data record for (file_id, "com.apple.decmpfs"). The
    /// returned buffer is two `node_size`-byte nodes back-to-back:
    /// node 0 is the B-tree header node, node 1 is the leaf.
    fn synth_attributes_btree(node_size: u32, file_id: u32, decmpfs_value: &[u8]) -> Vec<u8> {
        use btree::{HEADER_REC_SIZE, KIND_HEADER, KIND_LEAF, NODE_DESCRIPTOR_SIZE};
        let ns = node_size as usize;
        // ----- node 0: header node.
        let mut hdr = vec![0u8; ns];
        // BTNodeDescriptor: kind = header, height = 0, numRecords = 3.
        hdr[8] = KIND_HEADER as u8;
        hdr[9] = 0;
        hdr[10..12].copy_from_slice(&3u16.to_be_bytes());
        // BTHeaderRec at offset 14.
        let h = NODE_DESCRIPTOR_SIZE;
        hdr[h..h + 2].copy_from_slice(&1u16.to_be_bytes()); // tree_depth
        hdr[h + 2..h + 6].copy_from_slice(&1u32.to_be_bytes()); // root_node = leaf
        hdr[h + 6..h + 10].copy_from_slice(&1u32.to_be_bytes()); // leaf_records
        hdr[h + 10..h + 14].copy_from_slice(&1u32.to_be_bytes()); // first_leaf
        hdr[h + 14..h + 18].copy_from_slice(&1u32.to_be_bytes()); // last_leaf
        hdr[h + 18..h + 20].copy_from_slice(&(node_size as u16).to_be_bytes());
        hdr[h + 20..h + 22].copy_from_slice(&264u16.to_be_bytes()); // maxKeyLength
        hdr[h + 22..h + 26].copy_from_slice(&2u32.to_be_bytes()); // total_nodes
        hdr[h + 26..h + 30].copy_from_slice(&0u32.to_be_bytes()); // free_nodes
        hdr[h + 32..h + 36].copy_from_slice(&node_size.to_be_bytes()); // clumpSize
        hdr[h + 36] = 0; // btreeType = HFS+
        hdr[h + 37] = 0xCF; // keyCompareType = case-fold (plain HFS+)
        hdr[h + 38..h + 42].copy_from_slice(&6u32.to_be_bytes()); // big-keys + variable-index
        // Map record fills the rest. Offset table at the tail.
        let user_off = NODE_DESCRIPTOR_SIZE + HEADER_REC_SIZE;
        let map_off = user_off + 128;
        let offsets_table = 2 * 4;
        let free_off = ns - offsets_table;
        let offs = [
            NODE_DESCRIPTOR_SIZE as u16,
            user_off as u16,
            map_off as u16,
            free_off as u16,
        ];
        for (i, &o) in offs.iter().enumerate() {
            let pos = ns - 2 * (i + 1);
            hdr[pos..pos + 2].copy_from_slice(&o.to_be_bytes());
        }
        // Map: nodes 0 and 1 both in use.
        hdr[map_off] = 0b1100_0000;

        // ----- node 1: leaf with one record.
        let name = "com.apple.decmpfs";
        let name_units: Vec<u16> = name.encode_utf16().collect();
        let name_len = name_units.len();
        // Key bytes.
        let mut key_buf = Vec::new();
        let key_payload_len = 12 + 2 * name_len;
        key_buf.extend_from_slice(&(key_payload_len as u16).to_be_bytes());
        key_buf.extend_from_slice(&0u16.to_be_bytes()); // pad
        key_buf.extend_from_slice(&file_id.to_be_bytes());
        key_buf.extend_from_slice(&0u32.to_be_bytes()); // start_block
        key_buf.extend_from_slice(&(name_len as u16).to_be_bytes());
        for u in &name_units {
            key_buf.extend_from_slice(&u.to_be_bytes());
        }
        // Pad key to even (already is — 14 + 2*N).
        // Record body: inline-data.
        let mut body = Vec::new();
        body.extend_from_slice(&attributes::REC_INLINE_DATA.to_be_bytes());
        body.extend_from_slice(&0u32.to_be_bytes()); // reserved
        body.extend_from_slice(&(decmpfs_value.len() as u32).to_be_bytes());
        body.extend_from_slice(decmpfs_value);

        let rec = [key_buf.clone(), body.clone()].concat();
        let mut leaf = vec![0u8; ns];
        leaf[8] = KIND_LEAF as u8;
        leaf[9] = 1; // height
        leaf[10..12].copy_from_slice(&1u16.to_be_bytes());
        // Record at the start of the data area.
        let start = NODE_DESCRIPTOR_SIZE;
        let end = start + rec.len();
        assert!(end <= ns - 4, "attribute record overruns node");
        leaf[start..end].copy_from_slice(&rec);
        // Offset table: two entries (start of record + start of free).
        let l_offs = [start as u16, end as u16];
        for (i, &o) in l_offs.iter().enumerate() {
            let pos = ns - 2 * (i + 1);
            leaf[pos..pos + 2].copy_from_slice(&o.to_be_bytes());
        }

        let mut out = Vec::with_capacity(2 * ns);
        out.extend_from_slice(&hdr);
        out.extend_from_slice(&leaf);
        out
    }

    /// Locate the catalog file's encoded body inside `writer.catalog`
    /// by walking it to find the entry whose `(parent_id, name)` matches
    /// `path_name` under the root folder, and return a mutable handle.
    fn find_root_file_body_mut<'a>(w: &'a mut writer::Writer, file_name: &str) -> &'a mut Vec<u8> {
        // The writer keeps a BTreeMap<OwnedKey, Vec<u8>>. We need to
        // find the entry whose key is (ROOT_FOLDER_ID, file_name) and
        // is a REC_FILE. Construct the equivalent UniStr to match.
        let target = UniStr::from_str_lossy(file_name);
        for (k, body) in w.catalog.iter_mut() {
            if k.parent_id == catalog::ROOT_FOLDER_ID
                && k.name.code_units == target.code_units
                && body.len() >= 2
                && i16::from_be_bytes([body[0], body[1]]) == catalog::REC_FILE
            {
                return body;
            }
        }
        panic!("no catalog file record for /{file_name}");
    }

    #[cfg(feature = "gzip")]
    #[test]
    fn read_decmpfs_type3_inline_zlib() {
        use flate2::{Compression, write::ZlibEncoder};
        use std::io::Write;

        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();
        let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();

        // Empty placeholder file. The actual logical content will come
        // from the decmpfs xattr we install below.
        let mut empty = std::io::Cursor::new(Vec::<u8>::new());
        let cnid = hfs
            .create_file(&mut dev, "/cmp.bin", &mut empty, 0, 0o644, 0, 0)
            .unwrap();

        let plain = b"hello hfsplus decmpfs inline zlib world!\n".repeat(20);
        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
        enc.write_all(&plain).unwrap();
        let compressed = enc.finish().unwrap();

        // Build the decmpfs xattr payload: 16-byte header (type 3) +
        // inline zlib bytes.
        let mut xattr = Vec::new();
        xattr.extend_from_slice(&make_decmpfs_header(3, plain.len() as u64));
        xattr.extend_from_slice(&compressed);

        // Allocate two attributes-file blocks (= 2 * node_size / block_size).
        let block_size = hfs.volume_header.block_size;
        let node_size = opts.node_size;
        let attr_bytes_needed = (2 * node_size) as u64;
        let blocks_needed = u32::try_from(attr_bytes_needed.div_ceil(u64::from(block_size)))
            .expect("attribute fork block count fits in u32");
        let w = hfs.writer.as_mut().unwrap();
        let attr_start_block = w.allocate(blocks_needed).expect("allocate attributes file");

        // Update writer + VH attributes_file ForkData.
        let mut attr_fork = ForkData {
            logical_size: attr_bytes_needed,
            clump_size: node_size,
            total_blocks: blocks_needed,
            extents: Default::default(),
        };
        attr_fork.extents[0] = volume_header::ExtentDescriptor {
            start_block: attr_start_block,
            block_count: blocks_needed,
        };
        w.attributes_file = attr_fork;
        hfs.volume_header.attributes_file = attr_fork;

        // Flip UF_COMPRESSED on the file's owner_flags (offset 41 of
        // the encoded REC_FILE body) and zero the resource fork
        // (already empty post-create_file, defensive).
        {
            let body = find_root_file_body_mut(w, "cmp.bin");
            body[41] |= decmpfs::UF_COMPRESSED;
        }

        // Flush so the on-disk catalog + volume header pick up our
        // changes.
        hfs.flush(&mut dev).unwrap();

        // Lay down the synthesized 2-node attributes B-tree at its
        // extents start.
        let attr_tree = synth_attributes_btree(node_size, cnid, &xattr);
        let attr_off = u64::from(attr_start_block) * u64::from(block_size);
        dev.write_at(attr_off, &attr_tree).unwrap();

        // Now re-open and read the file via the public reader.
        let hfs = HfsPlus::open(&mut dev).unwrap();
        let mut r = hfs.open_file_reader(&mut dev, "/cmp.bin").unwrap();
        let mut got = Vec::new();
        std::io::Read::read_to_end(&mut r, &mut got).unwrap();
        assert_eq!(got.len(), plain.len(), "decompressed length matches header");
        assert_eq!(got, plain, "decompressed bytes match original");
    }

    #[cfg(feature = "gzip")]
    #[test]
    fn read_decmpfs_type4_resource_fork_zlib() {
        use flate2::{Compression, write::ZlibEncoder};
        use std::io::Write;

        let mut dev = crate::block::MemoryBackend::new(16 * 1024 * 1024);
        let opts = writer::FormatOpts::default();
        let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();

        let mut empty = std::io::Cursor::new(Vec::<u8>::new());
        let cnid = hfs
            .create_file(&mut dev, "/big.bin", &mut empty, 0, 0o644, 0, 0)
            .unwrap();

        // Build two blocks: first 64 KiB, then a tail.
        let mut plain = Vec::new();
        plain.extend(std::iter::repeat_n(0xABu8, decmpfs::HFSCOMPRESS_BLOCK_SIZE));
        plain.extend_from_slice(b"hfscompression type-4 tail data");
        let block1 = &plain[..decmpfs::HFSCOMPRESS_BLOCK_SIZE];
        let block2 = &plain[decmpfs::HFSCOMPRESS_BLOCK_SIZE..];

        let compress = |data: &[u8]| -> Vec<u8> {
            let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
            e.write_all(data).unwrap();
            e.finish().unwrap()
        };
        let c1 = compress(block1);
        let c2 = compress(block2);

        // Assemble resource-fork bytes (data area at offset 256, table
        // base at data_offset + 4).
        let block_count: u32 = 2;
        let table_size = 4 + 8 * block_count as usize;
        let blk1_off = table_size as u32;
        let blk2_off = blk1_off + c1.len() as u32;

        let mut rdata = Vec::new();
        let inner_size: u32 = (table_size + c1.len() + c2.len()) as u32;
        rdata.extend_from_slice(&inner_size.to_be_bytes());
        rdata.extend_from_slice(&block_count.to_le_bytes());
        rdata.extend_from_slice(&blk1_off.to_le_bytes());
        rdata.extend_from_slice(&(c1.len() as u32).to_le_bytes());
        rdata.extend_from_slice(&blk2_off.to_le_bytes());
        rdata.extend_from_slice(&(c2.len() as u32).to_le_bytes());
        rdata.extend_from_slice(&c1);
        rdata.extend_from_slice(&c2);

        let data_offset: u32 = 256;
        let data_length: u32 = rdata.len() as u32;
        let mut rf = Vec::new();
        rf.extend_from_slice(&data_offset.to_be_bytes());
        rf.extend_from_slice(&(data_offset + data_length).to_be_bytes());
        rf.extend_from_slice(&data_length.to_be_bytes());
        rf.extend_from_slice(&0u32.to_be_bytes());
        rf.resize(data_offset as usize, 0);
        rf.extend_from_slice(&rdata);

        // decmpfs xattr: header only (type 4 = data in resource fork).
        let xattr = make_decmpfs_header(4, plain.len() as u64).to_vec();

        // Layout:
        //   - allocate blocks for the attributes B-tree (2 nodes)
        //   - allocate blocks for the resource fork (covers rf.len())
        let block_size = hfs.volume_header.block_size;
        let node_size = opts.node_size;
        let attr_bytes_needed = (2 * node_size) as u64;
        let attr_blocks = u32::try_from(attr_bytes_needed.div_ceil(u64::from(block_size))).unwrap();
        let rf_blocks = u32::try_from((rf.len() as u64).div_ceil(u64::from(block_size))).unwrap();
        let w = hfs.writer.as_mut().unwrap();
        let attr_start = w.allocate(attr_blocks).unwrap();
        let rf_start = w.allocate(rf_blocks).unwrap();

        // Attributes-file fork.
        let mut attr_fork = ForkData {
            logical_size: attr_bytes_needed,
            clump_size: node_size,
            total_blocks: attr_blocks,
            extents: Default::default(),
        };
        attr_fork.extents[0] = volume_header::ExtentDescriptor {
            start_block: attr_start,
            block_count: attr_blocks,
        };
        w.attributes_file = attr_fork;
        hfs.volume_header.attributes_file = attr_fork;

        // Resource fork: rewrite the file's catalog body so its
        // resourceFork ForkData (offset 168..248) points at rf_start.
        {
            let body = find_root_file_body_mut(w, "big.bin");
            body[41] |= decmpfs::UF_COMPRESSED;
            // logical_size (8 BE) = rf.len()
            body[168..176].copy_from_slice(&(rf.len() as u64).to_be_bytes());
            // clump_size (4 BE)
            body[176..180].copy_from_slice(&block_size.to_be_bytes());
            // total_blocks (4 BE)
            body[180..184].copy_from_slice(&rf_blocks.to_be_bytes());
            // extents[0]
            body[184..188].copy_from_slice(&rf_start.to_be_bytes());
            body[188..192].copy_from_slice(&rf_blocks.to_be_bytes());
        }

        hfs.flush(&mut dev).unwrap();

        // Write the synthesized attribute tree and resource-fork bytes
        // to the allocated blocks.
        let attr_tree = synth_attributes_btree(node_size, cnid, &xattr);
        let attr_off = u64::from(attr_start) * u64::from(block_size);
        dev.write_at(attr_off, &attr_tree).unwrap();
        let rf_off = u64::from(rf_start) * u64::from(block_size);
        dev.write_at(rf_off, &rf).unwrap();

        let hfs = HfsPlus::open(&mut dev).unwrap();
        let mut r = hfs.open_file_reader(&mut dev, "/big.bin").unwrap();
        let mut got = Vec::new();
        std::io::Read::read_to_end(&mut r, &mut got).unwrap();
        assert_eq!(got.len(), plain.len());
        assert_eq!(got, plain);
    }

    #[test]
    fn read_decmpfs_unsupported_codec_errors_clearly() {
        // A file marked UF_COMPRESSED whose xattr advertises an
        // LZVN/LZFSE codec should produce a clear `Unsupported` error
        // rather than data corruption. We exercise this with type 7
        // (LZVN inline).
        let mut dev = crate::block::MemoryBackend::new(8 * 1024 * 1024);
        let opts = writer::FormatOpts::default();
        let mut hfs = HfsPlus::format(&mut dev, &opts).unwrap();
        let mut empty = std::io::Cursor::new(Vec::<u8>::new());
        let cnid = hfs
            .create_file(&mut dev, "/lzvn.bin", &mut empty, 0, 0o644, 0, 0)
            .unwrap();

        // decmpfs header advertises type 7 (LZVN inline), but we ship
        // no payload — the test only checks the codec dispatch path.
        let xattr = make_decmpfs_header(7, 4).to_vec();

        let block_size = hfs.volume_header.block_size;
        let node_size = opts.node_size;
        let attr_bytes_needed = (2 * node_size) as u64;
        let attr_blocks = u32::try_from(attr_bytes_needed.div_ceil(u64::from(block_size))).unwrap();
        let w = hfs.writer.as_mut().unwrap();
        let attr_start = w.allocate(attr_blocks).unwrap();
        let mut attr_fork = ForkData {
            logical_size: attr_bytes_needed,
            clump_size: node_size,
            total_blocks: attr_blocks,
            extents: Default::default(),
        };
        attr_fork.extents[0] = volume_header::ExtentDescriptor {
            start_block: attr_start,
            block_count: attr_blocks,
        };
        w.attributes_file = attr_fork;
        hfs.volume_header.attributes_file = attr_fork;
        {
            let body = find_root_file_body_mut(w, "lzvn.bin");
            body[41] |= decmpfs::UF_COMPRESSED;
        }
        hfs.flush(&mut dev).unwrap();
        let attr_tree = synth_attributes_btree(node_size, cnid, &xattr);
        let attr_off = u64::from(attr_start) * u64::from(block_size);
        dev.write_at(attr_off, &attr_tree).unwrap();

        let hfs = HfsPlus::open(&mut dev).unwrap();
        let err = hfs.open_file_reader(&mut dev, "/lzvn.bin").err().unwrap();
        assert!(
            matches!(err, crate::Error::Unsupported(_)),
            "LZVN should surface as Unsupported, got {err:?}"
        );
    }
}