btrfs-disk 0.13.0

Platform-independent parsing and writing of btrfs on-disk structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
//! # Typed Rust structs for btrfs tree item payloads
//!
//! Each on-disk item type has a corresponding struct with a `parse` method
//! that reads from a raw byte buffer using safe LE reader helpers. These
//! structs are the public API for item data; display formatting lives in
//! the `cli` crate.

/// Read a UUID (16 bytes) from a `Buf` cursor, advancing it by 16 bytes.
use crate::util::get_uuid;
use crate::{
    raw,
    tree::{DiskKey, KeyType, ObjectId},
    util::{raw_crc32c, write_disk_key},
};
use bytes::{Buf, BufMut};
use std::{fmt, mem};
use uuid::Uuid;

bitflags::bitflags! {
    /// Block group / chunk type flags: the combination of chunk type
    /// (DATA, SYSTEM, METADATA) and RAID profile stored in on-disk chunk
    /// items and block group items.
    ///
    /// Display produces the dump-tree format: `DATA|DUP`, `METADATA|single`, etc.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct BlockGroupFlags: u64 {
        const DATA     = raw::BTRFS_BLOCK_GROUP_DATA as u64;
        const SYSTEM   = raw::BTRFS_BLOCK_GROUP_SYSTEM as u64;
        const METADATA = raw::BTRFS_BLOCK_GROUP_METADATA as u64;
        const RAID0    = raw::BTRFS_BLOCK_GROUP_RAID0 as u64;
        const RAID1    = raw::BTRFS_BLOCK_GROUP_RAID1 as u64;
        const DUP      = raw::BTRFS_BLOCK_GROUP_DUP as u64;
        const RAID10   = raw::BTRFS_BLOCK_GROUP_RAID10 as u64;
        const RAID5    = raw::BTRFS_BLOCK_GROUP_RAID5 as u64;
        const RAID6    = raw::BTRFS_BLOCK_GROUP_RAID6 as u64;
        const RAID1C3  = raw::BTRFS_BLOCK_GROUP_RAID1C3 as u64;
        const RAID1C4  = raw::BTRFS_BLOCK_GROUP_RAID1C4 as u64;

        /// Explicit "single" marker (bit 48). When no profile bits are
        /// set, the allocation is also single.
        const SINGLE     = raw::BTRFS_AVAIL_ALLOC_BIT_SINGLE;

        /// Pseudo-type used for the global reservation pool.
        const GLOBAL_RSV = raw::BTRFS_SPACE_INFO_GLOBAL_RSV;
    }
}

impl BlockGroupFlags {
    /// Returns the human-readable chunk type name.
    #[must_use]
    pub fn type_name(self) -> &'static str {
        if self.contains(Self::GLOBAL_RSV) {
            return "GlobalReserve";
        }
        let ty = self & (Self::DATA | Self::SYSTEM | Self::METADATA);
        match ty {
            t if t == Self::DATA => "Data",
            t if t == Self::SYSTEM => "System",
            t if t == Self::METADATA => "Metadata",
            t if t == Self::DATA | Self::METADATA => "Data+Metadata",
            _ => "unknown",
        }
    }

    /// Returns the RAID profile name, or `"single"` when no profile bit is set.
    #[must_use]
    pub fn profile_name(self) -> &'static str {
        let profile = self
            & (Self::RAID0
                | Self::RAID1
                | Self::DUP
                | Self::RAID10
                | Self::RAID5
                | Self::RAID6
                | Self::RAID1C3
                | Self::RAID1C4
                | Self::SINGLE);
        match profile {
            p if p == Self::RAID0 => "RAID0",
            p if p == Self::RAID1 => "RAID1",
            p if p == Self::DUP => "DUP",
            p if p == Self::RAID10 => "RAID10",
            p if p == Self::RAID5 => "RAID5",
            p if p == Self::RAID6 => "RAID6",
            p if p == Self::RAID1C3 => "RAID1C3",
            p if p == Self::RAID1C4 => "RAID1C4",
            // Both explicit SINGLE and no-profile-bits mean "single".
            _ => "single",
        }
    }
}

bitflags::bitflags! {
    /// Inode item flags stored in `btrfs_inode_item::flags`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct InodeFlags: u64 {
        const NODATASUM      = raw::BTRFS_INODE_NODATASUM as u64;
        const NODATACOW      = raw::BTRFS_INODE_NODATACOW as u64;
        const READONLY       = raw::BTRFS_INODE_READONLY as u64;
        const NOCOMPRESS     = raw::BTRFS_INODE_NOCOMPRESS as u64;
        const PREALLOC       = raw::BTRFS_INODE_PREALLOC as u64;
        const SYNC           = raw::BTRFS_INODE_SYNC as u64;
        const IMMUTABLE      = raw::BTRFS_INODE_IMMUTABLE as u64;
        const APPEND         = raw::BTRFS_INODE_APPEND as u64;
        const NODUMP         = raw::BTRFS_INODE_NODUMP as u64;
        const NOATIME        = raw::BTRFS_INODE_NOATIME as u64;
        const DIRSYNC        = raw::BTRFS_INODE_DIRSYNC as u64;
        const COMPRESS       = raw::BTRFS_INODE_COMPRESS as u64;
        const ROOT_ITEM_INIT = raw::BTRFS_INODE_ROOT_ITEM_INIT as u64;
        // Preserve unknown bits from the on-disk value.
        const _ = !0;
    }
}

impl fmt::Display for InodeFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        const NAMES: &[(InodeFlags, &str)] = &[
            (InodeFlags::NODATASUM, "NODATASUM"),
            (InodeFlags::NODATACOW, "NODATACOW"),
            (InodeFlags::READONLY, "READONLY"),
            (InodeFlags::NOCOMPRESS, "NOCOMPRESS"),
            (InodeFlags::PREALLOC, "PREALLOC"),
            (InodeFlags::SYNC, "SYNC"),
            (InodeFlags::IMMUTABLE, "IMMUTABLE"),
            (InodeFlags::APPEND, "APPEND"),
            (InodeFlags::NODUMP, "NODUMP"),
            (InodeFlags::NOATIME, "NOATIME"),
            (InodeFlags::DIRSYNC, "DIRSYNC"),
            (InodeFlags::COMPRESS, "COMPRESS"),
            (InodeFlags::ROOT_ITEM_INIT, "ROOT_ITEM_INIT"),
        ];
        let known: InodeFlags = NAMES
            .iter()
            .fold(InodeFlags::empty(), |a, &(flag, _)| a | flag);
        let mut parts: Vec<String> = NAMES
            .iter()
            .filter(|&&(flag, _)| self.contains(flag))
            .map(|&(_, name)| name.to_string())
            .collect();
        let unknown = *self & !known;
        if !unknown.is_empty() {
            parts.push(format!("UNKNOWN: 0x{:x}", unknown.bits()));
        }
        if parts.is_empty() {
            write!(f, "none")
        } else {
            write!(f, "{}", parts.join("|"))
        }
    }
}
/// Btrfs timestamp (seconds + nanoseconds since Unix epoch).
#[derive(Debug, Clone, Copy)]
pub struct Timespec {
    /// Seconds since 1970-01-01 00:00:00 UTC.
    pub sec: u64,
    /// Nanosecond component (`0..999_999_999`).
    pub nsec: u32,
}

impl Timespec {
    fn parse(buf: &mut &[u8]) -> Self {
        Self {
            sec: buf.get_u64_le(),
            nsec: buf.get_u32_le(),
        }
    }

    /// Serialize to 12 bytes (8-byte sec + 4-byte nsec).
    fn write_to(&self, buf: &mut Vec<u8>) {
        buf.put_u64_le(self.sec);
        buf.put_u32_le(self.nsec);
    }
}

/// Compression type for file extents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// See also `btrfs_uapi::defrag::CompressType` which omits `None`/`Unknown`
/// for use in ioctl requests.
pub enum CompressionType {
    /// No compression.
    None,
    /// Zlib (deflate) compression.
    Zlib,
    /// LZO compression (btrfs per-sector format).
    Lzo,
    /// Zstandard compression.
    Zstd,
    /// Unrecognized compression type byte.
    Unknown(u8),
}

impl CompressionType {
    /// Convert a raw on-disk compression type byte to a `CompressionType` variant.
    #[must_use]
    pub fn from_raw(v: u8) -> Self {
        match v {
            0 => Self::None,
            1 => Self::Zlib,
            2 => Self::Lzo,
            3 => Self::Zstd,
            _ => Self::Unknown(v),
        }
    }

    /// Return the human-readable name of this compression type.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Zlib => "zlib",
            Self::Lzo => "lzo",
            Self::Zstd => "zstd",
            Self::Unknown(_) => "unknown",
        }
    }

    /// Convert back to the raw on-disk byte value.
    #[must_use]
    pub fn to_raw(self) -> u8 {
        match self {
            Self::None => 0,
            Self::Zlib => 1,
            Self::Lzo => 2,
            Self::Zstd => 3,
            Self::Unknown(v) => v,
        }
    }
}

/// File extent type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileExtentType {
    /// Data stored directly in the tree leaf (small files or file tails).
    Inline,
    /// Data stored in a separate disk extent, referenced by logical address.
    Regular,
    /// Preallocated extent (reserved but not yet written).
    Prealloc,
    /// Unrecognized extent type byte.
    Unknown(u8),
}

impl FileExtentType {
    /// Convert a raw on-disk extent type byte to a `FileExtentType` variant.
    #[must_use]
    pub fn from_raw(v: u8) -> Self {
        match u32::from(v) {
            raw::BTRFS_FILE_EXTENT_INLINE => Self::Inline,
            raw::BTRFS_FILE_EXTENT_REG => Self::Regular,
            raw::BTRFS_FILE_EXTENT_PREALLOC => Self::Prealloc,
            _ => Self::Unknown(v),
        }
    }

    /// Return the human-readable name of this extent type.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Inline => "inline",
            Self::Regular => "regular",
            Self::Prealloc => "prealloc",
            Self::Unknown(_) => "unknown",
        }
    }

    /// Convert back to the raw on-disk byte value.
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    pub fn to_raw(self) -> u8 {
        match self {
            Self::Inline => raw::BTRFS_FILE_EXTENT_INLINE as u8,
            Self::Regular => raw::BTRFS_FILE_EXTENT_REG as u8,
            Self::Prealloc => raw::BTRFS_FILE_EXTENT_PREALLOC as u8,
            Self::Unknown(v) => v,
        }
    }
}

/// Directory entry file type, stored in `btrfs_dir_item::type`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType {
    /// Unknown file type (0).
    Unknown,
    /// Regular file.
    RegFile,
    /// Directory.
    Dir,
    /// Character device.
    Chrdev,
    /// Block device.
    Blkdev,
    /// Named pipe (FIFO).
    Fifo,
    /// Unix domain socket.
    Sock,
    /// Symbolic link.
    Symlink,
    /// Extended attribute (used in `XATTR_ITEM` entries).
    Xattr,
    /// Unrecognized file type byte.
    Other(u8),
}

impl FileType {
    /// Convert a raw on-disk file type byte to a `FileType` variant.
    #[must_use]
    pub fn from_raw(v: u8) -> Self {
        match u32::from(v) {
            raw::BTRFS_FT_UNKNOWN => Self::Unknown,
            raw::BTRFS_FT_REG_FILE => Self::RegFile,
            raw::BTRFS_FT_DIR => Self::Dir,
            raw::BTRFS_FT_CHRDEV => Self::Chrdev,
            raw::BTRFS_FT_BLKDEV => Self::Blkdev,
            raw::BTRFS_FT_FIFO => Self::Fifo,
            raw::BTRFS_FT_SOCK => Self::Sock,
            raw::BTRFS_FT_SYMLINK => Self::Symlink,
            raw::BTRFS_FT_XATTR => Self::Xattr,
            _ => Self::Other(v),
        }
    }

    /// Return the human-readable name of this file type (matches btrfs-progs output).
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Unknown | Self::Other(_) => "UNKNOWN",
            Self::RegFile => "FILE",
            Self::Dir => "DIR",
            Self::Chrdev => "CHRDEV",
            Self::Blkdev => "BLKDEV",
            Self::Fifo => "FIFO",
            Self::Sock => "SOCK",
            Self::Symlink => "SYMLINK",
            Self::Xattr => "XATTR",
        }
    }
}

/// Inode metadata, stored as `INODE_ITEM` in the FS tree.
///
/// Contains POSIX attributes (uid, gid, mode, timestamps) plus btrfs-specific
/// fields (flags, sequence number, block group hint).
#[derive(Debug, Clone)]
pub struct InodeItem {
    /// Generation when this inode was created.
    pub generation: u64,
    /// Transaction ID of the last modification.
    pub transid: u64,
    /// Logical file size in bytes.
    pub size: u64,
    /// Total on-disk bytes used (including all copies for RAID).
    pub nbytes: u64,
    /// Block group hint for new allocations.
    pub block_group: u64,
    /// Hard link count.
    pub nlink: u32,
    /// Owner user ID.
    pub uid: u32,
    /// Owner group ID.
    pub gid: u32,
    /// POSIX file mode (type + permissions).
    pub mode: u32,
    /// Device number (for character/block device inodes).
    pub rdev: u64,
    /// Inode flags (NODATASUM, COMPRESS, etc.).
    pub flags: InodeFlags,
    /// NFS-compatible change sequence number.
    pub sequence: u64,
    /// Last access time.
    pub atime: Timespec,
    /// Last change time (inode metadata).
    pub ctime: Timespec,
    /// Last modification time (file data).
    pub mtime: Timespec,
    /// Creation time.
    pub otime: Timespec,
}

impl InodeItem {
    /// Parse an inode item from a raw byte buffer. Returns `None` if the
    /// buffer is too small.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_inode_item>() {
            return None;
        }
        let mut buf = data;
        Some(Self {
            generation: buf.get_u64_le(),
            transid: buf.get_u64_le(),
            size: buf.get_u64_le(),
            nbytes: buf.get_u64_le(),
            block_group: buf.get_u64_le(),
            nlink: buf.get_u32_le(),
            uid: buf.get_u32_le(),
            gid: buf.get_u32_le(),
            mode: buf.get_u32_le(),
            rdev: buf.get_u64_le(),
            flags: InodeFlags::from_bits_truncate(buf.get_u64_le()),
            sequence: buf.get_u64_le(),
            // Skip reserved[4] (4 x u64 = 32 bytes)
            atime: {
                buf.advance(32);
                Timespec::parse(&mut buf)
            },
            ctime: Timespec::parse(&mut buf),
            mtime: Timespec::parse(&mut buf),
            otime: Timespec::parse(&mut buf),
        })
    }
}

/// Parameters for creating an inode item.
pub struct InodeItemArgs {
    /// Generation and transid.
    pub generation: u64,
    /// Logical file size.
    pub size: u64,
    /// On-disk bytes used.
    pub nbytes: u64,
    /// Hard link count.
    pub nlink: u32,
    /// Owner user ID.
    pub uid: u32,
    /// Owner group ID.
    pub gid: u32,
    /// POSIX file mode (type + permissions).
    pub mode: u32,
    /// Timestamp for atime/ctime/mtime/otime.
    pub time: Timespec,
}

impl InodeItemArgs {
    /// Serialize to the 160-byte on-disk `btrfs_inode_item` representation.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(160);
        buf.put_u64_le(self.generation);
        buf.put_u64_le(self.generation); // transid = generation
        buf.put_u64_le(self.size);
        buf.put_u64_le(self.nbytes);
        buf.put_u64_le(0); // block_group
        buf.put_u32_le(self.nlink);
        buf.put_u32_le(self.uid);
        buf.put_u32_le(self.gid);
        buf.put_u32_le(self.mode);
        buf.put_u64_le(0); // rdev
        buf.put_u64_le(0); // flags
        buf.put_u64_le(0); // sequence
        buf.extend_from_slice(&[0u8; 32]); // reserved
        for _ in 0..4 {
            self.time.write_to(&mut buf);
        }
        debug_assert_eq!(buf.len(), 160);
        buf
    }
}

/// Hard link reference from an inode to a directory entry.
///
/// Key: `(inode_number, INODE_REF, parent_dir_inode)`. Multiple refs can be
/// packed into a single item when an inode has several hard links in the same
/// parent directory.
#[derive(Debug, Clone)]
pub struct InodeRef {
    /// Index in the parent directory (matches a `DIR_INDEX` key offset).
    pub index: u64,
    /// Filename component (raw bytes, typically UTF-8).
    pub name: Vec<u8>,
}

impl InodeRef {
    /// Parse all packed inode refs from a single item's data buffer.
    #[must_use]
    pub fn parse_all(data: &[u8]) -> Vec<Self> {
        let mut result = Vec::new();
        let mut buf = data;
        while buf.remaining() >= 10 {
            let index = buf.get_u64_le();
            let name_len = buf.get_u16_le() as usize;
            if buf.remaining() < name_len {
                break;
            }
            let name = buf[..name_len].to_vec();
            buf.advance(name_len);
            result.push(Self { index, name });
        }
        result
    }

    /// Serialize a single inode ref entry.
    ///
    /// On-disk layout: index (8) + `name_len` (2) + name.
    #[must_use]
    pub fn serialize(index: u64, name: &[u8]) -> Vec<u8> {
        let mut buf = Vec::with_capacity(10 + name.len());
        buf.put_u64_le(index);
        #[allow(clippy::cast_possible_truncation)]
        buf.put_u16_le(name.len() as u16);
        buf.extend_from_slice(name);
        buf
    }
}

/// Extended inode reference, used when the `EXTREF` feature is enabled.
///
/// Unlike `InodeRef`, the parent directory objectid is stored in the struct
/// rather than the key offset, allowing references from different parent
/// directories to coexist.
#[derive(Debug, Clone)]
pub struct InodeExtref {
    /// Parent directory inode number.
    pub parent: u64,
    /// Index in the parent directory.
    pub index: u64,
    /// Filename component (raw bytes, typically UTF-8).
    pub name: Vec<u8>,
}

impl InodeExtref {
    /// Parse all packed extended inode refs from a single item's data buffer.
    #[must_use]
    pub fn parse_all(data: &[u8]) -> Vec<Self> {
        let mut result = Vec::new();
        let mut buf = data;
        while buf.remaining() >= 18 {
            let parent = buf.get_u64_le();
            let index = buf.get_u64_le();
            let name_len = buf.get_u16_le() as usize;
            if buf.remaining() < name_len {
                break;
            }
            let name = buf[..name_len].to_vec();
            buf.advance(name_len);
            result.push(Self {
                parent,
                index,
                name,
            });
        }
        result
    }
}

/// Directory entry, stored as `DIR_ITEM` (hashed by name) or `DIR_INDEX`
/// (sequential index) in the FS tree.
///
/// Multiple entries can be packed into a single item when names hash to the
/// same value (for `DIR_ITEM`) or when processing xattrs (`XATTR_ITEM`).
#[derive(Debug, Clone)]
pub struct DirItem {
    /// Key of the target inode (objectid = inode number, type = `INODE_ITEM`).
    pub location: DiskKey,
    /// Transaction ID when this entry was created.
    pub transid: u64,
    /// Type of the referenced inode (file, directory, symlink, etc.).
    pub file_type: FileType,
    /// Filename or xattr name (raw bytes).
    pub name: Vec<u8>,
    /// Xattr value (empty for regular directory entries).
    pub data: Vec<u8>,
}

impl DirItem {
    /// Parse all packed directory entries from a single item's data buffer.
    #[must_use]
    pub fn parse_all(data: &[u8]) -> Vec<Self> {
        let mut result = Vec::new();
        let dir_item_size = mem::size_of::<raw::btrfs_dir_item>();
        let mut buf = data;

        while buf.remaining() >= dir_item_size {
            let location = DiskKey::parse(buf, 0);
            buf.advance(17); // skip past DiskKey (u64 + u8 + u64)
            let transid = buf.get_u64_le();
            let data_len = buf.get_u16_le() as usize;
            let name_len = buf.get_u16_le() as usize;
            let file_type = FileType::from_raw(buf.get_u8());

            if buf.remaining() < name_len + data_len {
                break;
            }
            let name = buf[..name_len].to_vec();
            buf.advance(name_len);
            let item_data = buf[..data_len].to_vec();
            buf.advance(data_len);
            result.push(Self {
                location,
                transid,
                file_type,
                name,
                data: item_data,
            });
        }
        result
    }

    /// Serialize a directory entry.
    ///
    /// On-disk layout: location key (17) + transid (8) + `data_len` (2) +
    /// `name_len` (2) + type (1) + name + data = 30 + `name.len()` + `data.len()`.
    #[must_use]
    pub fn serialize(
        location: &DiskKey,
        transid: u64,
        file_type: u8,
        name: &[u8],
    ) -> Vec<u8> {
        let mut buf = Vec::with_capacity(30 + name.len());
        let key_off = buf.len();
        buf.extend_from_slice(&[0u8; 17]);
        write_disk_key(&mut buf[key_off..], 0, location);
        buf.put_u64_le(transid);
        buf.put_u16_le(0); // data_len (no xattr data for regular entries)
        #[allow(clippy::cast_possible_truncation)]
        buf.put_u16_le(name.len() as u16);
        buf.put_u8(file_type);
        buf.extend_from_slice(name);
        buf
    }
}

bitflags::bitflags! {
    /// Root item flags stored in `btrfs_root_item::flags`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct RootItemFlags: u64 {
        const RDONLY = raw::BTRFS_ROOT_SUBVOL_RDONLY as u64;
        const DEAD   = raw::BTRFS_ROOT_SUBVOL_DEAD;
        // Preserve unknown bits from the on-disk value.
        const _ = !0;
    }
}

impl fmt::Display for RootItemFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.contains(Self::RDONLY) {
            write!(f, "RDONLY")
        } else {
            write!(f, "none")
        }
    }
}

/// Root item describing a tree (subvolume, snapshot, or internal tree).
///
/// Stored in the root tree with key `(tree_objectid, ROOT_ITEM, 0)`. Contains
/// the root block pointer, subvolume UUIDs, and transaction timestamps needed
/// for snapshot management and send/receive.
#[derive(Debug, Clone)]
pub struct RootItem {
    /// Raw bytes of the embedded `btrfs_inode_item` (160 bytes).
    ///
    /// The on-disk `ROOT_ITEM` starts with an embedded inode describing the
    /// root directory of the subvolume. This is preserved as raw bytes to
    /// avoid losing data during parse/serialize round-trips, since the
    /// embedded inode fields are not otherwise tracked by this struct.
    pub inode_data: Vec<u8>,
    /// Generation when this root was last modified.
    pub generation: u64,
    /// Objectid of the root directory inode (always 256 for FS trees).
    pub root_dirid: u64,
    /// Logical bytenr of this tree's root block.
    pub bytenr: u64,
    /// Quota byte limit (0 = unlimited).
    pub byte_limit: u64,
    /// Bytes used by this tree.
    pub bytes_used: u64,
    /// Generation of the last snapshot taken from this subvolume.
    pub last_snapshot: u64,
    /// Root flags (RDONLY for read-only snapshots).
    pub flags: RootItemFlags,
    /// Reference count.
    pub refs: u32,
    /// Progress key for in-progress drop operations.
    pub drop_progress: DiskKey,
    /// Tree level of the drop progress.
    pub drop_level: u8,
    /// B-tree level of this tree's root block.
    pub level: u8,
    /// Extended generation (v2 root items, matches `generation` in practice).
    pub generation_v2: u64,
    /// UUID of this subvolume.
    pub uuid: Uuid,
    /// UUID of the parent subvolume (for snapshots).
    pub parent_uuid: Uuid,
    /// UUID of the subvolume this was received from (for send/receive).
    pub received_uuid: Uuid,
    /// Transaction ID of the last change to this subvolume.
    pub ctransid: u64,
    /// Transaction ID when this subvolume was created.
    pub otransid: u64,
    /// Transaction ID when this subvolume was sent.
    pub stransid: u64,
    /// Transaction ID when this subvolume was received.
    pub rtransid: u64,
    /// Time of the last change.
    pub ctime: Timespec,
    /// Creation time.
    pub otime: Timespec,
    /// Time when sent.
    pub stime: Timespec,
    /// Time when received.
    pub rtime: Timespec,
}

impl RootItem {
    /// Parse a root item from a raw byte buffer. Handles both v1 (shorter)
    /// and v2 (full) root item formats gracefully, defaulting missing fields
    /// to zero/nil.
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn parse(data: &[u8]) -> Option<Self> {
        let inode_size = mem::size_of::<raw::btrfs_inode_item>();
        if data.len() < inode_size + 8 {
            return None;
        }

        let inode_data = data[..inode_size].to_vec();
        let mut buf = &data[inode_size..];
        let generation = buf.get_u64_le();
        let root_dirid = buf.get_u64_le();
        let bytenr = buf.get_u64_le();
        let byte_limit = buf.get_u64_le();
        let bytes_used = buf.get_u64_le();
        let last_snapshot = buf.get_u64_le();
        let flags = RootItemFlags::from_bits_truncate(buf.get_u64_le());
        let refs = buf.get_u32_le();

        let dp_off = inode_size + 60;
        let drop_progress = if dp_off + 17 <= data.len() {
            DiskKey::parse(data, dp_off)
        } else {
            DiskKey::parse(&[0; 17], 0)
        };
        let drop_level = if dp_off + 17 < data.len() {
            data[dp_off + 17]
        } else {
            0
        };

        let level_off = mem::offset_of!(raw::btrfs_root_item, level);
        let level = if level_off < data.len() {
            data[level_off]
        } else {
            0
        };
        let generation_v2 = if level_off + 1 + 8 <= data.len() {
            let mut b = &data[level_off + 1..];
            b.get_u64_le()
        } else {
            0
        };

        let uuid_off = mem::offset_of!(raw::btrfs_root_item, uuid);
        let uuid = if uuid_off + 16 <= data.len() {
            let mut b = &data[uuid_off..];
            get_uuid(&mut b)
        } else {
            Uuid::nil()
        };
        let parent_uuid = if uuid_off + 32 <= data.len() {
            let mut b = &data[uuid_off + 16..];
            get_uuid(&mut b)
        } else {
            Uuid::nil()
        };
        let received_uuid = if uuid_off + 48 <= data.len() {
            let mut b = &data[uuid_off + 32..];
            get_uuid(&mut b)
        } else {
            Uuid::nil()
        };

        let ct_off = mem::offset_of!(raw::btrfs_root_item, ctransid);
        let ctransid = if ct_off + 8 <= data.len() {
            let mut b = &data[ct_off..];
            b.get_u64_le()
        } else {
            0
        };
        let otransid = if ct_off + 16 <= data.len() {
            let mut b = &data[ct_off + 8..];
            b.get_u64_le()
        } else {
            0
        };
        let stransid = if ct_off + 24 <= data.len() {
            let mut b = &data[ct_off + 16..];
            b.get_u64_le()
        } else {
            0
        };
        let rtransid = if ct_off + 32 <= data.len() {
            let mut b = &data[ct_off + 24..];
            b.get_u64_le()
        } else {
            0
        };

        let ctime_off = mem::offset_of!(raw::btrfs_root_item, ctime);
        let ts_size = mem::size_of::<raw::btrfs_timespec>();
        let ctime = if ctime_off + ts_size <= data.len() {
            let mut b = &data[ctime_off..];
            Timespec::parse(&mut b)
        } else {
            Timespec { sec: 0, nsec: 0 }
        };
        let otime = if ctime_off + 2 * ts_size <= data.len() {
            let mut b = &data[ctime_off + ts_size..];
            Timespec::parse(&mut b)
        } else {
            Timespec { sec: 0, nsec: 0 }
        };
        let stime = if ctime_off + 3 * ts_size <= data.len() {
            let mut b = &data[ctime_off + 2 * ts_size..];
            Timespec::parse(&mut b)
        } else {
            Timespec { sec: 0, nsec: 0 }
        };
        let rtime = if ctime_off + 4 * ts_size <= data.len() {
            let mut b = &data[ctime_off + 3 * ts_size..];
            Timespec::parse(&mut b)
        } else {
            Timespec { sec: 0, nsec: 0 }
        };

        Some(Self {
            inode_data,
            generation,
            root_dirid,
            bytenr,
            byte_limit,
            bytes_used,
            last_snapshot,
            flags,
            refs,
            drop_progress,
            drop_level,
            level,
            generation_v2,
            uuid,
            parent_uuid,
            received_uuid,
            ctransid,
            otransid,
            stransid,
            rtransid,
            ctime,
            otime,
            stime,
            rtime,
        })
    }

    /// Create a minimal root item for internal trees (not subvolumes).
    ///
    /// Sets generation, bytenr, level, and refs=1. All other fields are
    /// zeroed/nil.
    #[must_use]
    pub fn new_internal(generation: u64, bytenr: u64, level: u8) -> Self {
        Self {
            inode_data: vec![0u8; 160],
            generation,
            root_dirid: 0,
            bytenr,
            byte_limit: 0,
            bytes_used: 0,
            last_snapshot: 0,
            flags: RootItemFlags::empty(),
            refs: 1,
            drop_progress: DiskKey {
                objectid: 0,
                key_type: KeyType::from_raw(0),
                offset: 0,
            },
            drop_level: 0,
            level,
            generation_v2: generation,
            uuid: Uuid::nil(),
            parent_uuid: Uuid::nil(),
            received_uuid: Uuid::nil(),
            ctransid: 0,
            otransid: 0,
            stransid: 0,
            rtransid: 0,
            ctime: Timespec { sec: 0, nsec: 0 },
            otime: Timespec { sec: 0, nsec: 0 },
            stime: Timespec { sec: 0, nsec: 0 },
            rtime: Timespec { sec: 0, nsec: 0 },
        }
    }

    /// Serialize to the on-disk byte representation (496 bytes).
    ///
    /// Starts with a 160-byte zeroed `inode_item`, followed by root item
    /// fields, padded with zeros to 496 bytes total.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(496);

        // btrfs_inode_item (160 bytes) — preserved from the original on-disk
        // data, or zeroed for newly created root items.
        buf.extend_from_slice(&self.inode_data);

        buf.put_u64_le(self.generation);
        buf.put_u64_le(self.root_dirid);
        buf.put_u64_le(self.bytenr);
        buf.put_u64_le(self.byte_limit);
        buf.put_u64_le(self.bytes_used);
        buf.put_u64_le(self.last_snapshot);
        buf.put_u64_le(self.flags.bits());
        buf.put_u32_le(self.refs);

        let key_off = buf.len();
        buf.extend_from_slice(&[0u8; 17]);
        write_disk_key(&mut buf[key_off..], 0, &self.drop_progress);

        buf.put_u8(self.drop_level);
        buf.put_u8(self.level);
        buf.put_u64_le(self.generation_v2);

        buf.extend_from_slice(self.uuid.as_bytes());
        buf.extend_from_slice(self.parent_uuid.as_bytes());
        buf.extend_from_slice(self.received_uuid.as_bytes());

        buf.put_u64_le(self.ctransid);
        buf.put_u64_le(self.otransid);
        buf.put_u64_le(self.stransid);
        buf.put_u64_le(self.rtransid);

        self.ctime.write_to(&mut buf);
        self.otime.write_to(&mut buf);
        self.stime.write_to(&mut buf);
        self.rtime.write_to(&mut buf);

        // Pad to 439 bytes (sizeof(btrfs_root_item): 160 inode + 279 root
        // fields including reserved[8]).
        buf.resize(mem::size_of::<raw::btrfs_root_item>(), 0);
        buf
    }
}

/// Reference linking a subvolume to its parent directory.
///
/// `ROOT_REF` keys (parent → child) and `ROOT_BACKREF` keys (child → parent)
/// use the same on-disk format.
#[derive(Debug, Clone)]
pub struct RootRef {
    /// Inode number of the directory containing the subvolume entry.
    pub dirid: u64,
    /// Directory sequence number (matches the `DIR_INDEX` offset).
    pub sequence: u64,
    /// Name of the subvolume entry in the parent directory.
    pub name: Vec<u8>,
}

impl RootRef {
    /// Parse a root ref (or root backref) from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_root_ref>() {
            return None;
        }
        let mut buf = data;
        let dirid = buf.get_u64_le();
        let sequence = buf.get_u64_le();
        let name_len = buf.get_u16_le() as usize;
        let name_start = mem::size_of::<raw::btrfs_root_ref>();
        let name = if name_start + name_len <= data.len() {
            data[name_start..name_start + name_len].to_vec()
        } else {
            Vec::new()
        };
        Some(Self {
            dirid,
            sequence,
            name,
        })
    }

    /// Serialize a `(dirid, sequence, name)` tuple to the on-disk
    /// `btrfs_root_ref` byte representation: 18-byte fixed header
    /// (`dirid` u64 + `sequence` u64 + `name_len` u16, all
    /// little-endian) followed by the raw name bytes.
    ///
    /// # Panics
    ///
    /// Panics if `name.len()` does not fit in a `u16` (the on-disk
    /// `name_len` field is 16 bits). Practical names are always far
    /// below 65535 bytes.
    #[must_use]
    pub fn serialize(dirid: u64, sequence: u64, name: &[u8]) -> Vec<u8> {
        let header = mem::size_of::<raw::btrfs_root_ref>();
        let mut buf = Vec::with_capacity(header + name.len());
        buf.put_u64_le(dirid);
        buf.put_u64_le(sequence);
        buf.put_u16_le(
            u16::try_from(name.len())
                .expect("RootRef::serialize: name length does not fit in u16"),
        );
        buf.put_slice(name);
        buf
    }
}

/// File extent descriptor, stored as `EXTENT_DATA` in the FS tree.
///
/// Key: `(inode, EXTENT_DATA, file_offset)`. Describes how a range of file
/// bytes maps to on-disk storage. Extents can be inline (data embedded in the
/// item), regular (referencing a disk extent), or prealloc (reserved but
/// unwritten).
#[derive(Debug, Clone)]
pub struct FileExtentItem {
    /// Generation when this extent was allocated.
    pub generation: u64,
    /// Uncompressed size of the data in this extent.
    pub ram_bytes: u64,
    /// Compression algorithm applied to the on-disk data.
    pub compression: CompressionType,
    /// Whether the extent is inline, regular, or preallocated.
    pub extent_type: FileExtentType,
    /// Type-specific extent location.
    pub body: FileExtentBody,
}

/// Body of a file extent: either inline data or a reference to a disk extent.
#[derive(Debug, Clone)]
pub enum FileExtentBody {
    /// Data is stored directly in the tree leaf (small files/tails).
    Inline {
        /// Number of bytes of inline data following the extent header.
        inline_size: usize,
    },
    /// Data is stored in a separate disk extent.
    Regular {
        /// Logical byte address of the extent on disk (0 = hole/sparse).
        disk_bytenr: u64,
        /// Size of the on-disk extent in bytes (compressed size if compressed).
        disk_num_bytes: u64,
        /// Byte offset into the extent where this file range starts.
        offset: u64,
        /// Number of logical file bytes this extent covers.
        num_bytes: u64,
    },
}

impl FileExtentItem {
    /// Parse a file extent item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 21 {
            return None;
        }
        let mut buf = data;
        let generation = buf.get_u64_le();
        let ram_bytes = buf.get_u64_le();
        let compression = CompressionType::from_raw(buf.get_u8());
        buf.advance(3); // skip encryption, other_encoding
        let extent_type = FileExtentType::from_raw(buf.get_u8());

        let body = if extent_type == FileExtentType::Inline {
            FileExtentBody::Inline {
                inline_size: buf.remaining(),
            }
        } else if buf.remaining() >= 32 {
            FileExtentBody::Regular {
                disk_bytenr: buf.get_u64_le(),
                disk_num_bytes: buf.get_u64_le(),
                offset: buf.get_u64_le(),
                num_bytes: buf.get_u64_le(),
            }
        } else {
            return None;
        };

        Some(Self {
            generation,
            ram_bytes,
            compression,
            extent_type,
            body,
        })
    }

    /// Size of the fixed `btrfs_file_extent_item` header (the bytes before
    /// `disk_bytenr` / inline data).
    pub const HEADER_SIZE: usize = 21;

    /// Size of a regular or prealloc `EXTENT_DATA` item: 21-byte header plus
    /// 32-byte body (`disk_bytenr`, `disk_num_bytes`, `offset`, `num_bytes`).
    pub const REGULAR_SIZE: usize = 53;

    /// Serialize a regular or prealloc `EXTENT_DATA` item (53 bytes).
    ///
    /// `prealloc` selects `BTRFS_FILE_EXTENT_PREALLOC` instead of the default
    /// `BTRFS_FILE_EXTENT_REG`. `disk_bytenr` of 0 represents a hole.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn to_bytes_regular(
        generation: u64,
        ram_bytes: u64,
        compression: CompressionType,
        prealloc: bool,
        disk_bytenr: u64,
        disk_num_bytes: u64,
        offset: u64,
        num_bytes: u64,
    ) -> Vec<u8> {
        let extent_type = if prealloc {
            FileExtentType::Prealloc
        } else {
            FileExtentType::Regular
        };
        let mut buf = Vec::with_capacity(Self::REGULAR_SIZE);
        buf.put_u64_le(generation);
        buf.put_u64_le(ram_bytes);
        buf.put_u8(compression.to_raw());
        buf.put_u8(0); // encryption
        buf.put_u16_le(0); // other_encoding
        buf.put_u8(extent_type.to_raw());
        buf.put_u64_le(disk_bytenr);
        buf.put_u64_le(disk_num_bytes);
        buf.put_u64_le(offset);
        buf.put_u64_le(num_bytes);
        debug_assert_eq!(buf.len(), Self::REGULAR_SIZE);
        buf
    }

    /// Serialize an inline `EXTENT_DATA` item: 21-byte header followed by
    /// `data` bytes (raw or already-compressed/framed payload).
    ///
    /// `ram_bytes` is the uncompressed file size covered by this inline
    /// extent. `compression` indicates whether `data` is compressed.
    #[must_use]
    pub fn to_bytes_inline(
        generation: u64,
        ram_bytes: u64,
        compression: CompressionType,
        data: &[u8],
    ) -> Vec<u8> {
        let mut buf = Vec::with_capacity(Self::HEADER_SIZE + data.len());
        buf.put_u64_le(generation);
        buf.put_u64_le(ram_bytes);
        buf.put_u8(compression.to_raw());
        buf.put_u8(0); // encryption
        buf.put_u16_le(0); // other_encoding
        buf.put_u8(FileExtentType::Inline.to_raw());
        debug_assert_eq!(buf.len(), Self::HEADER_SIZE);
        buf.extend_from_slice(data);
        buf
    }
}

/// Compute the hash used for `EXTENT_DATA_REF` keys, matching the kernel's
/// `hash_extent_data_ref()`. Uses two independent CRC32C computations
/// combined into a single u64.
#[must_use]
pub fn extent_data_ref_hash(root: u64, objectid: u64, offset: u64) -> u64 {
    let high_crc = raw_crc32c(!0u32, &root.to_le_bytes());
    let low_crc = raw_crc32c(!0u32, &objectid.to_le_bytes());
    let low_crc = raw_crc32c(low_crc, &offset.to_le_bytes());
    (u64::from(high_crc) << 31) ^ u64::from(low_crc)
}

/// Inline reference types found inside `EXTENT_ITEM`/`METADATA_ITEM`.
#[derive(Debug, Clone)]
pub enum InlineRef {
    /// Direct backref from a metadata extent to the tree that owns it.
    /// The `root` field is the tree objectid (e.g. 5 for `FS_TREE`).
    TreeBlockBackref {
        /// Raw offset value from the inline ref header (equals `root`).
        ref_offset: u64,
        /// Tree objectid that owns this metadata block.
        root: u64,
    },
    /// Shared backref from a metadata extent via a parent tree block.
    /// Used when a tree block is shared between snapshots.
    SharedBlockBackref {
        /// Raw offset value from the inline ref header (equals `parent`).
        ref_offset: u64,
        /// Logical bytenr of the parent tree block that references this extent.
        parent: u64,
    },
    /// Backref from a data extent to a specific file inode. Stores the
    /// owning root, inode number, file offset, and reference count.
    ExtentDataBackref {
        /// Computed hash of (root, objectid, offset) for display.
        ref_offset: u64,
        /// Tree objectid that owns the referencing inode.
        root: u64,
        /// Inode number that references this data extent.
        objectid: u64,
        /// File byte offset where this extent is referenced.
        offset: u64,
        /// Number of references from this (root, objectid, offset) triple.
        count: u32,
    },
    /// Shared backref from a data extent via a parent tree block.
    /// Used when data extents are shared between snapshots.
    SharedDataBackref {
        /// Raw offset value from the inline ref header (equals `parent`).
        ref_offset: u64,
        /// Logical bytenr of the parent tree block that references this extent.
        parent: u64,
        /// Number of references from the parent block.
        count: u32,
    },
    /// Simple ownership reference for an extent (`simple_quota` feature).
    /// Records which tree root owns the extent.
    ExtentOwnerRef {
        /// Raw offset value from the inline ref header (equals `root`).
        ref_offset: u64,
        /// Tree objectid that owns this extent.
        root: u64,
    },
}

impl InlineRef {
    /// The raw type byte for this inline ref.
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    pub fn raw_type(&self) -> u8 {
        match self {
            Self::TreeBlockBackref { .. } => {
                raw::BTRFS_TREE_BLOCK_REF_KEY as u8
            }
            Self::SharedBlockBackref { .. } => {
                raw::BTRFS_SHARED_BLOCK_REF_KEY as u8
            }
            Self::ExtentDataBackref { .. } => {
                raw::BTRFS_EXTENT_DATA_REF_KEY as u8
            }
            Self::SharedDataBackref { .. } => {
                raw::BTRFS_SHARED_DATA_REF_KEY as u8
            }
            Self::ExtentOwnerRef { .. } => {
                raw::BTRFS_EXTENT_OWNER_REF_KEY as u8
            }
        }
    }

    /// The offset value from the inline ref header.
    #[must_use]
    pub fn raw_offset(&self) -> u64 {
        match self {
            Self::TreeBlockBackref { ref_offset, .. }
            | Self::SharedBlockBackref { ref_offset, .. }
            | Self::ExtentDataBackref { ref_offset, .. }
            | Self::SharedDataBackref { ref_offset, .. }
            | Self::ExtentOwnerRef { ref_offset, .. } => *ref_offset,
        }
    }
}

/// On-disk size in bytes of an inline backref record (including its
/// 1-byte type tag) for a given inline ref type byte.
///
/// Returns `None` if `type_byte` is not a recognized inline ref type.
///
/// - `TREE_BLOCK_REF`/`EXTENT_OWNER_REF`: 1 (tag) + 8 (root) = 9
/// - `SHARED_BLOCK_REF`: 1 (tag) + 8 (parent) = 9
/// - `EXTENT_DATA_REF`: 1 (tag) + 28 (`btrfs_extent_data_ref`) = 29
/// - `SHARED_DATA_REF`: 1 (tag) + 8 (parent) + 4 (count) = 13
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn inline_ref_size(type_byte: u8) -> Option<usize> {
    match u32::from(type_byte) {
        raw::BTRFS_TREE_BLOCK_REF_KEY | raw::BTRFS_EXTENT_OWNER_REF_KEY => {
            Some(9)
        }
        raw::BTRFS_SHARED_BLOCK_REF_KEY => Some(9),
        raw::BTRFS_EXTENT_DATA_REF_KEY => Some(29),
        raw::BTRFS_SHARED_DATA_REF_KEY => Some(13),
        _ => None,
    }
}

bitflags::bitflags! {
    /// Extent item flags stored in `btrfs_extent_item::flags`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct ExtentFlags: u64 {
        const DATA         = raw::BTRFS_EXTENT_FLAG_DATA as u64;
        const TREE_BLOCK   = raw::BTRFS_EXTENT_FLAG_TREE_BLOCK as u64;
        const FULL_BACKREF = raw::BTRFS_BLOCK_FLAG_FULL_BACKREF as u64;
        // Preserve unknown bits from the on-disk value.
        const _ = !0;
    }
}

impl fmt::Display for ExtentFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = Vec::new();
        if self.contains(Self::DATA) {
            parts.push("DATA");
        }
        if self.contains(Self::TREE_BLOCK) {
            parts.push("TREE_BLOCK");
        }
        if self.contains(Self::FULL_BACKREF) {
            parts.push("FULL_BACKREF");
        }
        write!(f, "{}", parts.join("|"))
    }
}

/// Extent allocation record from the extent tree.
///
/// Tracks reference counts, ownership, and backreferences for a contiguous
/// range of allocated disk space. Used for both data extents (`EXTENT_ITEM`)
/// and metadata blocks (`METADATA_ITEM` with skinny metadata).
#[derive(Debug, Clone)]
pub struct ExtentItem {
    /// Number of references to this extent.
    pub refs: u64,
    /// Generation when this extent was allocated.
    pub generation: u64,
    /// Whether this extent holds data or a tree block.
    pub flags: ExtentFlags,
    /// For non-skinny tree block extents: the first key in the block.
    pub tree_block_key: Option<DiskKey>,
    /// For non-skinny tree block extents: the block's tree level.
    pub tree_block_level: Option<u8>,
    /// For skinny metadata items: the tree level (from the key offset).
    pub skinny_level: Option<u64>,
    /// Inline backreferences packed after the extent header.
    pub inline_refs: Vec<InlineRef>,
}

impl ExtentItem {
    /// Returns true if this extent holds file data.
    #[must_use]
    pub fn is_data(&self) -> bool {
        self.flags.contains(ExtentFlags::DATA)
    }

    /// Returns true if this extent holds a metadata tree block.
    #[must_use]
    pub fn is_tree_block(&self) -> bool {
        self.flags.contains(ExtentFlags::TREE_BLOCK)
    }

    /// Parse an extent item from a raw byte buffer, using the item key to
    /// determine whether this is a skinny metadata item or a full extent item.
    #[must_use]
    pub fn parse(data: &[u8], key: &DiskKey) -> Option<Self> {
        use crate::tree::KeyType;

        if data.len() < mem::size_of::<raw::btrfs_extent_item>() {
            return None;
        }
        let mut buf = data;
        let refs = buf.get_u64_le();
        let generation = buf.get_u64_le();
        let flags = ExtentFlags::from_bits_truncate(buf.get_u64_le());

        let is_tree_block = flags.contains(ExtentFlags::TREE_BLOCK);

        let mut tree_block_key = None;
        let mut tree_block_level = None;
        if is_tree_block
            && key.key_type == KeyType::ExtentItem
            && buf.remaining() > 17
        {
            tree_block_key = Some(DiskKey::parse(buf, 0));
            buf.advance(17); // skip DiskKey
            tree_block_level = Some(buf.get_u8());
        }

        let skinny_level =
            if key.key_type == KeyType::MetadataItem && is_tree_block {
                Some(key.offset)
            } else {
                None
            };

        let mut inline_refs = Vec::new();
        while buf.remaining() > 0 {
            let ref_type = buf.get_u8();
            let ref_offset = if buf.remaining() >= 8 {
                buf.get_u64_le()
            } else {
                0
            };

            match u32::from(ref_type) {
                raw::BTRFS_TREE_BLOCK_REF_KEY => {
                    inline_refs.push(InlineRef::TreeBlockBackref {
                        ref_offset,
                        root: ref_offset,
                    });
                }
                raw::BTRFS_SHARED_BLOCK_REF_KEY => {
                    inline_refs.push(InlineRef::SharedBlockBackref {
                        ref_offset,
                        parent: ref_offset,
                    });
                }
                raw::BTRFS_EXTENT_DATA_REF_KEY => {
                    // EXTENT_DATA_REF has no 8-byte offset field; the struct
                    // starts directly after the type byte. The 8 bytes we
                    // speculatively consumed are actually the first field
                    // (root) of the struct, so reinterpret them.
                    let root = ref_offset; // already read as u64_le
                    if buf.remaining() >= 20 {
                        let oid = buf.get_u64_le();
                        let off = buf.get_u64_le();
                        let count = buf.get_u32_le();
                        // The C tool prints a CRC hash for the display offset;
                        // compute it the same way: hash(root, objectid, offset).
                        let hash = extent_data_ref_hash(root, oid, off);
                        inline_refs.push(InlineRef::ExtentDataBackref {
                            ref_offset: hash,
                            root,
                            objectid: oid,
                            offset: off,
                            count,
                        });
                    } else {
                        break;
                    }
                }
                raw::BTRFS_SHARED_DATA_REF_KEY => {
                    if buf.remaining() >= 4 {
                        let count = buf.get_u32_le();
                        inline_refs.push(InlineRef::SharedDataBackref {
                            ref_offset,
                            parent: ref_offset,
                            count,
                        });
                    } else {
                        break;
                    }
                }
                raw::BTRFS_EXTENT_OWNER_REF_KEY => {
                    inline_refs.push(InlineRef::ExtentOwnerRef {
                        ref_offset,
                        root: ref_offset,
                    });
                }
                _ => break,
            }
        }

        Some(Self {
            refs,
            generation,
            flags,
            tree_block_key,
            tree_block_level,
            skinny_level,
            inline_refs,
        })
    }

    /// Size of a skinny metadata extent item with one `TREE_BLOCK_REF`.
    ///
    /// Layout: extent header (24) + inline ref type (1) + offset (8) = 33.
    pub const SKINNY_SIZE: usize = 33;

    /// Size of a non-skinny metadata extent item with `tree_block_info`
    /// and one `TREE_BLOCK_REF`.
    ///
    /// Layout: extent header (24) + `tree_block_info` (18) + inline ref (9) = 51.
    pub const NON_SKINNY_SIZE: usize = 51;

    /// Serialize a skinny metadata extent item (`METADATA_ITEM`) with a
    /// single `TREE_BLOCK_REF` inline backref (33 bytes).
    #[must_use]
    pub fn to_bytes_skinny(
        refs: u64,
        generation: u64,
        root_id: u64,
    ) -> Vec<u8> {
        let mut buf = Vec::with_capacity(Self::SKINNY_SIZE);
        buf.put_u64_le(refs);
        buf.put_u64_le(generation);
        buf.put_u64_le(ExtentFlags::TREE_BLOCK.bits());
        buf.put_u8(KeyType::TreeBlockRef.to_raw());
        buf.put_u64_le(root_id);
        debug_assert_eq!(buf.len(), Self::SKINNY_SIZE);
        buf
    }

    /// Serialize a non-skinny metadata extent item (`EXTENT_ITEM`) with
    /// `tree_block_info` and a `TREE_BLOCK_REF` inline backref (51 bytes).
    #[must_use]
    pub fn to_bytes_non_skinny(
        refs: u64,
        generation: u64,
        root_id: u64,
        first_key: &DiskKey,
        level: u8,
    ) -> Vec<u8> {
        let mut buf = Vec::with_capacity(Self::NON_SKINNY_SIZE);
        buf.put_u64_le(refs);
        buf.put_u64_le(generation);
        buf.put_u64_le(ExtentFlags::TREE_BLOCK.bits());
        // tree_block_info: first key + level
        let key_off = buf.len();
        buf.extend_from_slice(&[0u8; 17]);
        write_disk_key(&mut buf[key_off..], 0, first_key);
        buf.put_u8(level);
        buf.put_u8(KeyType::TreeBlockRef.to_raw());
        buf.put_u64_le(root_id);
        debug_assert_eq!(buf.len(), Self::NON_SKINNY_SIZE);
        buf
    }

    /// Size of a data extent item with one inline `EXTENT_DATA_REF`.
    ///
    /// Layout: extent header (24) + inline ref type (1) + data ref (28) = 53.
    pub const DATA_INLINE_SIZE: usize = 53;

    /// Serialize a data extent item (`EXTENT_ITEM`) with a single inline
    /// `EXTENT_DATA_REF` backref (53 bytes).
    #[must_use]
    pub fn to_bytes_data(
        refs: u64,
        generation: u64,
        root: u64,
        objectid: u64,
        offset: u64,
        count: u32,
    ) -> Vec<u8> {
        let mut buf = Vec::with_capacity(Self::DATA_INLINE_SIZE);
        buf.put_u64_le(refs); // extent header: refs
        buf.put_u64_le(generation); // extent header: generation
        buf.put_u64_le(ExtentFlags::DATA.bits()); // flags
        buf.put_u8(KeyType::ExtentDataRef.to_raw()); // inline type tag
        buf.put_u64_le(root); // btrfs_extent_data_ref.root
        buf.put_u64_le(objectid); // btrfs_extent_data_ref.objectid
        buf.put_u64_le(offset); // btrfs_extent_data_ref.offset
        buf.put_u32_le(count); // btrfs_extent_data_ref.count
        debug_assert_eq!(buf.len(), Self::DATA_INLINE_SIZE);
        buf
    }
}

/// Standalone data extent backreference (non-inline).
///
/// Key: `(extent_bytenr, EXTENT_DATA_REF, hash)`. Records which file inode
/// references a given data extent.
#[derive(Debug, Clone)]
pub struct ExtentDataRef {
    /// Root tree objectid that owns the referencing inode.
    pub root: u64,
    /// Inode number that references this extent.
    pub objectid: u64,
    /// File offset where this extent is referenced.
    pub offset: u64,
    /// Number of references from this (root, objectid, offset) triple.
    pub count: u32,
}

impl ExtentDataRef {
    /// Parse a standalone extent data ref from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_extent_data_ref>() {
            return None;
        }
        let mut buf = data;
        Some(Self {
            root: buf.get_u64_le(),
            objectid: buf.get_u64_le(),
            offset: buf.get_u64_le(),
            count: buf.get_u32_le(),
        })
    }
}

/// Shared data extent backreference (for snapshot-shared extents).
///
/// Key: `(extent_bytenr, SHARED_DATA_REF, parent_bytenr)`.
#[derive(Debug, Clone)]
pub struct SharedDataRef {
    /// Number of references from the parent block.
    pub count: u32,
}

impl SharedDataRef {
    /// Parse a shared data ref from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 4 {
            return None;
        }
        let mut buf = data;
        Some(Self {
            count: buf.get_u32_le(),
        })
    }
}

/// Block group descriptor, tracking space usage for a chunk.
///
/// Key: `(logical_offset, BLOCK_GROUP_ITEM, length)`.
#[derive(Debug, Clone)]
pub struct BlockGroupItem {
    /// Bytes used within this block group.
    pub used: u64,
    /// Objectid of the chunk that backs this block group.
    pub chunk_objectid: u64,
    /// Type and RAID profile flags (DATA, METADATA, SYSTEM, DUP, RAID*, etc.).
    pub flags: BlockGroupFlags,
}

impl BlockGroupItem {
    /// Parse a block group item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_block_group_item>() {
            return None;
        }
        let mut buf = data;
        Some(Self {
            used: buf.get_u64_le(),
            chunk_objectid: buf.get_u64_le(),
            flags: BlockGroupFlags::from_bits_truncate(buf.get_u64_le()),
        })
    }

    /// Serialize to the 24-byte on-disk representation.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(24);
        buf.put_u64_le(self.used);
        buf.put_u64_le(self.chunk_objectid);
        buf.put_u64_le(self.flags.bits());
        buf
    }
}

/// Chunk item mapping logical addresses to physical device locations.
///
/// Key: `(FIRST_CHUNK_TREE, CHUNK_ITEM, logical_offset)`. Each chunk maps a
/// contiguous range of logical addresses to one or more device stripes.
#[derive(Debug, Clone)]
pub struct ChunkItem {
    /// Length of this chunk in bytes.
    pub length: u64,
    /// Owner of this chunk (always `BTRFS_FIRST_CHUNK_TREE_OBJECTID`).
    pub owner: u64,
    /// Stripe length for striped profiles.
    pub stripe_len: u64,
    /// Type and RAID profile flags.
    pub chunk_type: BlockGroupFlags,
    /// I/O alignment requirement.
    pub io_align: u32,
    /// I/O width requirement.
    pub io_width: u32,
    /// Sector size of the underlying devices.
    pub sector_size: u32,
    /// Number of stripes (device copies) for this chunk.
    pub num_stripes: u16,
    /// Number of sub-stripes (for RAID10).
    pub sub_stripes: u16,
    /// Physical device locations for each stripe.
    pub stripes: Vec<ChunkStripe>,
}

/// A single physical stripe within a chunk.
#[derive(Debug, Clone)]
pub struct ChunkStripe {
    /// Device ID where this stripe lives.
    pub devid: u64,
    /// Physical byte offset on the device.
    pub offset: u64,
    /// UUID of the device.
    pub dev_uuid: Uuid,
}

impl ChunkItem {
    /// Parse a chunk item (with stripes) from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        let chunk_base_size = mem::offset_of!(raw::btrfs_chunk, stripe);
        if data.len() < chunk_base_size {
            return None;
        }
        let mut buf = data;
        let length = buf.get_u64_le();
        let owner = buf.get_u64_le();
        let stripe_len = buf.get_u64_le();
        let chunk_type = BlockGroupFlags::from_bits_truncate(buf.get_u64_le());
        let io_align = buf.get_u32_le();
        let io_width = buf.get_u32_le();
        let sector_size = buf.get_u32_le();
        let num_stripes = buf.get_u16_le();
        let sub_stripes = buf.get_u16_le();
        let stripe_size = mem::size_of::<raw::btrfs_stripe>();
        let mut stripes = Vec::with_capacity(num_stripes as usize);
        let mut sbuf = &data[chunk_base_size..];
        for i in 0..num_stripes as usize {
            let s_off = chunk_base_size + i * stripe_size;
            if s_off + stripe_size > data.len() {
                break;
            }
            let devid = sbuf.get_u64_le();
            let offset = sbuf.get_u64_le();
            let dev_uuid = get_uuid(&mut sbuf);
            stripes.push(ChunkStripe {
                devid,
                offset,
                dev_uuid,
            });
        }
        Some(Self {
            length,
            owner,
            stripe_len,
            chunk_type,
            io_align,
            io_width,
            sector_size,
            num_stripes,
            sub_stripes,
            stripes,
        })
    }
}

impl ChunkItem {
    /// Convert to a `ChunkMapping` for use with `chunk_item_bytes` and
    /// `ChunkTreeCache`.
    #[must_use]
    pub fn to_mapping(&self, logical: u64) -> crate::chunk::ChunkMapping {
        crate::chunk::ChunkMapping {
            logical,
            length: self.length,
            stripe_len: self.stripe_len,
            chunk_type: self.chunk_type.bits(),
            num_stripes: self.num_stripes,
            sub_stripes: self.sub_stripes,
            stripes: self
                .stripes
                .iter()
                .map(|s| crate::chunk::Stripe {
                    devid: s.devid,
                    offset: s.offset,
                    dev_uuid: s.dev_uuid,
                })
                .collect(),
        }
    }
}

/// Device item describing a single device in the filesystem.
///
/// Stored in the device tree and embedded in the superblock. Contains the
/// device's size, usage, and identifying UUIDs.
#[derive(Debug, Clone)]
pub struct DeviceItem {
    /// Unique device ID within this filesystem.
    pub devid: u64,
    /// Total size of the device in bytes.
    pub total_bytes: u64,
    /// Bytes allocated on this device.
    pub bytes_used: u64,
    /// I/O alignment requirement.
    pub io_align: u32,
    /// I/O width requirement.
    pub io_width: u32,
    /// Sector size of this device.
    pub sector_size: u32,
    /// Device type (reserved, always 0).
    pub dev_type: u64,
    /// Generation when this device was last updated.
    pub generation: u64,
    /// Start offset for allocations on this device.
    pub start_offset: u64,
    /// Device group (reserved, always 0).
    pub dev_group: u32,
    /// Seek speed hint (0 = not set).
    pub seek_speed: u8,
    /// Bandwidth hint (0 = not set).
    pub bandwidth: u8,
    /// UUID of this device.
    pub uuid: Uuid,
    /// Filesystem UUID that this device belongs to.
    pub fsid: Uuid,
}

impl DeviceItem {
    /// Serialize this device item to a `BufMut` in on-disk little-endian format.
    pub fn write_bytes(&self, buf: &mut impl BufMut) {
        buf.put_u64_le(self.devid);
        buf.put_u64_le(self.total_bytes);
        buf.put_u64_le(self.bytes_used);
        buf.put_u32_le(self.io_align);
        buf.put_u32_le(self.io_width);
        buf.put_u32_le(self.sector_size);
        buf.put_u64_le(self.dev_type);
        buf.put_u64_le(self.generation);
        buf.put_u64_le(self.start_offset);
        buf.put_u32_le(self.dev_group);
        buf.put_u8(self.seek_speed);
        buf.put_u8(self.bandwidth);
        buf.put_slice(self.uuid.as_bytes());
        buf.put_slice(self.fsid.as_bytes());
    }

    /// Parse a device item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_dev_item>() {
            return None;
        }
        let mut buf = data;
        let devid = buf.get_u64_le();
        let total_bytes = buf.get_u64_le();
        let bytes_used = buf.get_u64_le();
        let io_align = buf.get_u32_le();
        let io_width = buf.get_u32_le();
        let sector_size = buf.get_u32_le();
        let dev_type = buf.get_u64_le();
        let generation = buf.get_u64_le();
        let start_offset = buf.get_u64_le();
        let dev_group = buf.get_u32_le();
        let seek_speed = buf.get_u8();
        let bandwidth = buf.get_u8();
        let uuid = get_uuid(&mut buf);
        let fsid = get_uuid(&mut buf);
        Some(Self {
            devid,
            total_bytes,
            bytes_used,
            io_align,
            io_width,
            sector_size,
            dev_type,
            generation,
            start_offset,
            dev_group,
            seek_speed,
            bandwidth,
            uuid,
            fsid,
        })
    }
}

/// Device extent, mapping a physical range on a device to a chunk.
///
/// Key: `(devid, DEV_EXTENT, physical_offset)`. The inverse of a chunk
/// stripe: given a device and physical offset, find the owning chunk.
#[derive(Debug, Clone)]
pub struct DeviceExtent {
    /// Objectid of the chunk tree (always 3).
    pub chunk_tree: u64,
    /// Objectid of the owning chunk.
    pub chunk_objectid: u64,
    /// Logical offset of the owning chunk.
    pub chunk_offset: u64,
    /// Length of this device extent in bytes.
    pub length: u64,
    /// UUID of the chunk tree.
    pub chunk_tree_uuid: Uuid,
}

impl DeviceExtent {
    /// Parse a device extent from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_dev_extent>() {
            return None;
        }
        let mut buf = data;
        let chunk_tree = buf.get_u64_le();
        let chunk_objectid = buf.get_u64_le();
        let chunk_offset = buf.get_u64_le();
        let length = buf.get_u64_le();
        let chunk_tree_uuid = get_uuid(&mut buf);
        Some(Self {
            chunk_tree,
            chunk_objectid,
            chunk_offset,
            length,
            chunk_tree_uuid,
        })
    }
}

bitflags::bitflags! {
    /// Free space info flags stored in `btrfs_free_space_info::flags`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct FreeSpaceInfoFlags: u32 {
        const USING_BITMAPS = raw::BTRFS_FREE_SPACE_USING_BITMAPS;
        // Preserve unknown bits from the on-disk value.
        const _ = !0;
    }
}

impl fmt::Display for FreeSpaceInfoFlags {
    // The C reference prints this field as an unsigned decimal integer (%u).
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.bits())
    }
}

/// Free space info for a block group in the free space tree.
///
/// Key: `(block_group_offset, FREE_SPACE_INFO, block_group_length)`.
#[derive(Debug, Clone)]
pub struct FreeSpaceInfo {
    /// Number of free extents (or bitmap entries) in this block group.
    pub extent_count: u32,
    /// Flags indicating whether this block group uses bitmaps.
    pub flags: FreeSpaceInfoFlags,
}

impl FreeSpaceInfo {
    /// Parse a free space info item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 8 {
            return None;
        }
        let mut buf = data;
        Some(Self {
            extent_count: buf.get_u32_le(),
            flags: FreeSpaceInfoFlags::from_bits_truncate(buf.get_u32_le()),
        })
    }
}

/// Quota group status, stored in the quota tree.
///
/// Key: `(0, QGROUP_STATUS, 0)`. Tracks the overall state of quota accounting.
#[derive(Debug, Clone)]
pub struct QgroupStatus {
    /// Qgroup on-disk format version.
    pub version: u64,
    /// Generation when quotas were last consistent.
    pub generation: u64,
    /// Status flags (e.g. rescan in progress).
    pub flags: u64,
    /// Progress objectid for an in-progress rescan.
    pub scan: u64,
    /// Generation when quotas were enabled (kernel 6.8+, absent on older formats).
    pub enable_gen: Option<u64>,
}

impl QgroupStatus {
    /// Parse a qgroup status item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 32 {
            return None;
        }
        let mut buf = data;
        let version = buf.get_u64_le();
        let generation = buf.get_u64_le();
        let flags = buf.get_u64_le();
        let scan = buf.get_u64_le();
        let enable_gen = if buf.remaining() >= 8 {
            Some(buf.get_u64_le())
        } else {
            None
        };
        Some(Self {
            version,
            generation,
            flags,
            scan,
            enable_gen,
        })
    }
}

/// Quota group accounting info.
///
/// Key: `(level/subvolid, QGROUP_INFO, 0)`. Tracks how much space a qgroup
/// references and how much is exclusive to it.
#[derive(Debug, Clone)]
pub struct QgroupInfo {
    /// Generation when this info was last updated.
    pub generation: u64,
    /// Total bytes referenced by this qgroup (shared + exclusive).
    pub referenced: u64,
    /// Referenced bytes after compression.
    pub referenced_compressed: u64,
    /// Bytes used exclusively by this qgroup.
    pub exclusive: u64,
    /// Exclusive bytes after compression.
    pub exclusive_compressed: u64,
}

impl QgroupInfo {
    /// Parse a qgroup info item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_qgroup_info_item>() {
            return None;
        }
        let mut buf = data;
        Some(Self {
            generation: buf.get_u64_le(),
            referenced: buf.get_u64_le(),
            referenced_compressed: buf.get_u64_le(),
            exclusive: buf.get_u64_le(),
            exclusive_compressed: buf.get_u64_le(),
        })
    }
}

/// Quota group limits.
///
/// Key: `(level/subvolid, QGROUP_LIMIT, 0)`. Caps referenced and/or exclusive
/// space usage for a qgroup.
#[derive(Debug, Clone)]
pub struct QgroupLimit {
    /// Bitmask of which limits are active.
    pub flags: u64,
    /// Maximum referenced bytes (0 = unlimited).
    pub max_referenced: u64,
    /// Maximum exclusive bytes (0 = unlimited).
    pub max_exclusive: u64,
    /// Reserved referenced bytes.
    pub rsv_referenced: u64,
    /// Reserved exclusive bytes.
    pub rsv_exclusive: u64,
}

impl QgroupLimit {
    /// Parse a qgroup limit item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < mem::size_of::<raw::btrfs_qgroup_limit_item>() {
            return None;
        }
        let mut buf = data;
        Some(Self {
            flags: buf.get_u64_le(),
            max_referenced: buf.get_u64_le(),
            max_exclusive: buf.get_u64_le(),
            rsv_referenced: buf.get_u64_le(),
            rsv_exclusive: buf.get_u64_le(),
        })
    }
}

/// Per-device I/O error statistics.
///
/// Key: `(DEV_STATS, PERSISTENT_ITEM, devid)`. Stored as an array of u64
/// counters for write errors, read errors, flush errors, corruption errors,
/// and generation mismatches.
#[derive(Debug, Clone)]
pub struct DeviceStats {
    /// Named counters: `(stat_name, count)`.
    pub values: Vec<(String, u64)>,
}

impl DeviceStats {
    /// Parse device statistics from a raw byte buffer. Reads up to 5 u64
    /// counters (`write_errs`, `read_errs`, `flush_errs`, `corruption_errs`, generation).
    #[must_use]
    pub fn parse(data: &[u8]) -> Self {
        let stat_names = [
            "write_errs",
            "read_errs",
            "flush_errs",
            "corruption_errs",
            "generation",
        ];
        let mut buf = data;
        let mut values = Vec::new();
        for name in &stat_names {
            if buf.remaining() >= 8 {
                values.push((name.to_string(), buf.get_u64_le()));
            }
        }
        DeviceStats { values }
    }
}

/// UUID tree entry mapping a subvolume UUID to its objectid(s).
///
/// Key: `(upper_half_of_uuid, UUID_KEY_SUBVOL, lower_half_of_uuid)`.
#[derive(Debug, Clone)]
pub struct UuidItem {
    /// Subvolume objectids associated with this UUID.
    pub subvol_ids: Vec<u64>,
}

impl UuidItem {
    /// Parse a UUID tree item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Self {
        let mut buf = data;
        let mut subvol_ids = Vec::new();
        while buf.remaining() >= 8 {
            subvol_ids.push(buf.get_u64_le());
        }
        Self { subvol_ids }
    }
}

/// Parsed item payload: the typed result of parsing a leaf item's raw data
/// based on its key type.
///
/// Returned by [`parse_item_payload`]. Each variant wraps the corresponding
/// item struct. `Unknown` holds the raw bytes for unrecognized key types.
pub enum ItemPayload {
    /// Inode metadata (POSIX attributes, timestamps, flags).
    InodeItem(InodeItem),
    /// One or more hard-link references packed in a single item.
    InodeRef(Vec<InodeRef>),
    /// One or more extended inode references.
    InodeExtref(Vec<InodeExtref>),
    /// One or more directory entries (also used for `DIR_INDEX` and `XATTR_ITEM`).
    DirItem(Vec<DirItem>),
    /// Directory log item with the logged range end offset.
    DirLogItem {
        /// End of the logged directory range.
        end: u64,
    },
    /// Orphan marker (no data payload).
    OrphanItem,
    /// Tree root descriptor (subvolume, snapshot, or internal tree).
    RootItem(RootItem),
    /// Root forward or back reference (`ROOT_REF` / `ROOT_BACKREF`).
    RootRef(RootRef),
    /// File extent descriptor.
    FileExtentItem(FileExtentItem),
    /// Raw extent checksum data.
    ExtentCsum {
        /// Raw checksum bytes (array of per-sector checksums).
        data: Vec<u8>,
    },
    /// Extent allocation record (`EXTENT_ITEM` or `METADATA_ITEM`).
    ExtentItem(ExtentItem),
    /// Standalone tree block backref (no data payload; the key offset is the root).
    TreeBlockRef,
    /// Standalone shared block backref (no data payload; the key offset is the parent bytenr).
    SharedBlockRef,
    /// Standalone data extent backref.
    ExtentDataRef(ExtentDataRef),
    /// Standalone shared data extent backref.
    SharedDataRef(SharedDataRef),
    /// Simple ownership reference for an extent.
    ExtentOwnerRef {
        /// Tree objectid that owns this extent.
        root: u64,
    },
    /// Block group descriptor.
    BlockGroupItem(BlockGroupItem),
    /// Free space info for a block group.
    FreeSpaceInfo(FreeSpaceInfo),
    /// Free space extent (no data payload; key encodes start and length).
    FreeSpaceExtent,
    /// Free space bitmap (data payload is the bitmap).
    FreeSpaceBitmap,
    /// Chunk item mapping logical to physical addresses.
    ChunkItem(ChunkItem),
    /// Device item describing a single device.
    DeviceItem(DeviceItem),
    /// Physical extent mapping on a device.
    DeviceExtent(DeviceExtent),
    /// Quota group status.
    QgroupStatus(QgroupStatus),
    /// Quota group accounting info.
    QgroupInfo(QgroupInfo),
    /// Quota group limits.
    QgroupLimit(QgroupLimit),
    /// Quota group relation (no data payload; parent/child encoded in key).
    QgroupRelation,
    /// Per-device I/O error statistics.
    DeviceStats(DeviceStats),
    /// Balance status item.
    BalanceItem {
        /// Balance flags from the first 8 bytes of the item data.
        flags: u64,
    },
    /// Device replace status.
    DeviceReplace(DeviceReplaceItem),
    /// UUID tree entry mapping a UUID to subvolume objectids.
    UuidItem(UuidItem),
    /// String item (typically the superblock label).
    StringItem(Vec<u8>),
    /// RAID stripe extent mapping.
    RaidStripe(RaidStripeItem),
    /// Unrecognized item type; raw data preserved.
    Unknown(Vec<u8>),
}

/// Device replace status, persisted across reboots.
///
/// Key: `(DEV_REPLACE, PERSISTENT_ITEM, 0)`.
#[derive(Debug, Clone)]
pub struct DeviceReplaceItem {
    /// Device ID of the source device being replaced.
    pub src_devid: u64,
    /// Left cursor position (bytes processed from left).
    pub cursor_left: u64,
    /// Right cursor position.
    pub cursor_right: u64,
    /// Replace mode (continuous = 0 or legacy).
    pub replace_mode: u64,
    /// Current state (not started, started, suspended, etc.).
    pub replace_state: u64,
    /// Unix timestamp when the replace operation started.
    pub time_started: u64,
    /// Unix timestamp when the replace operation completed or was cancelled.
    pub time_stopped: u64,
    /// Number of write errors during replace.
    pub num_write_errors: u64,
    /// Number of uncorrectable read errors during replace.
    pub num_uncorrectable_read_errors: u64,
}

impl DeviceReplaceItem {
    /// Parse a device replace item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 80 {
            return None;
        }
        let mut buf = data;
        Some(Self {
            src_devid: buf.get_u64_le(),
            cursor_left: buf.get_u64_le(),
            cursor_right: buf.get_u64_le(),
            replace_mode: buf.get_u64_le(),
            replace_state: buf.get_u64_le(),
            time_started: buf.get_u64_le(),
            time_stopped: buf.get_u64_le(),
            num_write_errors: buf.get_u64_le(),
            num_uncorrectable_read_errors: buf.get_u64_le(),
        })
    }
}

/// RAID stripe extent mapping (for the raid-stripe-tree feature).
///
/// Key: `(logical_offset, RAID_STRIPE, length)`.
#[derive(Debug, Clone)]
pub struct RaidStripeItem {
    /// RAID encoding type.
    pub encoding: u64,
    /// Per-device stripe entries.
    pub stripes: Vec<RaidStripeEntry>,
}

/// A single device stripe within a RAID stripe item.
#[derive(Debug, Clone)]
pub struct RaidStripeEntry {
    /// Device ID for this stripe.
    pub devid: u64,
    /// Physical byte offset on the device.
    pub physical: u64,
}

impl RaidStripeItem {
    /// Parse a RAID stripe item from a raw byte buffer.
    #[must_use]
    pub fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < 8 {
            return None;
        }
        let mut buf = data;
        let encoding = buf.get_u64_le();
        let mut stripes = Vec::new();
        while buf.remaining() >= 16 {
            stripes.push(RaidStripeEntry {
                devid: buf.get_u64_le(),
                physical: buf.get_u64_le(),
            });
        }
        Some(Self { encoding, stripes })
    }
}

/// Parse an item's raw data into a typed payload based on its key type.
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn parse_item_payload(key: &DiskKey, data: &[u8]) -> ItemPayload {
    use crate::tree::KeyType;

    match key.key_type {
        KeyType::InodeItem => match InodeItem::parse(data) {
            Some(v) => ItemPayload::InodeItem(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::InodeRef => ItemPayload::InodeRef(InodeRef::parse_all(data)),
        KeyType::InodeExtref => {
            ItemPayload::InodeExtref(InodeExtref::parse_all(data))
        }
        KeyType::DirItem | KeyType::DirIndex | KeyType::XattrItem => {
            ItemPayload::DirItem(DirItem::parse_all(data))
        }
        KeyType::DirLogItem | KeyType::DirLogIndex => {
            let end = if data.len() >= 8 {
                let mut buf = data;
                buf.get_u64_le()
            } else {
                0
            };
            ItemPayload::DirLogItem { end }
        }
        KeyType::OrphanItem => ItemPayload::OrphanItem,
        KeyType::RootItem => match RootItem::parse(data) {
            Some(v) => ItemPayload::RootItem(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::RootRef | KeyType::RootBackref => match RootRef::parse(data) {
            Some(v) => ItemPayload::RootRef(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::ExtentData => match FileExtentItem::parse(data) {
            Some(v) => ItemPayload::FileExtentItem(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::ExtentCsum => ItemPayload::ExtentCsum {
            data: data.to_vec(),
        },
        KeyType::ExtentItem | KeyType::MetadataItem => {
            match ExtentItem::parse(data, key) {
                Some(v) => ItemPayload::ExtentItem(v),
                None => ItemPayload::Unknown(data.to_vec()),
            }
        }
        KeyType::TreeBlockRef => ItemPayload::TreeBlockRef,
        KeyType::SharedBlockRef => ItemPayload::SharedBlockRef,
        KeyType::ExtentDataRef => match ExtentDataRef::parse(data) {
            Some(v) => ItemPayload::ExtentDataRef(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::SharedDataRef => match SharedDataRef::parse(data) {
            Some(v) => ItemPayload::SharedDataRef(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::ExtentOwnerRef => {
            if data.len() >= 8 {
                let mut buf = data;
                ItemPayload::ExtentOwnerRef {
                    root: buf.get_u64_le(),
                }
            } else {
                ItemPayload::Unknown(data.to_vec())
            }
        }
        KeyType::BlockGroupItem => match BlockGroupItem::parse(data) {
            Some(v) => ItemPayload::BlockGroupItem(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::FreeSpaceInfo => match FreeSpaceInfo::parse(data) {
            Some(v) => ItemPayload::FreeSpaceInfo(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::FreeSpaceExtent => ItemPayload::FreeSpaceExtent,
        KeyType::FreeSpaceBitmap => ItemPayload::FreeSpaceBitmap,
        KeyType::ChunkItem => match ChunkItem::parse(data) {
            Some(v) => ItemPayload::ChunkItem(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::DeviceItem => match DeviceItem::parse(data) {
            Some(v) => ItemPayload::DeviceItem(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::DeviceExtent => match DeviceExtent::parse(data) {
            Some(v) => ItemPayload::DeviceExtent(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::QgroupStatus => match QgroupStatus::parse(data) {
            Some(v) => ItemPayload::QgroupStatus(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::QgroupInfo => match QgroupInfo::parse(data) {
            Some(v) => ItemPayload::QgroupInfo(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::QgroupLimit => match QgroupLimit::parse(data) {
            Some(v) => ItemPayload::QgroupLimit(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::QgroupRelation => ItemPayload::QgroupRelation,
        KeyType::PersistentItem => {
            if key.objectid == u64::from(raw::BTRFS_DEV_STATS_OBJECTID) {
                ItemPayload::DeviceStats(DeviceStats::parse(data))
            } else {
                ItemPayload::Unknown(data.to_vec())
            }
        }
        KeyType::TemporaryItem => {
            if ObjectId::from_raw(key.objectid) == ObjectId::Balance
                && data.len() >= 8
            {
                ItemPayload::BalanceItem {
                    flags: {
                        let mut buf = data;
                        buf.get_u64_le()
                    },
                }
            } else {
                ItemPayload::Unknown(data.to_vec())
            }
        }
        KeyType::DeviceReplace => match DeviceReplaceItem::parse(data) {
            Some(v) => ItemPayload::DeviceReplace(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        KeyType::UuidKeySubvol | KeyType::UuidKeyReceivedSubvol => {
            ItemPayload::UuidItem(UuidItem::parse(data))
        }
        KeyType::StringItem => ItemPayload::StringItem(data.to_vec()),
        KeyType::RaidStripe => match RaidStripeItem::parse(data) {
            Some(v) => ItemPayload::RaidStripe(v),
            None => ItemPayload::Unknown(data.to_vec()),
        },
        _ => ItemPayload::Unknown(data.to_vec()),
    }
}

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

    // ── Enum round-trips ──────────────────────────────────────────────

    #[test]
    fn compression_type_round_trip() {
        for v in 0..=3 {
            let ct = CompressionType::from_raw(v);
            assert_eq!(ct.to_raw(), v);
        }
        assert_eq!(CompressionType::from_raw(0), CompressionType::None);
        assert_eq!(CompressionType::from_raw(1), CompressionType::Zlib);
        assert_eq!(CompressionType::from_raw(2), CompressionType::Lzo);
        assert_eq!(CompressionType::from_raw(3), CompressionType::Zstd);
        assert_eq!(CompressionType::from_raw(99), CompressionType::Unknown(99));
        assert_eq!(CompressionType::Unknown(99).to_raw(), 99);
    }

    #[test]
    fn compression_type_names() {
        assert_eq!(CompressionType::None.name(), "none");
        assert_eq!(CompressionType::Zlib.name(), "zlib");
        assert_eq!(CompressionType::Lzo.name(), "lzo");
        assert_eq!(CompressionType::Zstd.name(), "zstd");
        assert_eq!(CompressionType::Unknown(42).name(), "unknown");
    }

    #[test]
    fn file_extent_type_round_trip() {
        assert_eq!(FileExtentType::from_raw(0), FileExtentType::Inline);
        assert_eq!(FileExtentType::from_raw(1), FileExtentType::Regular);
        assert_eq!(FileExtentType::from_raw(2), FileExtentType::Prealloc);
        assert_eq!(FileExtentType::from_raw(77), FileExtentType::Unknown(77));
        for v in 0..=2 {
            let ft = FileExtentType::from_raw(v);
            assert_eq!(ft.to_raw(), v);
        }
        assert_eq!(FileExtentType::Unknown(77).to_raw(), 77);
    }

    #[test]
    fn file_extent_type_names() {
        assert_eq!(FileExtentType::Inline.name(), "inline");
        assert_eq!(FileExtentType::Regular.name(), "regular");
        assert_eq!(FileExtentType::Prealloc.name(), "prealloc");
        assert_eq!(FileExtentType::Unknown(5).name(), "unknown");
    }

    #[test]
    fn file_type_from_raw_all_variants() {
        assert_eq!(FileType::from_raw(0), FileType::Unknown);
        assert_eq!(FileType::from_raw(1), FileType::RegFile);
        assert_eq!(FileType::from_raw(2), FileType::Dir);
        assert_eq!(FileType::from_raw(3), FileType::Chrdev);
        assert_eq!(FileType::from_raw(4), FileType::Blkdev);
        assert_eq!(FileType::from_raw(5), FileType::Fifo);
        assert_eq!(FileType::from_raw(6), FileType::Sock);
        assert_eq!(FileType::from_raw(7), FileType::Symlink);
        assert_eq!(FileType::from_raw(8), FileType::Xattr);
        assert_eq!(FileType::from_raw(99), FileType::Other(99));
    }

    #[test]
    fn file_type_names() {
        assert_eq!(FileType::Unknown.name(), "UNKNOWN");
        assert_eq!(FileType::RegFile.name(), "FILE");
        assert_eq!(FileType::Dir.name(), "DIR");
        assert_eq!(FileType::Chrdev.name(), "CHRDEV");
        assert_eq!(FileType::Blkdev.name(), "BLKDEV");
        assert_eq!(FileType::Fifo.name(), "FIFO");
        assert_eq!(FileType::Sock.name(), "SOCK");
        assert_eq!(FileType::Symlink.name(), "SYMLINK");
        assert_eq!(FileType::Xattr.name(), "XATTR");
        assert_eq!(FileType::Other(200).name(), "UNKNOWN");
    }

    // ── Simple struct parsers ─────────────────────────────────────────

    #[test]
    fn block_group_item_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&1000u64.to_le_bytes()); // used
        buf.extend_from_slice(&256u64.to_le_bytes()); // chunk_objectid
        buf.extend_from_slice(
            &(raw::BTRFS_BLOCK_GROUP_DATA as u64).to_le_bytes(),
        );
        let item = BlockGroupItem::parse(&buf).unwrap();
        assert_eq!(item.used, 1000);
        assert_eq!(item.chunk_objectid, 256);
        assert_eq!(item.flags, BlockGroupFlags::DATA);
    }

    #[test]
    fn block_group_item_too_short() {
        assert!(BlockGroupItem::parse(&[0; 23]).is_none());
    }

    #[test]
    fn free_space_info_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&42u32.to_le_bytes());
        buf.extend_from_slice(&7u32.to_le_bytes());
        let info = FreeSpaceInfo::parse(&buf).unwrap();
        assert_eq!(info.extent_count, 42);
        assert_eq!(info.flags, FreeSpaceInfoFlags::from_bits_truncate(7));
    }

    #[test]
    fn free_space_info_too_short() {
        assert!(FreeSpaceInfo::parse(&[0; 7]).is_none());
    }

    #[test]
    fn dev_extent_parse() {
        let size = mem::size_of::<raw::btrfs_dev_extent>();
        let mut buf = vec![0u8; size];
        buf[0..8].copy_from_slice(&3u64.to_le_bytes()); // chunk_tree
        buf[8..16].copy_from_slice(&256u64.to_le_bytes()); // chunk_objectid
        buf[16..24].copy_from_slice(&0x10000u64.to_le_bytes()); // chunk_offset
        buf[24..32].copy_from_slice(&0x40000u64.to_le_bytes()); // length
        // chunk_tree_uuid at offset 32
        buf[32..48].copy_from_slice(&[0xAB; 16]);
        let de = DeviceExtent::parse(&buf).unwrap();
        assert_eq!(de.chunk_tree, 3);
        assert_eq!(de.chunk_objectid, 256);
        assert_eq!(de.chunk_offset, 0x10000);
        assert_eq!(de.length, 0x40000);
        assert_eq!(de.chunk_tree_uuid.as_bytes(), &[0xAB; 16]);
    }

    #[test]
    fn dev_extent_too_short() {
        let size = mem::size_of::<raw::btrfs_dev_extent>();
        assert!(DeviceExtent::parse(&vec![0u8; size - 1]).is_none());
    }

    #[test]
    fn extent_data_ref_parse() {
        let size = mem::size_of::<raw::btrfs_extent_data_ref>();
        let mut buf = vec![0u8; size];
        buf[0..8].copy_from_slice(&5u64.to_le_bytes()); // root
        buf[8..16].copy_from_slice(&256u64.to_le_bytes()); // objectid
        buf[16..24].copy_from_slice(&0u64.to_le_bytes()); // offset
        buf[24..28].copy_from_slice(&1u32.to_le_bytes()); // count
        let edr = ExtentDataRef::parse(&buf).unwrap();
        assert_eq!(edr.root, 5);
        assert_eq!(edr.objectid, 256);
        assert_eq!(edr.offset, 0);
        assert_eq!(edr.count, 1);
    }

    #[test]
    fn extent_data_ref_too_short() {
        assert!(ExtentDataRef::parse(&[0; 27]).is_none());
    }

    #[test]
    fn shared_data_ref_parse() {
        let buf = 17u32.to_le_bytes();
        let sdr = SharedDataRef::parse(&buf).unwrap();
        assert_eq!(sdr.count, 17);
    }

    #[test]
    fn shared_data_ref_too_short() {
        assert!(SharedDataRef::parse(&[0; 3]).is_none());
    }

    #[test]
    fn qgroup_info_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&100u64.to_le_bytes()); // generation
        buf.extend_from_slice(&4096u64.to_le_bytes()); // referenced
        buf.extend_from_slice(&4096u64.to_le_bytes()); // referenced_compressed
        buf.extend_from_slice(&2048u64.to_le_bytes()); // exclusive
        buf.extend_from_slice(&2048u64.to_le_bytes()); // exclusive_compressed
        let qi = QgroupInfo::parse(&buf).unwrap();
        assert_eq!(qi.generation, 100);
        assert_eq!(qi.referenced, 4096);
        assert_eq!(qi.referenced_compressed, 4096);
        assert_eq!(qi.exclusive, 2048);
        assert_eq!(qi.exclusive_compressed, 2048);
    }

    #[test]
    fn qgroup_info_too_short() {
        assert!(QgroupInfo::parse(&[0; 39]).is_none());
    }

    #[test]
    fn qgroup_limit_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&3u64.to_le_bytes()); // flags
        buf.extend_from_slice(&1_000_000u64.to_le_bytes()); // max_referenced
        buf.extend_from_slice(&500_000u64.to_le_bytes()); // max_exclusive
        buf.extend_from_slice(&0u64.to_le_bytes()); // rsv_referenced
        buf.extend_from_slice(&0u64.to_le_bytes()); // rsv_exclusive
        let ql = QgroupLimit::parse(&buf).unwrap();
        assert_eq!(ql.flags, 3);
        assert_eq!(ql.max_referenced, 1_000_000);
        assert_eq!(ql.max_exclusive, 500_000);
        assert_eq!(ql.rsv_referenced, 0);
        assert_eq!(ql.rsv_exclusive, 0);
    }

    #[test]
    fn qgroup_limit_too_short() {
        assert!(QgroupLimit::parse(&[0; 39]).is_none());
    }

    #[test]
    fn qgroup_status_parse_minimal() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&1u64.to_le_bytes()); // version
        buf.extend_from_slice(&50u64.to_le_bytes()); // generation
        buf.extend_from_slice(&2u64.to_le_bytes()); // flags
        buf.extend_from_slice(&0u64.to_le_bytes()); // scan
        let qs = QgroupStatus::parse(&buf).unwrap();
        assert_eq!(qs.version, 1);
        assert_eq!(qs.generation, 50);
        assert_eq!(qs.flags, 2);
        assert_eq!(qs.scan, 0);
        assert!(qs.enable_gen.is_none());
    }

    #[test]
    fn qgroup_status_parse_with_enable_gen() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&1u64.to_le_bytes());
        buf.extend_from_slice(&50u64.to_le_bytes());
        buf.extend_from_slice(&2u64.to_le_bytes());
        buf.extend_from_slice(&0u64.to_le_bytes());
        buf.extend_from_slice(&99u64.to_le_bytes()); // enable_gen
        let qs = QgroupStatus::parse(&buf).unwrap();
        assert_eq!(qs.enable_gen, Some(99));
    }

    #[test]
    fn qgroup_status_too_short() {
        assert!(QgroupStatus::parse(&[0; 31]).is_none());
    }

    #[test]
    fn dev_replace_item_parse() {
        let mut buf = vec![0u8; 80];
        buf[0..8].copy_from_slice(&1u64.to_le_bytes()); // src_devid
        buf[8..16].copy_from_slice(&0x1000u64.to_le_bytes()); // cursor_left
        buf[16..24].copy_from_slice(&0x2000u64.to_le_bytes()); // cursor_right
        buf[24..32].copy_from_slice(&0u64.to_le_bytes()); // replace_mode
        buf[32..40].copy_from_slice(&2u64.to_le_bytes()); // replace_state
        buf[40..48].copy_from_slice(&1700000000u64.to_le_bytes()); // time_started
        buf[48..56].copy_from_slice(&1700000100u64.to_le_bytes()); // time_stopped
        buf[56..64].copy_from_slice(&3u64.to_le_bytes()); // num_write_errors
        buf[64..72].copy_from_slice(&5u64.to_le_bytes()); // num_uncorrectable_read_errors
        let dri = DeviceReplaceItem::parse(&buf).unwrap();
        assert_eq!(dri.src_devid, 1);
        assert_eq!(dri.cursor_left, 0x1000);
        assert_eq!(dri.cursor_right, 0x2000);
        assert_eq!(dri.replace_state, 2);
        assert_eq!(dri.time_started, 1700000000);
        assert_eq!(dri.time_stopped, 1700000100);
        assert_eq!(dri.num_write_errors, 3);
        assert_eq!(dri.num_uncorrectable_read_errors, 5);
    }

    #[test]
    fn dev_replace_item_too_short() {
        assert!(DeviceReplaceItem::parse(&[0; 79]).is_none());
    }

    #[test]
    fn raid_stripe_item_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&1u64.to_le_bytes()); // encoding
        // stripe 1
        buf.extend_from_slice(&1u64.to_le_bytes()); // devid
        buf.extend_from_slice(&0x10000u64.to_le_bytes()); // physical
        // stripe 2
        buf.extend_from_slice(&2u64.to_le_bytes());
        buf.extend_from_slice(&0x20000u64.to_le_bytes());
        let rsi = RaidStripeItem::parse(&buf).unwrap();
        assert_eq!(rsi.encoding, 1);
        assert_eq!(rsi.stripes.len(), 2);
        assert_eq!(rsi.stripes[0].devid, 1);
        assert_eq!(rsi.stripes[0].physical, 0x10000);
        assert_eq!(rsi.stripes[1].devid, 2);
        assert_eq!(rsi.stripes[1].physical, 0x20000);
    }

    #[test]
    fn raid_stripe_item_no_stripes() {
        let buf = 42u64.to_le_bytes();
        let rsi = RaidStripeItem::parse(&buf).unwrap();
        assert_eq!(rsi.encoding, 42);
        assert!(rsi.stripes.is_empty());
    }

    #[test]
    fn raid_stripe_item_too_short() {
        assert!(RaidStripeItem::parse(&[0; 7]).is_none());
    }

    // ── Variable-length parsers ───────────────────────────────────────

    #[test]
    fn inode_ref_parse_single() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&42u64.to_le_bytes()); // index
        buf.extend_from_slice(&4u16.to_le_bytes()); // name_len
        buf.extend_from_slice(b"test");
        let refs = InodeRef::parse_all(&buf);
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].index, 42);
        assert_eq!(refs[0].name, b"test");
    }

    #[test]
    fn inode_ref_parse_multiple() {
        let mut buf = Vec::new();
        // entry 1
        buf.extend_from_slice(&1u64.to_le_bytes());
        buf.extend_from_slice(&3u16.to_le_bytes());
        buf.extend_from_slice(b"abc");
        // entry 2
        buf.extend_from_slice(&2u64.to_le_bytes());
        buf.extend_from_slice(&2u16.to_le_bytes());
        buf.extend_from_slice(b"xy");
        let refs = InodeRef::parse_all(&buf);
        assert_eq!(refs.len(), 2);
        assert_eq!(refs[0].index, 1);
        assert_eq!(refs[0].name, b"abc");
        assert_eq!(refs[1].index, 2);
        assert_eq!(refs[1].name, b"xy");
    }

    #[test]
    fn inode_ref_parse_truncated() {
        // Header present but name extends past buffer end.
        let mut buf = Vec::new();
        buf.extend_from_slice(&1u64.to_le_bytes());
        buf.extend_from_slice(&10u16.to_le_bytes()); // claims 10 bytes
        buf.extend_from_slice(b"abc"); // only 3 available
        let refs = InodeRef::parse_all(&buf);
        assert!(refs.is_empty());
    }

    #[test]
    fn inode_extref_parse_single() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&256u64.to_le_bytes()); // parent
        buf.extend_from_slice(&3u64.to_le_bytes()); // index
        buf.extend_from_slice(&5u16.to_le_bytes()); // name_len
        buf.extend_from_slice(b"hello");
        let refs = InodeExtref::parse_all(&buf);
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].parent, 256);
        assert_eq!(refs[0].index, 3);
        assert_eq!(refs[0].name, b"hello");
    }

    #[test]
    fn dir_item_parse_single() {
        let dir_item_size = mem::size_of::<raw::btrfs_dir_item>();
        let mut buf = vec![0u8; dir_item_size];
        // location: DiskKey at offset 0 (17 bytes: u64 objectid + u8 type + u64 offset)
        buf[0..8].copy_from_slice(&256u64.to_le_bytes()); // objectid
        buf[8] = 1; // key type
        buf[9..17].copy_from_slice(&0u64.to_le_bytes()); // offset
        // transid at offset 17
        buf[17..25].copy_from_slice(&100u64.to_le_bytes());
        // data_len at offset 25
        buf[25..27].copy_from_slice(&0u16.to_le_bytes());
        // name_len at offset 27
        buf[27..29].copy_from_slice(&4u16.to_le_bytes());
        // file_type at offset 29
        buf[29] = 1; // FT_REG_FILE
        // Append name
        buf.extend_from_slice(b"file");
        let items = DirItem::parse_all(&buf);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].transid, 100);
        assert_eq!(items[0].file_type, FileType::RegFile);
        assert_eq!(items[0].name, b"file");
        assert!(items[0].data.is_empty());
    }

    #[test]
    fn root_ref_parse() {
        let hdr_size = mem::size_of::<raw::btrfs_root_ref>();
        let mut buf = vec![0u8; hdr_size];
        buf[0..8].copy_from_slice(&256u64.to_le_bytes()); // dirid
        buf[8..16].copy_from_slice(&7u64.to_le_bytes()); // sequence
        buf[16..18].copy_from_slice(&6u16.to_le_bytes()); // name_len
        buf.extend_from_slice(b"subvol");
        let rr = RootRef::parse(&buf).unwrap();
        assert_eq!(rr.dirid, 256);
        assert_eq!(rr.sequence, 7);
        assert_eq!(rr.name, b"subvol");
    }

    #[test]
    fn root_ref_too_short() {
        let hdr_size = mem::size_of::<raw::btrfs_root_ref>();
        assert!(RootRef::parse(&vec![0u8; hdr_size - 1]).is_none());
    }

    #[test]
    fn root_ref_serialize_round_trip() {
        let bytes = RootRef::serialize(256, 42, b"snapshot-1");
        let parsed = RootRef::parse(&bytes).unwrap();
        assert_eq!(parsed.dirid, 256);
        assert_eq!(parsed.sequence, 42);
        assert_eq!(parsed.name, b"snapshot-1");
        // Header is 18 bytes (8 + 8 + 2) plus the name.
        assert_eq!(bytes.len(), mem::size_of::<raw::btrfs_root_ref>() + 10);
    }

    #[test]
    fn root_ref_serialize_empty_name() {
        let bytes = RootRef::serialize(7, 0, b"");
        let parsed = RootRef::parse(&bytes).unwrap();
        assert_eq!(parsed.dirid, 7);
        assert_eq!(parsed.sequence, 0);
        assert!(parsed.name.is_empty());
    }

    #[test]
    fn uuid_item_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&256u64.to_le_bytes());
        buf.extend_from_slice(&257u64.to_le_bytes());
        buf.extend_from_slice(&258u64.to_le_bytes());
        let ui = UuidItem::parse(&buf);
        assert_eq!(ui.subvol_ids, vec![256, 257, 258]);
    }

    #[test]
    fn uuid_item_empty() {
        let ui = UuidItem::parse(&[]);
        assert!(ui.subvol_ids.is_empty());
    }

    #[test]
    fn dev_stats_parse() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&1u64.to_le_bytes()); // write_errs
        buf.extend_from_slice(&2u64.to_le_bytes()); // read_errs
        buf.extend_from_slice(&3u64.to_le_bytes()); // flush_errs
        buf.extend_from_slice(&4u64.to_le_bytes()); // corruption_errs
        buf.extend_from_slice(&5u64.to_le_bytes()); // generation
        let ds = DeviceStats::parse(&buf);
        assert_eq!(ds.values.len(), 5);
        assert_eq!(ds.values[0], ("write_errs".to_string(), 1));
        assert_eq!(ds.values[1], ("read_errs".to_string(), 2));
        assert_eq!(ds.values[2], ("flush_errs".to_string(), 3));
        assert_eq!(ds.values[3], ("corruption_errs".to_string(), 4));
        assert_eq!(ds.values[4], ("generation".to_string(), 5));
    }

    #[test]
    fn dev_stats_partial() {
        // Only 2 values available.
        let mut buf = Vec::new();
        buf.extend_from_slice(&10u64.to_le_bytes());
        buf.extend_from_slice(&20u64.to_le_bytes());
        let ds = DeviceStats::parse(&buf);
        assert_eq!(ds.values.len(), 2);
        assert_eq!(ds.values[0].1, 10);
        assert_eq!(ds.values[1].1, 20);
    }

    // ── FileExtentItem ────────────────────────────────────────────────

    #[test]
    fn file_extent_item_inline() {
        let mut buf = vec![0u8; 21 + 10]; // 21 header + 10 inline data
        buf[0..8].copy_from_slice(&7u64.to_le_bytes()); // generation
        buf[8..16].copy_from_slice(&10u64.to_le_bytes()); // ram_bytes
        buf[16] = 0; // compression = none
        // bytes 17-19 are encryption/other_encoding (unused)
        buf[20] = 0; // extent_type = inline
        buf[21..31].copy_from_slice(&[0xAA; 10]); // inline data
        let fei = FileExtentItem::parse(&buf).unwrap();
        assert_eq!(fei.generation, 7);
        assert_eq!(fei.ram_bytes, 10);
        assert_eq!(fei.compression, CompressionType::None);
        assert_eq!(fei.extent_type, FileExtentType::Inline);
        match fei.body {
            FileExtentBody::Inline { inline_size } => {
                assert_eq!(inline_size, 10)
            }
            _ => panic!("expected inline body"),
        }
    }

    #[test]
    fn file_extent_item_regular() {
        let mut buf = vec![0u8; 53];
        buf[0..8].copy_from_slice(&100u64.to_le_bytes()); // generation
        buf[8..16].copy_from_slice(&4096u64.to_le_bytes()); // ram_bytes
        buf[16] = 1; // compression = zlib
        buf[20] = 1; // extent_type = regular
        buf[21..29].copy_from_slice(&0x100000u64.to_le_bytes()); // disk_bytenr
        buf[29..37].copy_from_slice(&4096u64.to_le_bytes()); // disk_num_bytes
        buf[37..45].copy_from_slice(&0u64.to_le_bytes()); // offset
        buf[45..53].copy_from_slice(&4096u64.to_le_bytes()); // num_bytes
        let fei = FileExtentItem::parse(&buf).unwrap();
        assert_eq!(fei.generation, 100);
        assert_eq!(fei.compression, CompressionType::Zlib);
        assert_eq!(fei.extent_type, FileExtentType::Regular);
        match fei.body {
            FileExtentBody::Regular {
                disk_bytenr,
                disk_num_bytes,
                offset,
                num_bytes,
            } => {
                assert_eq!(disk_bytenr, 0x100000);
                assert_eq!(disk_num_bytes, 4096);
                assert_eq!(offset, 0);
                assert_eq!(num_bytes, 4096);
            }
            _ => panic!("expected regular body"),
        }
    }

    #[test]
    fn file_extent_item_too_short() {
        assert!(FileExtentItem::parse(&[0; 20]).is_none());
    }

    #[test]
    fn file_extent_item_regular_too_short() {
        // 21 bytes is enough for inline but not for regular.
        let mut buf = vec![0u8; 21];
        buf[20] = 1; // extent_type = regular
        assert!(FileExtentItem::parse(&buf).is_none());
    }

    #[test]
    fn file_extent_item_to_bytes_regular_round_trip() {
        let bytes = FileExtentItem::to_bytes_regular(
            42,
            65536,
            CompressionType::Zstd,
            false,
            0x200000,
            4096,
            0,
            65536,
        );
        assert_eq!(bytes.len(), FileExtentItem::REGULAR_SIZE);
        let parsed = FileExtentItem::parse(&bytes).unwrap();
        assert_eq!(parsed.generation, 42);
        assert_eq!(parsed.ram_bytes, 65536);
        assert_eq!(parsed.compression, CompressionType::Zstd);
        assert_eq!(parsed.extent_type, FileExtentType::Regular);
        match parsed.body {
            FileExtentBody::Regular {
                disk_bytenr,
                disk_num_bytes,
                offset,
                num_bytes,
            } => {
                assert_eq!(disk_bytenr, 0x200000);
                assert_eq!(disk_num_bytes, 4096);
                assert_eq!(offset, 0);
                assert_eq!(num_bytes, 65536);
            }
            _ => panic!("expected regular body"),
        }
    }

    #[test]
    fn file_extent_item_to_bytes_regular_prealloc_flag() {
        let bytes = FileExtentItem::to_bytes_regular(
            1,
            4096,
            CompressionType::None,
            true,
            0x10000,
            4096,
            0,
            4096,
        );
        let parsed = FileExtentItem::parse(&bytes).unwrap();
        assert_eq!(parsed.extent_type, FileExtentType::Prealloc);
    }

    #[test]
    fn file_extent_item_to_bytes_inline_round_trip() {
        let payload = b"hello inline";
        let bytes = FileExtentItem::to_bytes_inline(
            7,
            payload.len() as u64,
            CompressionType::None,
            payload,
        );
        assert_eq!(bytes.len(), FileExtentItem::HEADER_SIZE + payload.len());
        let parsed = FileExtentItem::parse(&bytes).unwrap();
        assert_eq!(parsed.generation, 7);
        assert_eq!(parsed.ram_bytes, payload.len() as u64);
        assert_eq!(parsed.compression, CompressionType::None);
        assert_eq!(parsed.extent_type, FileExtentType::Inline);
        match parsed.body {
            FileExtentBody::Inline { inline_size } => {
                assert_eq!(inline_size, payload.len());
            }
            _ => panic!("expected inline body"),
        }
        // Inline payload bytes must be preserved verbatim.
        assert_eq!(&bytes[FileExtentItem::HEADER_SIZE..], payload);
    }

    // ── Helper functions ──────────────────────────────────────────────

    #[test]
    fn raw_crc32c_known_value() {
        // The raw CRC32C of an empty buffer with seed 0 should be 0.
        assert_eq!(raw_crc32c(0, &[]), 0);
        // Verify that raw_crc32c differs from the standard CRC32C.
        // Standard CRC32C of "123456789" is 0xE3069283.
        let raw = raw_crc32c(0, b"123456789");
        let standard = crc32c::crc32c(b"123456789");
        assert_eq!(standard, 0xE3069283);
        assert_ne!(raw, standard);
        // raw_crc32c is deterministic.
        assert_eq!(raw, raw_crc32c(0, b"123456789"));
        // Chaining: raw_crc32c with a nonzero seed produces different results.
        let chained = raw_crc32c(raw, b"more");
        assert_ne!(chained, raw);
    }

    #[test]
    fn extent_data_ref_hash_deterministic() {
        let h1 = extent_data_ref_hash(5, 256, 0);
        let h2 = extent_data_ref_hash(5, 256, 0);
        assert_eq!(h1, h2);
        // Different inputs produce different hashes.
        let h3 = extent_data_ref_hash(5, 256, 4096);
        assert_ne!(h1, h3);
    }

    #[test]
    fn block_group_flags_type_name() {
        assert_eq!(BlockGroupFlags::DATA.type_name(), "Data");
        assert_eq!(BlockGroupFlags::METADATA.type_name(), "Metadata");
        assert_eq!(BlockGroupFlags::SYSTEM.type_name(), "System");
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::METADATA).type_name(),
            "Data+Metadata"
        );
        assert_eq!(BlockGroupFlags::GLOBAL_RSV.type_name(), "GlobalReserve");
    }

    #[test]
    fn block_group_flags_profile_name() {
        assert_eq!(BlockGroupFlags::DATA.profile_name(), "single");
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::DUP).profile_name(),
            "DUP"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID0).profile_name(),
            "RAID0"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID1).profile_name(),
            "RAID1"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID10).profile_name(),
            "RAID10"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID5).profile_name(),
            "RAID5"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID6).profile_name(),
            "RAID6"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID1C3).profile_name(),
            "RAID1C3"
        );
        assert_eq!(
            (BlockGroupFlags::DATA | BlockGroupFlags::RAID1C4).profile_name(),
            "RAID1C4"
        );
    }

    #[test]
    fn extent_item_skinny_size() {
        let bytes = ExtentItem::to_bytes_skinny(1, 42, 5);
        assert_eq!(bytes.len(), ExtentItem::SKINNY_SIZE);
        assert_eq!(bytes.len(), 33);
    }

    #[test]
    fn extent_item_non_skinny_size() {
        let key = DiskKey {
            objectid: 256,
            key_type: KeyType::InodeItem,
            offset: 0,
        };
        let bytes = ExtentItem::to_bytes_non_skinny(1, 42, 5, &key, 0);
        assert_eq!(bytes.len(), ExtentItem::NON_SKINNY_SIZE);
        assert_eq!(bytes.len(), 51);
    }

    #[test]
    fn extent_item_skinny_non_skinny_header_match() {
        let skinny = ExtentItem::to_bytes_skinny(1, 42, 5);
        let key = DiskKey {
            objectid: 0,
            key_type: KeyType::from_raw(0),
            offset: 0,
        };
        let non_skinny = ExtentItem::to_bytes_non_skinny(1, 42, 5, &key, 0);
        // First 24 bytes (refs + generation + flags) identical
        assert_eq!(&skinny[..24], &non_skinny[..24]);
    }

    #[test]
    fn extent_item_flags_are_tree_block() {
        let bytes = ExtentItem::to_bytes_skinny(1, 42, 5);
        let flags = u64::from_le_bytes(bytes[16..24].try_into().unwrap());
        assert_eq!(flags, ExtentFlags::TREE_BLOCK.bits());
    }

    #[test]
    fn root_item_to_bytes_round_trip() {
        let original = RootItem::new_internal(42, 65536, 0);
        let bytes = original.to_bytes();
        assert_eq!(bytes.len(), 439);
        let parsed = RootItem::parse(&bytes).expect("parse failed");
        assert_eq!(parsed.generation, 42);
        assert_eq!(parsed.bytenr, 65536);
        assert_eq!(parsed.level, 0);
        assert_eq!(parsed.refs, 1);
    }

    #[test]
    fn block_group_item_to_bytes_round_trip() {
        let bg = BlockGroupItem {
            used: 1024 * 1024,
            chunk_objectid: 256,
            flags: BlockGroupFlags::METADATA | BlockGroupFlags::DUP,
        };
        let bytes = bg.to_bytes();
        assert_eq!(bytes.len(), 24);
        let parsed = BlockGroupItem::parse(&bytes).unwrap();
        assert_eq!(parsed.used, bg.used);
        assert_eq!(parsed.chunk_objectid, bg.chunk_objectid);
        assert_eq!(parsed.flags, bg.flags);
    }

    #[test]
    fn inode_item_args_to_bytes_size() {
        let args = InodeItemArgs {
            generation: 7,
            size: 42,
            nbytes: 4096,
            nlink: 1,
            uid: 1000,
            gid: 1000,
            mode: 0o100644,
            time: Timespec { sec: 100, nsec: 0 },
        };
        let bytes = args.to_bytes();
        assert_eq!(bytes.len(), 160);
        let parsed = InodeItem::parse(&bytes).unwrap();
        assert_eq!(parsed.generation, 7);
        assert_eq!(parsed.size, 42);
        assert_eq!(parsed.nlink, 1);
    }

    #[test]
    fn dir_item_serialize_round_trip() {
        let location = DiskKey {
            objectid: 257,
            key_type: KeyType::InodeItem,
            offset: 0,
        };
        let bytes = DirItem::serialize(
            &location,
            7,
            raw::BTRFS_FT_REG_FILE as u8,
            b"hello.txt",
        );
        let items = DirItem::parse_all(&bytes);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].location.objectid, 257);
        assert_eq!(items[0].transid, 7);
        assert_eq!(items[0].name, b"hello.txt");
    }

    #[test]
    fn inode_ref_serialize_round_trip() {
        let bytes = InodeRef::serialize(2, b"hello.txt");
        let refs = InodeRef::parse_all(&bytes);
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].index, 2);
        assert_eq!(refs[0].name, b"hello.txt");
    }
}