isomage 2.1.0

Pure-Rust reader for ISO 9660, UDF, FAT, ext2/3/4, NTFS, HFS+, SquashFS, ZIP, TAR, and more. No unsafe, no runtime deps.
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
//! ext2 / ext3 / ext4 filesystem reader (`ext` feature).
//!
//! Reads the directory tree of an ext2/3/4 image and produces a
//! [`TreeNode`] compatible with `cat_node` / `extract_node`.
//!
//! Reference: Linux kernel Documentation/filesystems/ext4/,
//! and the e2fsprogs source tree.
//!
//! ## What is implemented
//!
//! - Superblock detection (magic `0xEF53` at offset 1080).
//! - Block group descriptor tables (32-byte "classic" and 64-byte
//!   "64bit" feature variants).
//! - Inode table reads for directories and regular files.
//! - Extent tree traversal (ext4, `EXT4_EXTENTS_FL`), up to depth 5.
//! - Classical block pointers: direct (i\_block\[0..11\]), single-indirect
//!   (i\_block\[12\]), double-indirect (i\_block\[13\]), and triple-indirect
//!   (i\_block\[14\]).
//! - Directory entry scanning (linear and htree-transparent: we walk the
//!   raw data blocks, so HTree is transparent).
//! - `INCOMPAT_FILETYPE` directories (file_type byte in each entry).
//! - `INCOMPAT_64BIT` high-32-bit block addresses in BGDs.
//! - Symlinks appear in the tree with correct size; devices/FIFOs/sockets
//!   are silently skipped.
//!
//! ## `file_location` semantics
//!
//! A file's `file_location` is set **only** when all data resides in a
//! single physically-contiguous block run. This is true for:
//! - Extent-tree depth=0 with exactly one extent.
//! - Classical mode with only direct blocks that happen to be contiguous
//!   and the file fits within the 12 direct pointers.
//!
//! Multi-extent, indirect-block, and inline-data files still appear in
//! the tree with correct `size`, but `file_location = None`. `cat_node`
//! will refuse those; `extract_node` can be extended later.

use std::io::{Read, Seek, SeekFrom};

use crate::tree::TreeNode;

// ── ECMA / Linux kernel spec constants ───────────────────────────────────────

/// Superblock magic (Linux kernel fs/ext4/ext4.h `EXT4_SUPER_MAGIC`).
const EXT_MAGIC: u16 = 0xEF53;

/// Byte offset of the superblock from the start of the filesystem.
/// (ECMA — not applicable; Linux kernel convention: 1024 bytes.)
const SUPERBLOCK_OFFSET: u64 = 1024;

// Inode mode bits (stat(2) S_IF* family).
const S_IFMT: u16 = 0xF000;
const S_IFREG: u16 = 0x8000;
const S_IFDIR: u16 = 0x4000;
const S_IFLNK: u16 = 0xA000;

// Inode flag bits (i_flags).
const EXT4_EXTENTS_FL: u32 = 0x0008_0000;
const EXT4_INLINE_DATA_FL: u32 = 0x1000_0000;

// Incompatible feature bits (s_feature_incompat).
const INCOMPAT_FILETYPE: u32 = 0x0002;
// INCOMPAT_EXTENTS (0x0040): inodes use extent trees; we check EXT4_EXTENTS_FL
// per-inode instead, so this flag is informational here.
const INCOMPAT_64BIT: u32 = 0x0080;

/// Extent tree node header magic (little-endian `0xF30A`).
const EXTENT_MAGIC: u16 = 0xF30A;

/// Maximum directory recursion depth before we give up, to avoid
/// stack overflows on corrupted images.
const MAX_DEPTH: usize = 32;

// ── Error type ────────────────────────────────────────────────────────────────

/// Reasons `detect` or `detect_and_parse` can fail.
#[derive(Debug)]
pub enum Error {
    /// Image shorter than the minimum to hold a superblock.
    TooShort,
    /// Superblock magic was not `0xEF53`, or other structural
    /// inconsistency that makes parsing unsafe to continue.
    BadSuperblock,
    /// Underlying I/O error.
    Io(std::io::Error),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::TooShort => write!(f, "image too short to contain an ext superblock"),
            Error::BadSuperblock => write!(f, "ext superblock magic 0xEF53 missing"),
            Error::Io(e) => write!(f, "ext I/O error: {e}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

// ── Superblock ────────────────────────────────────────────────────────────────

/// Parsed ext superblock fields we actually use.
#[derive(Debug, Clone)]
struct Superblock {
    inodes_per_group: u32,
    first_data_block: u32, // 1 for 1 KiB blocks, 0 for larger
    log_block_size: u32,   // block_size = 1024 << log_block_size
    inode_size: u16,       // inode size in bytes
    feature_incompat: u32,
    desc_size: u16, // block group descriptor size (64-bit ext4)
}

impl Superblock {
    fn block_size(&self) -> u64 {
        1024u64 << self.log_block_size
    }

    fn has_incompat(&self, flag: u32) -> bool {
        self.feature_incompat & flag != 0
    }

    fn desc_size_effective(&self) -> u64 {
        // 32 bytes for non-64bit, s_desc_size for 64-bit (must be ≥ 64).
        if self.has_incompat(INCOMPAT_64BIT) && self.desc_size >= 64 {
            self.desc_size as u64
        } else {
            32
        }
    }

    /// Byte offset (from image start) of the first block group descriptor.
    fn bgd_table_offset(&self, base_offset: u64) -> u64 {
        // The BGD table immediately follows the superblock block.
        // For 1 KiB blocks: superblock is in block 1, BGD in block 2.
        // For ≥ 2 KiB blocks: superblock is in block 0, BGD in block 1.
        let first_bgd_block = self.first_data_block as u64 + 1;
        base_offset + first_bgd_block * self.block_size()
    }
}

fn read_superblock<R: Read + Seek>(file: &mut R, base_offset: u64) -> Result<Superblock, Error> {
    file.seek(SeekFrom::Start(base_offset + SUPERBLOCK_OFFSET))?;
    let mut sb = [0u8; 264]; // up to s_desc_size at offset 236+2=238, take 264 for safety
    file.read_exact(&mut sb).map_err(|e| {
        if e.kind() == std::io::ErrorKind::UnexpectedEof {
            Error::TooShort
        } else {
            Error::Io(e)
        }
    })?;
    let magic = u16::from_le_bytes([sb[56], sb[57]]);
    if magic != EXT_MAGIC {
        return Err(Error::BadSuperblock);
    }
    // s_inodes_count, s_blocks_count_lo: only used for sanity checks.
    let blocks_count_lo = u32::from_le_bytes(sb[4..8].try_into().unwrap());
    let first_data_block = u32::from_le_bytes(sb[20..24].try_into().unwrap());
    let log_block_size = u32::from_le_bytes(sb[24..28].try_into().unwrap());
    let blocks_per_group = u32::from_le_bytes(sb[32..36].try_into().unwrap());
    let inodes_per_group = u32::from_le_bytes(sb[40..44].try_into().unwrap());

    // ext supports block sizes 1–64 KiB: log_block_size ∈ [0, 6].
    // Values ≥ 64 would panic the left-shift below; values > 6 indicate corruption.
    if log_block_size > 6 {
        return Err(Error::BadSuperblock);
    }

    let rev_level = u32::from_le_bytes(sb[76..80].try_into().unwrap());

    // Sanity: blocks_per_group must be non-zero (it's a divisor in inode location calc).
    if blocks_per_group == 0 {
        return Err(Error::BadSuperblock);
    }
    // Sanity: non-empty filesystem.
    if blocks_count_lo == 0 {
        return Err(Error::BadSuperblock);
    }
    // Sanity: inodes_per_group is a divisor when locating inodes.
    if inodes_per_group == 0 {
        return Err(Error::BadSuperblock);
    }

    let (inode_size, feature_incompat, desc_size) = if rev_level >= 1 {
        let inode_size = u16::from_le_bytes([sb[88], sb[89]]);
        let feature_incompat = u32::from_le_bytes(sb[96..100].try_into().unwrap());
        let desc_size = u16::from_le_bytes([sb[236], sb[237]]);
        (inode_size, feature_incompat, desc_size)
    } else {
        // rev_level 0: fixed 128-byte inodes, no extents.
        (128, 0, 32)
    };

    // Validate inode_size: must be a power of two ≥ 128 and ≤ block_size.
    let bs = 1024u64 << log_block_size;
    let eff_inode_size = if inode_size < 128 { 128u16 } else { inode_size };
    if eff_inode_size as u64 > bs {
        return Err(Error::BadSuperblock);
    }

    Ok(Superblock {
        inodes_per_group,
        first_data_block,
        log_block_size,
        inode_size: eff_inode_size,
        feature_incompat,
        desc_size,
    })
}

// ── Block Group Descriptor ────────────────────────────────────────────────────

/// Parsed block group descriptor, just the inode table address.
struct Bgd {
    inode_table: u64, // block number of the inode table
}

fn read_bgd<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    group: u64,
) -> Result<Bgd, Error> {
    let desc_size = sb.desc_size_effective();
    let offset = sb.bgd_table_offset(base_offset) + group * desc_size;
    file.seek(SeekFrom::Start(offset))?;
    let mut buf = vec![0u8; desc_size as usize];
    file.read_exact(&mut buf)?;

    let inode_table_lo = u32::from_le_bytes(buf[8..12].try_into().unwrap()) as u64;
    let inode_table = if sb.has_incompat(INCOMPAT_64BIT) && desc_size >= 64 {
        let hi = u32::from_le_bytes(buf[40..44].try_into().unwrap()) as u64;
        (hi << 32) | inode_table_lo
    } else {
        inode_table_lo
    };

    Ok(Bgd { inode_table })
}

// ── Inode ─────────────────────────────────────────────────────────────────────

/// Parsed inode fields.
struct Inode {
    mode: u16,
    size: u64, // full 64-bit size (lo | hi<<32 for regular files)
    flags: u32,
    i_block: [u32; 15], // raw 60-byte block-pointer / extent-root area
}

impl Inode {
    fn file_type_char(&self) -> u8 {
        ((self.mode & S_IFMT) >> 12) as u8
    }

    fn is_dir(&self) -> bool {
        self.mode & S_IFMT == S_IFDIR
    }

    fn is_reg(&self) -> bool {
        self.mode & S_IFMT == S_IFREG
    }

    fn is_symlink(&self) -> bool {
        self.mode & S_IFMT == S_IFLNK
    }

    fn uses_extents(&self) -> bool {
        self.flags & EXT4_EXTENTS_FL != 0
    }

    fn is_inline(&self) -> bool {
        self.flags & EXT4_INLINE_DATA_FL != 0
    }
}

fn read_inode<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    inode_num: u32,
) -> Result<Inode, Error> {
    if inode_num == 0 {
        return Err(Error::BadSuperblock);
    }
    let group = (inode_num as u64 - 1) / sb.inodes_per_group as u64;
    let local_index = (inode_num as u64 - 1) % sb.inodes_per_group as u64;

    let bgd = read_bgd(file, sb, base_offset, group)?;
    let inode_offset =
        base_offset + bgd.inode_table * sb.block_size() + local_index * sb.inode_size as u64;

    file.seek(SeekFrom::Start(inode_offset))?;
    // Read at least 112 bytes (up through i_size_high at 108..112).
    let read_len = (sb.inode_size as usize).max(112);
    let mut buf = vec![0u8; read_len];
    file.read_exact(&mut buf)?;

    let mode = u16::from_le_bytes([buf[0], buf[1]]);
    let size_lo = u32::from_le_bytes(buf[4..8].try_into().unwrap());
    let flags = u32::from_le_bytes(buf[32..36].try_into().unwrap());

    // i_block: 15 u32s at offset 40.
    let mut i_block = [0u32; 15];
    for (i, slot) in i_block.iter_mut().enumerate() {
        let off = 40 + i * 4;
        *slot = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap());
    }

    // Size high word (i_size_high, previously i_dir_acl) at offset 108.
    // Only meaningful for regular files (not directories).
    let size_high = u32::from_le_bytes(buf[108..112].try_into().unwrap());
    let size = if mode & S_IFMT == S_IFREG {
        (size_high as u64) << 32 | size_lo as u64
    } else {
        size_lo as u64
    };

    Ok(Inode {
        mode,
        size,
        flags,
        i_block,
    })
}

// ── Block reading ─────────────────────────────────────────────────────────────

/// Read `block_num` (filesystem-relative block number) into `buf`.
fn read_block<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    block_num: u64,
    buf: &mut Vec<u8>,
) -> Result<(), Error> {
    buf.resize(sb.block_size() as usize, 0);
    file.seek(SeekFrom::Start(base_offset + block_num * sb.block_size()))?;
    file.read_exact(buf)?;
    Ok(())
}

// ── Extent tree ───────────────────────────────────────────────────────────────

/// One leaf extent: maps logical blocks [first_logical_block, +len) to
/// physical block phys.
#[derive(Debug, Clone, Copy)]
struct Extent {
    len: u16,        // number of blocks (ee_len & 0x7FFF)
    phys: u64,       // physical starting block
    unwritten: bool, // bit 15 of ee_len: preallocated but not yet written
}

/// One internal node index entry: covers logical blocks starting at
/// first_logical_block, child node at physical block leaf.
#[derive(Debug, Clone, Copy)]
struct ExtentIdx {
    leaf: u64,
}

/// Decode the 12-byte extent tree header.
fn parse_extent_header(data: &[u8]) -> Option<(u16, u16)> {
    // magic, entries, max, depth
    if data.len() < 12 {
        return None;
    }
    let magic = u16::from_le_bytes([data[0], data[1]]);
    if magic != EXTENT_MAGIC {
        return None;
    }
    let entries = u16::from_le_bytes([data[2], data[3]]);
    let depth = u16::from_le_bytes([data[6], data[7]]);
    Some((entries, depth))
}

/// Parse `entries` leaf extents from `data` starting at byte 12.
fn parse_leaf_extents(data: &[u8], entries: u16) -> Vec<Extent> {
    let mut out = Vec::with_capacity(entries as usize);
    for i in 0..entries as usize {
        let off = 12 + i * 12;
        if off + 12 > data.len() {
            break;
        }
        let ee_len = u16::from_le_bytes([data[off + 4], data[off + 5]]);
        let ee_start_hi = u16::from_le_bytes([data[off + 6], data[off + 7]]) as u64;
        let ee_start_lo = u32::from_le_bytes(data[off + 8..off + 12].try_into().unwrap()) as u64;
        let phys = (ee_start_hi << 32) | ee_start_lo;
        let unwritten = ee_len & 0x8000 != 0;
        let len = ee_len & 0x7FFF;
        out.push(Extent {
            len,
            phys,
            unwritten,
        });
    }
    out
}

/// Parse `entries` internal index entries from `data` starting at byte 12.
fn parse_idx_entries(data: &[u8], entries: u16) -> Vec<ExtentIdx> {
    let mut out = Vec::with_capacity(entries as usize);
    for i in 0..entries as usize {
        let off = 12 + i * 12;
        if off + 12 > data.len() {
            break;
        }
        let leaf_lo = u32::from_le_bytes(data[off + 4..off + 8].try_into().unwrap()) as u64;
        let leaf_hi = u16::from_le_bytes([data[off + 8], data[off + 9]]) as u64;
        let leaf = (leaf_hi << 32) | leaf_lo;
        out.push(ExtentIdx { leaf });
    }
    out
}

/// Walk the extent tree rooted at `node_data` and collect all leaf extents.
/// `node_data` is the raw 60 bytes of i_block, or a block read from disk.
///
/// Recursion is bounded by the depth field in each header; max depth 5 per
/// kernel, and we hard-cap at 5 to be safe on corrupted images.
fn collect_extents<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    node_data: &[u8],
    remaining_depth: u8,
) -> Result<Vec<Extent>, Error> {
    let Some((entries, depth)) = parse_extent_header(node_data) else {
        return Ok(Vec::new());
    };

    if depth == 0 {
        // Leaf node.
        return Ok(parse_leaf_extents(node_data, entries));
    }

    if remaining_depth == 0 {
        // Depth exceeded our safety cap — treat as empty.
        return Ok(Vec::new());
    }

    // Internal node: recurse into each child block.
    let idx_entries = parse_idx_entries(node_data, entries);
    let mut block_buf = Vec::new();
    let mut all_extents = Vec::new();
    for idx in idx_entries {
        read_block(file, sb, base_offset, idx.leaf, &mut block_buf)?;
        let child_extents =
            collect_extents(file, sb, base_offset, &block_buf, remaining_depth - 1)?;
        all_extents.extend(child_extents);
    }
    Ok(all_extents)
}

// ── Classical block pointer iteration ────────────────────────────────────────

/// Read one block of u32 block pointers from `block_num`.
fn read_ptr_block<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    block_num: u64,
) -> Result<Vec<u32>, Error> {
    let bs = sb.block_size() as usize;
    let mut buf = vec![0u8; bs];
    file.seek(SeekFrom::Start(base_offset + block_num * sb.block_size()))?;
    file.read_exact(&mut buf)?;
    Ok(buf
        .chunks_exact(4)
        .map(|c| u32::from_le_bytes(c.try_into().unwrap()))
        .collect())
}

/// Collect all physical data block numbers for an inode using classical
/// (non-extent) block addressing, in logical order, stopping once `size`
/// bytes are covered.
///
/// Handles direct (0..11), single-indirect (12), double-indirect (13),
/// and triple-indirect (14) pointers.
fn collect_classical_blocks<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    inode: &Inode,
    size: u64,
) -> Result<Vec<u64>, Error> {
    let bs = sb.block_size();
    let mut blocks: Vec<u64> = Vec::new();
    let mut covered: u64 = 0;

    // Direct blocks: i_block[0..11].
    for &blk in &inode.i_block[0..12] {
        if blk == 0 || covered >= size {
            break;
        }
        blocks.push(blk as u64);
        covered += bs;
    }

    if covered >= size {
        return Ok(blocks);
    }

    // Single-indirect: i_block[12].
    let si = inode.i_block[12];
    if si != 0 {
        let ptrs = read_ptr_block(file, sb, base_offset, si as u64)?;
        for blk in ptrs {
            if blk == 0 || covered >= size {
                break;
            }
            blocks.push(blk as u64);
            covered += bs;
        }
    }

    if covered >= size {
        return Ok(blocks);
    }

    // Double-indirect: i_block[13].
    let di = inode.i_block[13];
    if di != 0 {
        let l1 = read_ptr_block(file, sb, base_offset, di as u64)?;
        'di_outer: for l1ptr in l1 {
            if l1ptr == 0 || covered >= size {
                break;
            }
            let l2 = read_ptr_block(file, sb, base_offset, l1ptr as u64)?;
            for blk in l2 {
                if blk == 0 || covered >= size {
                    break 'di_outer;
                }
                blocks.push(blk as u64);
                covered += bs;
            }
        }
    }

    if covered >= size {
        return Ok(blocks);
    }

    // Triple-indirect: i_block[14].
    let ti = inode.i_block[14];
    if ti != 0 {
        let l1 = read_ptr_block(file, sb, base_offset, ti as u64)?;
        'ti_outer: for l1ptr in l1 {
            if l1ptr == 0 || covered >= size {
                break;
            }
            let l2 = read_ptr_block(file, sb, base_offset, l1ptr as u64)?;
            'ti_middle: for l2ptr in l2 {
                if l2ptr == 0 || covered >= size {
                    break 'ti_outer;
                }
                let l3 = read_ptr_block(file, sb, base_offset, l2ptr as u64)?;
                for blk in l3 {
                    if blk == 0 || covered >= size {
                        break 'ti_middle;
                    }
                    blocks.push(blk as u64);
                    covered += bs;
                }
            }
        }
    }

    Ok(blocks)
}

// ── Directory parsing ─────────────────────────────────────────────────────────

/// One directory entry (partially parsed — just what we need).
#[derive(Debug)]
struct DirEntry {
    inode: u32,
    name: String,
}

/// Scan a raw directory data block for entries, pushing valid ones into `out`.
fn scan_dir_block(data: &[u8], has_filetype: bool, out: &mut Vec<DirEntry>) {
    let mut pos = 0usize;
    while pos + 8 <= data.len() {
        let inode = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
        let rec_len = u16::from_le_bytes([data[pos + 4], data[pos + 5]]) as usize;
        let name_len = data[pos + 6] as usize;
        // file_type is at pos+7 when INCOMPAT_FILETYPE; otherwise name_len_high.
        // Either way, the name starts at pos+8.

        if rec_len < 8 || pos + rec_len > data.len() {
            break;
        }
        if inode != 0 && name_len > 0 && pos + 8 + name_len <= data.len() {
            let raw = &data[pos + 8..pos + 8 + name_len];
            let name = String::from_utf8_lossy(raw).into_owned();
            if name != "." && name != ".." {
                let _file_type = if has_filetype { data[pos + 7] } else { 0 };
                out.push(DirEntry { inode, name });
            }
        }
        pos += rec_len.max(1); // guard against rec_len=0 infinite loop
    }
}

/// Read all directory entries from an inode.
fn read_dir_entries<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    inode: &Inode,
) -> Result<Vec<DirEntry>, Error> {
    let has_filetype = sb.has_incompat(INCOMPAT_FILETYPE);
    let mut entries = Vec::new();
    let mut block_buf = Vec::new();

    if inode.uses_extents() {
        // i_block holds the extent tree root (60 bytes = 12-byte header + up
        // to 4 leaf extents at depth=0, or index entries at depth>0).
        let root_bytes: Vec<u8> = inode
            .i_block
            .iter()
            .flat_map(|&w| w.to_le_bytes())
            .collect();
        let extents = collect_extents(file, sb, base_offset, &root_bytes, 5)?;
        for ext in extents {
            for i in 0..ext.len as u64 {
                read_block(file, sb, base_offset, ext.phys + i, &mut block_buf)?;
                scan_dir_block(&block_buf, has_filetype, &mut entries);
            }
        }
    } else {
        // Classical block pointers: collect block numbers first, then read
        // each block in a separate pass to avoid split-borrow issues.
        let blk_nums = collect_classical_blocks(file, sb, base_offset, inode, inode.size)?;
        for blk in blk_nums {
            read_block(file, sb, base_offset, blk, &mut block_buf)?;
            scan_dir_block(&block_buf, has_filetype, &mut entries);
        }
    }

    Ok(entries)
}

// ── File location detection ────────────────────────────────────────────────────

/// Try to find a single contiguous physical location for `inode`'s data.
/// Returns `Some(byte_offset_in_image)` only when the entire file content
/// lives in one unbroken physical run.
fn single_run_location<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    inode: &Inode,
) -> Result<Option<u64>, Error> {
    if inode.size == 0 {
        return Ok(None);
    }
    if inode.is_inline() {
        return Ok(None);
    }

    if inode.uses_extents() {
        let root_bytes: Vec<u8> = inode
            .i_block
            .iter()
            .flat_map(|&w| w.to_le_bytes())
            .collect();
        let extents = collect_extents(file, sb, base_offset, &root_bytes, 5)?;
        // Single contiguous run: exactly one non-unwritten extent whose block
        // count covers the full file. Unwritten extents are preallocated but
        // contain stale on-disk data; reading them would return garbage.
        if extents.len() == 1 {
            let ext = &extents[0];
            if !ext.unwritten {
                let needed_blocks = inode.size.div_ceil(sb.block_size());
                if ext.len as u64 >= needed_blocks {
                    return Ok(Some(base_offset + ext.phys * sb.block_size()));
                }
            }
        }
        return Ok(None);
    }

    // Classical mode: check that the direct blocks are a contiguous run.
    // We only check if the file fits within the direct pointer range
    // (i_block[0..11]) to keep the logic simple and reliable.
    let bs = sb.block_size();
    let needed_blocks = inode.size.div_ceil(bs);
    if needed_blocks > 12 {
        // Would require indirect blocks; skip contiguous check.
        return Ok(None);
    }

    // Require all needed direct blocks to be consecutive.
    let first = inode.i_block[0] as u64;
    if first == 0 {
        return Ok(None);
    }
    for i in 1..needed_blocks as usize {
        if inode.i_block[i] as u64 != first + i as u64 {
            return Ok(None);
        }
    }
    Ok(Some(base_offset + first * bs))
}

// ── Tree building ─────────────────────────────────────────────────────────────

/// Recursively build a `TreeNode` tree rooted at `inode_num`.
/// `depth` is the current recursion depth (starts at 0 for root).
fn build_tree<R: Read + Seek>(
    file: &mut R,
    sb: &Superblock,
    base_offset: u64,
    name: String,
    inode_num: u32,
    depth: usize,
) -> Result<Option<TreeNode>, Error> {
    if depth > MAX_DEPTH {
        return Ok(None);
    }

    let inode = read_inode(file, sb, base_offset, inode_num)?;

    if inode.is_dir() {
        let mut node = TreeNode::new_directory(name);
        let entries = read_dir_entries(file, sb, base_offset, &inode)?;
        for entry in entries {
            if let Some(child) =
                build_tree(file, sb, base_offset, entry.name, entry.inode, depth + 1)?
            {
                node.add_child(child);
            }
        }
        Ok(Some(node))
    } else if inode.is_reg() {
        // Inline-data files: in tree but no location.
        if inode.is_inline() {
            return Ok(Some(TreeNode::new_file(name, inode.size)));
        }
        let loc = single_run_location(file, sb, base_offset, &inode)?;
        let node = match loc {
            Some(offset) => TreeNode::new_file_with_location(name, inode.size, offset, inode.size),
            None => TreeNode::new_file(name, inode.size),
        };
        Ok(Some(node))
    } else if inode.is_symlink() {
        // Fast symlinks store the target path in i_block directly; there are
        // no data blocks. Non-fast symlinks do use blocks, but we can't
        // reliably distinguish without reading more state. Never set
        // file_location for symlinks to avoid returning a bogus offset.
        Ok(Some(TreeNode::new_file(name, inode.size)))
    } else {
        // Block/char devices, FIFOs, sockets — skip.
        let _ = inode.file_type_char(); // suppress unused warning
        Ok(None)
    }
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Return `true` if the stream at its current position looks like an ext
/// filesystem.
///
/// Reads 2 bytes from the superblock's magic field and restores the stream
/// position whether or not detection succeeds.
pub fn detect<R: Read + Seek>(file: &mut R) -> bool {
    let saved = match file.stream_position() {
        Ok(p) => p,
        Err(_) => return false,
    };
    let ok = detect_inner(file);
    let _ = file.seek(SeekFrom::Start(saved));
    ok
}

fn detect_inner<R: Read + Seek>(file: &mut R) -> bool {
    // We need to know where "base" is — use current position.
    let base = match file.stream_position() {
        Ok(p) => p,
        Err(_) => return false,
    };
    let magic_offset = base + SUPERBLOCK_OFFSET + 56;
    if file.seek(SeekFrom::Start(magic_offset)).is_err() {
        return false;
    }
    let mut magic_buf = [0u8; 2];
    if file.read_exact(&mut magic_buf).is_err() {
        return false;
    }
    u16::from_le_bytes(magic_buf) == EXT_MAGIC
}

/// Detect and parse an ext2/3/4 filesystem, returning the directory tree.
///
/// `file`'s current position is treated as the filesystem's base offset,
/// allowing this function to parse ext partitions that start mid-image.
pub fn detect_and_parse<R: Read + Seek>(file: &mut R) -> Result<TreeNode, Error> {
    let base_offset = file.stream_position()?;

    let sb = read_superblock(file, base_offset)?;

    // Root inode is always #2.
    let mut root =
        build_tree(file, &sb, base_offset, "/".to_string(), 2, 0)?.ok_or(Error::BadSuperblock)?;

    root.calculate_directory_size();
    Ok(root)
}

// ── Unit tests ────────────────────────────────────────────────────────────────

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

    // ── Minimal in-memory ext2 image builder ──────────────────────────────

    /// Build a minimal valid ext2 image in memory.
    ///
    /// Layout (1 KiB blocks, 256 KiB total, 1 block group):
    ///
    /// - Block 0: boot block (empty)
    /// - Block 1: superblock
    /// - Block 2: block group descriptor table (one entry, 32 bytes)
    /// - Block 3: block bitmap (all zeros except blocks 0-7 marked used)
    /// - Block 4: inode bitmap (inodes 1-3 marked used)
    /// - Block 5: inode table (inode 2 = root dir, inode 3 = hello.txt)
    /// - Block 6: root directory data block
    /// - Block 7: hello.txt data block
    ///
    /// Features: INCOMPAT_FILETYPE, no extents (classical block pointers).
    fn make_ext2_image() -> Vec<u8> {
        const BS: usize = 1024;
        const TOTAL_BLOCKS: usize = 256;
        const IMAGE_SIZE: usize = TOTAL_BLOCKS * BS;
        const INODE_SIZE: usize = 128;
        const INODES_PER_GROUP: usize = 256;

        // Block assignments.
        const BLOCK_BITMAP_BLK: usize = 3;
        const INODE_BITMAP_BLK: usize = 4;
        const INODE_TABLE_BLK: usize = 5;
        const ROOT_DATA_BLK: usize = 6;
        const FILE_DATA_BLK: usize = 7;

        // Inode numbers.
        const ROOT_INUM: usize = 2;
        const FILE_INUM: usize = 3;

        let mut img = vec![0u8; IMAGE_SIZE];

        // ── Superblock (block 1 = offset 1024) ──────────────────────────
        {
            let sb = &mut img[1024..1024 + 264];
            // s_inodes_count
            sb[0..4].copy_from_slice(&(INODES_PER_GROUP as u32).to_le_bytes());
            // s_blocks_count_lo
            sb[4..8].copy_from_slice(&(TOTAL_BLOCKS as u32).to_le_bytes());
            // s_first_data_block = 1 (for 1 KiB blocks)
            sb[20..24].copy_from_slice(&1u32.to_le_bytes());
            // s_log_block_size = 0  →  block_size = 1024
            sb[24..28].copy_from_slice(&0u32.to_le_bytes());
            // s_blocks_per_group
            sb[32..36].copy_from_slice(&(TOTAL_BLOCKS as u32).to_le_bytes());
            // s_inodes_per_group
            sb[40..44].copy_from_slice(&(INODES_PER_GROUP as u32).to_le_bytes());
            // s_magic = 0xEF53
            sb[56..58].copy_from_slice(&EXT_MAGIC.to_le_bytes());
            // s_rev_level = 1 (dynamic)
            sb[76..80].copy_from_slice(&1u32.to_le_bytes());
            // s_first_ino = 11
            sb[84..88].copy_from_slice(&11u32.to_le_bytes());
            // s_inode_size = 128
            sb[88..90].copy_from_slice(&(INODE_SIZE as u16).to_le_bytes());
            // s_feature_compat = 0
            sb[92..96].copy_from_slice(&0u32.to_le_bytes());
            // s_feature_incompat = INCOMPAT_FILETYPE
            sb[96..100].copy_from_slice(&INCOMPAT_FILETYPE.to_le_bytes());
            // s_feature_ro_compat = 0
            sb[100..104].copy_from_slice(&0u32.to_le_bytes());
            // s_desc_size = 32
            sb[236..238].copy_from_slice(&32u16.to_le_bytes());
        }

        // ── Block group descriptor (block 2 = offset 2048) ──────────────
        {
            // BGD is right after the superblock block. For 1 KiB blocks,
            // s_first_data_block = 1, so BGD starts at block 2.
            let bgd = &mut img[2 * BS..2 * BS + 32];
            // bg_block_bitmap_lo
            bgd[0..4].copy_from_slice(&(BLOCK_BITMAP_BLK as u32).to_le_bytes());
            // bg_inode_bitmap_lo
            bgd[4..8].copy_from_slice(&(INODE_BITMAP_BLK as u32).to_le_bytes());
            // bg_inode_table_lo
            bgd[8..12].copy_from_slice(&(INODE_TABLE_BLK as u32).to_le_bytes());
        }

        // ── Inode table ──────────────────────────────────────────────────
        // Inode #2 (root directory), stored at index 1 (0-indexed).
        {
            let inode_base = INODE_TABLE_BLK * BS;
            let root_off = inode_base + (ROOT_INUM - 1) * INODE_SIZE;
            let ino = &mut img[root_off..root_off + INODE_SIZE];
            // i_mode = S_IFDIR | 0755
            let mode: u16 = S_IFDIR | 0o755;
            ino[0..2].copy_from_slice(&mode.to_le_bytes());
            // i_size_lo (will be filled after directory block is built)
            ino[4..8].copy_from_slice(&(BS as u32).to_le_bytes());
            // i_links_count
            ino[26..28].copy_from_slice(&2u16.to_le_bytes());
            // i_flags = 0 (no extents, no inline)
            ino[32..36].copy_from_slice(&0u32.to_le_bytes());
            // i_block[0] = ROOT_DATA_BLK
            ino[40..44].copy_from_slice(&(ROOT_DATA_BLK as u32).to_le_bytes());
        }

        // Inode #3 (hello.txt), stored at index 2.
        {
            let inode_base = INODE_TABLE_BLK * BS;
            let file_off = inode_base + (FILE_INUM - 1) * INODE_SIZE;
            let ino = &mut img[file_off..file_off + INODE_SIZE];
            let mode: u16 = S_IFREG | 0o644;
            ino[0..2].copy_from_slice(&mode.to_le_bytes());
            // i_size_lo = 12 ("hello world\n")
            ino[4..8].copy_from_slice(&12u32.to_le_bytes());
            ino[26..28].copy_from_slice(&1u16.to_le_bytes());
            ino[32..36].copy_from_slice(&0u32.to_le_bytes());
            // i_block[0] = FILE_DATA_BLK
            ino[40..44].copy_from_slice(&(FILE_DATA_BLK as u32).to_le_bytes());
        }

        // ── Root directory data block ────────────────────────────────────
        // Two entries: "." → inode 2, "hello.txt" → inode 3.
        // With INCOMPAT_FILETYPE, byte 7 of each entry is file_type.
        {
            let dblk = &mut img[ROOT_DATA_BLK * BS..ROOT_DATA_BLK * BS + BS];

            // Entry 0: "."  inode=2  rec_len=12  name_len=1  file_type=2(dir)
            let e0_rec: u16 = 12;
            dblk[0..4].copy_from_slice(&(ROOT_INUM as u32).to_le_bytes());
            dblk[4..6].copy_from_slice(&e0_rec.to_le_bytes());
            dblk[6] = 1; // name_len
            dblk[7] = 2; // file_type = directory
            dblk[8] = b'.';

            // Entry 1: ".."  inode=2  rec_len=12  name_len=2  file_type=2
            let e1_off = 12;
            let e1_rec: u16 = 12;
            dblk[e1_off..e1_off + 4].copy_from_slice(&(ROOT_INUM as u32).to_le_bytes());
            dblk[e1_off + 4..e1_off + 6].copy_from_slice(&e1_rec.to_le_bytes());
            dblk[e1_off + 6] = 2; // name_len
            dblk[e1_off + 7] = 2; // file_type = directory
            dblk[e1_off + 8] = b'.';
            dblk[e1_off + 9] = b'.';

            // Entry 2: "hello.txt"  inode=3  rec_len=(1024-24)  name_len=9  file_type=1
            let e2_off = 24;
            let e2_rec: u16 = (BS - e2_off) as u16;
            dblk[e2_off..e2_off + 4].copy_from_slice(&(FILE_INUM as u32).to_le_bytes());
            dblk[e2_off + 4..e2_off + 6].copy_from_slice(&e2_rec.to_le_bytes());
            dblk[e2_off + 6] = 9; // name_len = len("hello.txt")
            dblk[e2_off + 7] = 1; // file_type = regular
            dblk[e2_off + 8..e2_off + 17].copy_from_slice(b"hello.txt");
        }

        // ── File data block ──────────────────────────────────────────────
        {
            let fblk = &mut img[FILE_DATA_BLK * BS..FILE_DATA_BLK * BS + 12];
            fblk.copy_from_slice(b"hello world\n");
        }

        img
    }

    // ── Test helpers ──────────────────────────────────────────────────────

    fn cursor_of(img: &[u8]) -> Cursor<Vec<u8>> {
        Cursor::new(img.to_vec())
    }

    // ── Detection tests ───────────────────────────────────────────────────

    #[test]
    fn detect_valid_ext2() {
        let img = make_ext2_image();
        let mut c = cursor_of(&img);
        assert!(detect(&mut c), "should detect valid ext2 image");
    }

    #[test]
    fn detect_restores_position() {
        let img = make_ext2_image();
        let mut c = cursor_of(&img);
        c.seek(SeekFrom::Start(42)).unwrap();
        let _ = detect(&mut c);
        assert_eq!(
            c.stream_position().unwrap(),
            42,
            "detect() must restore stream position"
        );
    }

    #[test]
    fn detect_restores_position_on_failure() {
        // Too-short image — detect returns false, position should still be 0.
        let img = vec![0u8; 512];
        let mut c = Cursor::new(img);
        c.seek(SeekFrom::Start(7)).unwrap();
        let _ = detect(&mut c);
        assert_eq!(c.stream_position().unwrap(), 7);
    }

    #[test]
    fn detect_rejects_bad_magic() {
        let mut img = make_ext2_image();
        // Corrupt the magic bytes.
        img[1024 + 56] = 0xDE;
        img[1024 + 57] = 0xAD;
        let mut c = cursor_of(&img);
        assert!(!detect(&mut c), "corrupted magic should not detect as ext");
    }

    #[test]
    fn detect_rejects_too_short() {
        // Image too short to even contain the magic field.
        let img = vec![0u8; 512];
        let mut c = Cursor::new(img);
        assert!(!detect(&mut c));
    }

    #[test]
    fn detect_rejects_fat_image() {
        // A FAT12 boot sector starts with 0xEB 0x?? 0x90 and "FAT" at 54.
        let mut img = vec![0u8; 2048];
        img[0] = 0xEB;
        img[1] = 0x58;
        img[2] = 0x90;
        img[3..8].copy_from_slice(b"FAT12");
        let mut c = Cursor::new(img);
        assert!(!detect(&mut c), "FAT image should not be detected as ext");
    }

    // ── Parse tests ───────────────────────────────────────────────────────

    #[test]
    fn parse_ext2_tree_shape() {
        let img = make_ext2_image();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("parse ext2 image");
        assert_eq!(root.name, "/");
        assert!(root.is_directory);
        assert_eq!(
            root.children.len(),
            1,
            "root should have exactly 1 child (hello.txt)"
        );
        assert_eq!(root.children[0].name, "hello.txt");
        assert!(!root.children[0].is_directory);
        assert_eq!(root.children[0].size, 12);
    }

    #[test]
    fn parse_ext2_file_location() {
        let img = make_ext2_image();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("parse");
        let file = root
            .children
            .iter()
            .find(|n| n.name == "hello.txt")
            .unwrap();
        // file_location should be Some(...) — classical contiguous direct blocks.
        assert!(
            file.file_location.is_some(),
            "hello.txt should have a file_location"
        );
        // Should point to block 7 (FILE_DATA_BLK) in the image.
        let expected = 7 * 1024u64;
        assert_eq!(
            file.file_location.unwrap(),
            expected,
            "file_location should point to block 7"
        );
    }

    #[test]
    fn parse_ext2_file_contents() {
        let img = make_ext2_image();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("parse");
        let file = root
            .children
            .iter()
            .find(|n| n.name == "hello.txt")
            .unwrap();
        let loc = file.file_location.unwrap();
        let len = file.size as usize;
        c.seek(SeekFrom::Start(loc)).unwrap();
        let mut buf = vec![0u8; len];
        c.read_exact(&mut buf).unwrap();
        assert_eq!(buf, b"hello world\n");
    }

    #[test]
    fn ext2_empty_root_ok() {
        // Build an image where the root directory has no children
        // (only "." and ".." entries).
        let mut img = make_ext2_image();
        // Overwrite the third directory entry (hello.txt) to be all-zeros
        // so inode = 0, which the scanner skips.
        let root_data_start = 6 * 1024 + 24; // offset of third entry
                                             // Just zero the inode field so the entry is skipped.
        img[root_data_start..root_data_start + 4].copy_from_slice(&0u32.to_le_bytes());
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("parse should succeed even with no children");
        assert_eq!(root.name, "/");
        assert!(root.is_directory);
    }

    #[test]
    fn ext2_large_file_no_crash() {
        // Inode with i_block[12] (single-indirect) non-zero but pointing
        // to block 0 (which will read as all zeros = no blocks). Should not
        // panic; just returns file_location = None.
        let mut img = make_ext2_image();
        // Modify hello.txt inode to claim size > 12 blocks.
        let inode_table_start = 5 * 1024;
        let file_inode_off = inode_table_start + (3 - 1) * 128; // inode #3 = index 2
                                                                // Set size to 1 MiB (many blocks needed).
        let new_size: u32 = 1024 * 1024;
        img[file_inode_off + 4..file_inode_off + 8].copy_from_slice(&new_size.to_le_bytes());
        // Set i_block[12] (single indirect) to block 8 (beyond our data).
        // Block 8 will read as zeros → all zero block pointers → no actual data.
        img[file_inode_off + 40 + 12 * 4..file_inode_off + 40 + 13 * 4]
            .copy_from_slice(&8u32.to_le_bytes());
        let mut c = cursor_of(&img);
        // Should parse without panic; file_location will be None.
        let root = detect_and_parse(&mut c).expect("parse should not crash");
        let file = root
            .children
            .iter()
            .find(|n| n.name == "hello.txt")
            .unwrap();
        assert_eq!(
            file.file_location, None,
            "large file has no single-run location"
        );
    }

    // ── Error Display / source ────────────────────────────────────────────────

    #[test]
    fn error_display_too_short() {
        let msg = format!("{}", Error::TooShort);
        assert!(
            msg.contains("short") || msg.contains("superblock"),
            "unexpected: {msg}"
        );
    }

    #[test]
    fn error_display_bad_superblock() {
        let msg = format!("{}", Error::BadSuperblock);
        assert!(
            msg.contains("superblock") || msg.contains("0xEF53"),
            "unexpected: {msg}"
        );
    }

    #[test]
    fn error_display_io() {
        let io = std::io::Error::other("disk fail");
        let msg = format!("{}", Error::Io(io));
        assert!(msg.contains("disk fail"), "unexpected: {msg}");
    }

    #[test]
    fn error_source_io() {
        use std::error::Error as StdError;
        let io = std::io::Error::other("src");
        assert!(Error::Io(io).source().is_some());
    }

    #[test]
    fn error_source_non_io() {
        use std::error::Error as StdError;
        assert!(Error::TooShort.source().is_none());
        assert!(Error::BadSuperblock.source().is_none());
    }

    // ── From<io::Error> ──────────────────────────────────────────────────────

    #[test]
    fn error_from_io_error() {
        let io = std::io::Error::other("disk");
        let err = Error::from(io);
        assert!(matches!(err, Error::Io(_)));
    }

    // ── Superblock::desc_size_effective with INCOMPAT_64BIT ──────────────────

    #[test]
    fn desc_size_effective_returns_desc_size_when_64bit() {
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 0,
            log_block_size: 2, // 4 KiB blocks
            inode_size: 256,
            feature_incompat: INCOMPAT_64BIT,
            desc_size: 64,
        };
        assert_eq!(sb.desc_size_effective(), 64);
    }

    // ── detect_and_parse error paths ─────────────────────────────────────────

    #[test]
    fn detect_and_parse_too_short_for_superblock() {
        // Magic at the right place, but image too short for read_superblock (264 bytes needed).
        let mut img = vec![0u8; 1100];
        img[1024 + 56..1024 + 58].copy_from_slice(&EXT_MAGIC.to_le_bytes());
        let mut c = Cursor::new(img);
        assert!(matches!(detect_and_parse(&mut c), Err(Error::TooShort)));
    }

    #[test]
    fn detect_and_parse_bad_superblock_magic() {
        let img = vec![0u8; 2048]; // enough bytes, magic = 0x0000 (wrong)
        let mut c = Cursor::new(img);
        assert!(matches!(
            detect_and_parse(&mut c),
            Err(Error::BadSuperblock)
        ));
    }

    // ── Inode::file_type_char ─────────────────────────────────────────────────

    #[test]
    fn inode_file_type_char_char_device() {
        // S_IFCHR = 0x2000; (0x2000 & S_IFMT) >> 12 = 2
        let inode = Inode {
            mode: 0x2000,
            size: 0,
            flags: 0,
            i_block: [0; 15],
        };
        assert_eq!(inode.file_type_char(), 2);
    }

    // ── read_inode with inode_num == 0 ────────────────────────────────────────

    #[test]
    fn read_inode_with_zero_num_returns_bad_superblock() {
        let img = make_ext2_image();
        let mut c = Cursor::new(img);
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let result = read_inode(&mut c, &sb, 0, 0);
        assert!(matches!(result, Err(Error::BadSuperblock)));
    }

    // ── Superblock sanity checks ──────────────────────────────────────────────

    fn make_corrupt_image<F: Fn(&mut Vec<u8>)>(corrupt: F) -> Vec<u8> {
        let mut img = make_ext2_image();
        corrupt(&mut img);
        img
    }

    #[test]
    fn rejects_log_block_size_too_large() {
        let img = make_corrupt_image(|img| {
            // s_log_block_size at offset 1024+24: set to 7 (would be 128 KiB).
            img[1024 + 24..1024 + 28].copy_from_slice(&7u32.to_le_bytes());
        });
        let mut c = cursor_of(&img);
        assert!(detect_and_parse(&mut c).is_err());
    }

    #[test]
    fn rejects_blocks_per_group_zero() {
        let img = make_corrupt_image(|img| {
            img[1024 + 32..1024 + 36].copy_from_slice(&0u32.to_le_bytes());
        });
        let mut c = cursor_of(&img);
        assert!(detect_and_parse(&mut c).is_err());
    }

    #[test]
    fn rejects_blocks_count_zero() {
        let img = make_corrupt_image(|img| {
            img[1024 + 4..1024 + 8].copy_from_slice(&0u32.to_le_bytes());
        });
        let mut c = cursor_of(&img);
        assert!(detect_and_parse(&mut c).is_err());
    }

    #[test]
    fn rejects_inodes_per_group_zero() {
        let img = make_corrupt_image(|img| {
            img[1024 + 40..1024 + 44].copy_from_slice(&0u32.to_le_bytes());
        });
        let mut c = cursor_of(&img);
        assert!(detect_and_parse(&mut c).is_err());
    }

    // ── Rev_level 0 path ──────────────────────────────────────────────────────

    #[test]
    fn rev_level_zero_uses_defaults() {
        // Set rev_level = 0; parser should use fixed 128-byte inodes, no extents.
        let mut img = make_ext2_image();
        img[1024 + 76..1024 + 80].copy_from_slice(&0u32.to_le_bytes());
        // Also zero the feature_incompat field to be safe.
        img[1024 + 96..1024 + 100].copy_from_slice(&0u32.to_le_bytes());
        let mut c = cursor_of(&img);
        // Should still parse OK; rev_level 0 just sets defaults.
        let root = detect_and_parse(&mut c).expect("rev_level 0 should still parse");
        assert_eq!(root.name, "/");
    }

    // ── Inode size > block_size rejects ───────────────────────────────────────

    #[test]
    fn rejects_inode_size_larger_than_block_size() {
        // inode_size = 4096, block_size = 1024 → invalid.
        let img = make_corrupt_image(|img| {
            img[1024 + 88..1024 + 90].copy_from_slice(&4096u16.to_le_bytes());
        });
        let mut c = cursor_of(&img);
        assert!(detect_and_parse(&mut c).is_err());
    }

    // ── Extent tree path ──────────────────────────────────────────────────────

    fn make_ext4_extent_image() -> Vec<u8> {
        // Like make_ext2_image but the file inode uses an extent tree.
        const BS: usize = 1024;
        const INODE_SIZE: usize = 128;
        const INODE_TABLE_BLK: usize = 5;
        const FILE_DATA_BLK: usize = 7;
        const FILE_INUM: usize = 3;

        let mut img = make_ext2_image(); // start from the classical image

        // Enable EXT4_EXTENTS_FL on the file inode (#3).
        let inode_base = INODE_TABLE_BLK * BS;
        let file_off = inode_base + (FILE_INUM - 1) * INODE_SIZE;
        // Set i_flags = EXT4_EXTENTS_FL (0x80000)
        img[file_off + 32..file_off + 36].copy_from_slice(&0x0008_0000u32.to_le_bytes());

        // Build an extent tree in i_block (60 bytes at file_off+40).
        // Header: magic=0xF30A, entries=1, max=4, depth=0, generation=0
        let extent_area = &mut img[file_off + 40..file_off + 100];
        extent_area[..2].copy_from_slice(&0xF30Au16.to_le_bytes()); // magic
        extent_area[2..4].copy_from_slice(&1u16.to_le_bytes()); // entries
        extent_area[4..6].copy_from_slice(&4u16.to_le_bytes()); // max
        extent_area[6..8].copy_from_slice(&0u16.to_le_bytes()); // depth = 0 (leaf)
        extent_area[8..12].copy_from_slice(&0u32.to_le_bytes()); // generation
                                                                 // Leaf extent at offset 12: ee_block=0, ee_len=1, ee_start_hi=0, ee_start_lo=FILE_DATA_BLK
        extent_area[12..16].copy_from_slice(&0u32.to_le_bytes()); // ee_block (logical)
        extent_area[16..18].copy_from_slice(&1u16.to_le_bytes()); // ee_len = 1 block
        extent_area[18..20].copy_from_slice(&0u16.to_le_bytes()); // ee_start_hi
        extent_area[20..24].copy_from_slice(&(FILE_DATA_BLK as u32).to_le_bytes()); // ee_start_lo

        img
    }

    #[test]
    fn parse_ext4_extent_tree_file() {
        let img = make_ext4_extent_image();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("extent tree parse failed");
        let file = root
            .children
            .iter()
            .find(|n| n.name == "hello.txt")
            .unwrap();
        assert_eq!(file.size, 12);
        // Single extent → file_location should be set.
        assert!(
            file.file_location.is_some(),
            "single-extent file should have file_location"
        );
    }

    // ── parse_extent_header with bad magic ───────────────────────────────────

    #[test]
    fn parse_extent_header_bad_magic_returns_none() {
        let mut data = vec![0u8; 60];
        data[0..2].copy_from_slice(&0xDEADu16.to_le_bytes()); // wrong magic
        assert!(parse_extent_header(&data).is_none());
    }

    #[test]
    fn parse_extent_header_too_short_returns_none() {
        let data = vec![0u8; 4]; // < 12 bytes required
        assert!(parse_extent_header(&data).is_none());
    }

    // ── Inline data (EXT4_INLINE_DATA_FL) ────────────────────────────────────

    #[test]
    fn inline_data_file_has_no_location() {
        let mut img = make_ext2_image();
        const INODE_TABLE_BLK: usize = 5;
        const BS: usize = 1024;
        const INODE_SIZE: usize = 128;
        const FILE_INUM: usize = 3;
        let file_off = INODE_TABLE_BLK * BS + (FILE_INUM - 1) * INODE_SIZE;
        // Set EXT4_INLINE_DATA_FL (bit 28) in i_flags.
        let flags: u32 = 0x1000_0000;
        img[file_off + 32..file_off + 36].copy_from_slice(&flags.to_le_bytes());
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("inline data parse failed");
        let file = root
            .children
            .iter()
            .find(|n| n.name == "hello.txt")
            .unwrap();
        assert!(
            file.file_location.is_none(),
            "inline-data file should have no file_location"
        );
    }

    // ── Symlink inode in tree ────────────────────────────────────────────────

    fn make_ext2_with_symlink() -> Vec<u8> {
        // Extend the base image: add a symlink inode (#4) to the root dir.
        const BS: usize = 1024;
        const INODE_TABLE_BLK: usize = 5;
        const INODE_SIZE: usize = 128;
        const ROOT_DATA_BLK: usize = 6;
        const SYMLINK_INUM: usize = 4;

        let mut img = make_ext2_image();

        // Set up symlink inode #4 at index 3 in the inode table.
        let symlink_off = INODE_TABLE_BLK * BS + (SYMLINK_INUM - 1) * INODE_SIZE;
        let mode: u16 = S_IFLNK | 0o777;
        img[symlink_off..symlink_off + 2].copy_from_slice(&mode.to_le_bytes());
        img[symlink_off + 4..symlink_off + 8].copy_from_slice(&7u32.to_le_bytes()); // size=7 "foo/bar"

        // Add a new directory entry for "link" → inode 4.
        // We'll insert it after the existing entries in the root data block.
        // Existing entries end at offset 24+9=33, rounded up to 36.
        // We need to shrink the last entry's rec_len to make room.
        let dir_base = ROOT_DATA_BLK * BS;
        // The last entry (hello.txt at offset 24) currently spans to end of block.
        // Resize it to fit exactly: name_len=9 → rec_len=20 (8 header + 9 name + 3 pad).
        let new_rec_len: u16 = 20;
        img[dir_base + 24 + 4..dir_base + 24 + 6].copy_from_slice(&new_rec_len.to_le_bytes());

        // New entry at offset 44: "link" → inode 4.
        let e_off = 44;
        let e_rec: u16 = (BS - e_off) as u16;
        img[dir_base + e_off..dir_base + e_off + 4]
            .copy_from_slice(&(SYMLINK_INUM as u32).to_le_bytes());
        img[dir_base + e_off + 4..dir_base + e_off + 6].copy_from_slice(&e_rec.to_le_bytes());
        img[dir_base + e_off + 6] = 4; // name_len = "link"
        img[dir_base + e_off + 7] = 7; // file_type = symlink
        img[dir_base + e_off + 8..dir_base + e_off + 12].copy_from_slice(b"link");

        img
    }

    #[test]
    fn symlink_appears_in_tree() {
        let img = make_ext2_with_symlink();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("symlink image parse failed");
        let link = root.find_node("/link");
        assert!(link.is_some(), "symlink should appear in the tree");
        let link = link.unwrap();
        assert!(!link.is_directory);
        // Symlinks don't get file_location.
        assert!(link.file_location.is_none());
    }

    // ── Non-contiguous blocks → no file_location ─────────────────────────────

    #[test]
    fn discontiguous_blocks_no_file_location() {
        let mut img = make_ext2_image();
        const INODE_TABLE_BLK: usize = 5;
        const BS: usize = 1024;
        const INODE_SIZE: usize = 128;
        const FILE_INUM: usize = 3;
        let file_off = INODE_TABLE_BLK * BS + (FILE_INUM - 1) * INODE_SIZE;
        // Make file large enough to need 2 blocks, but make them non-contiguous.
        img[file_off + 4..file_off + 8].copy_from_slice(&(2048u32).to_le_bytes()); // 2 KB
                                                                                   // i_block[0] = 7 (existing), i_block[1] = 9 (skipping 8 → discontiguous).
        img[file_off + 44..file_off + 48].copy_from_slice(&9u32.to_le_bytes()); // i_block[1] = 9
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("parse failed");
        let file = root
            .children
            .iter()
            .find(|n| n.name == "hello.txt")
            .unwrap();
        assert!(
            file.file_location.is_none(),
            "discontiguous blocks should yield no file_location"
        );
    }

    // ── read_bgd with 64-bit descriptor ──────────────────────────────────────

    #[test]
    fn read_bgd_uses_64bit_inode_table_hi() {
        // Superblock with INCOMPAT_64BIT and desc_size=64, 1KB blocks.
        // bgd_table_offset = base_offset + (first_data_block + 1) * block_size
        //                  = 0 + 2 * 1024 = 2048.
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_64BIT,
            desc_size: 64,
        };
        // Image must be at least 2048 + 64 bytes.
        let mut img = vec![0u8; 3072];
        // Write the BGD at offset 2048:
        //   inode_table_lo at bytes 8..12 → 5
        //   inode_table_hi at bytes 40..44 → 2
        img[2048 + 8..2048 + 12].copy_from_slice(&5u32.to_le_bytes());
        img[2048 + 40..2048 + 44].copy_from_slice(&2u32.to_le_bytes());
        let mut c = Cursor::new(img);
        let bgd = read_bgd(&mut c, &sb, 0, 0).expect("read_bgd should succeed");
        // inode_table = (2 << 32) | 5 = 8589934597
        assert_eq!(bgd.inode_table, (2u64 << 32) | 5u64);
    }

    // ── parse_idx_entries ─────────────────────────────────────────────────────

    #[test]
    fn parse_idx_entries_one_entry() {
        // Build a buffer with one index entry at offset 12.
        // Bytes 16..20 = leaf_lo = 7, bytes 20..22 = leaf_hi = 0.
        let mut data = vec![0u8; 24];
        // Header (bytes 0..12): magic + counts etc. — content ignored by this function.
        data[16..20].copy_from_slice(&7u32.to_le_bytes()); // leaf_lo
        data[20..22].copy_from_slice(&0u16.to_le_bytes()); // leaf_hi
        let entries = parse_idx_entries(&data, 1);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].leaf, 7);
    }

    #[test]
    fn parse_idx_entries_overflow_breaks() {
        // entries = 2 but buffer only has room for 1 → the second iteration
        // hits `off + 12 > data.len()` and breaks.
        let data = vec![0u8; 24]; // room for exactly one 12-byte entry at offset 12
        let entries = parse_idx_entries(&data, 2);
        assert_eq!(entries.len(), 1);
    }

    // ── collect_extents with internal node (depth > 0) ────────────────────────

    #[test]
    fn collect_extents_follows_internal_node_to_leaf() {
        // Build a two-level extent tree in memory.
        //
        // Root node (i_block area, 60 bytes): depth=1, 1 index entry → child at block 3.
        // Child block (block 3, offset 3*1024=3072): depth=0, 1 leaf entry → phys block 10.
        //
        // We need an image of at least 3072 + 1024 = 4096 bytes.
        const BS: usize = 1024;
        let mut img = vec![0u8; 5 * BS];

        let em = EXTENT_MAGIC.to_le_bytes();

        // Root node (60 bytes; only first 24 are relevant here).
        let mut root = vec![0u8; 60];
        root[0..2].copy_from_slice(&em); // magic
        root[2..4].copy_from_slice(&1u16.to_le_bytes()); // entries = 1
        root[4..6].copy_from_slice(&4u16.to_le_bytes()); // max = 4
        root[6..8].copy_from_slice(&1u16.to_le_bytes()); // depth = 1 (internal)
                                                         // Index entry at bytes 12..24:
                                                         //   ei_block at [12..16] = 0
                                                         //   ei_leaf_lo at [16..20] = 3 (child is at block 3)
                                                         //   ei_leaf_hi at [20..22] = 0
        root[16..20].copy_from_slice(&3u32.to_le_bytes());

        // Child block at offset 3 * BS = 3072:
        img[3 * BS..3 * BS + 2].copy_from_slice(&em);
        img[3 * BS + 2..3 * BS + 4].copy_from_slice(&1u16.to_le_bytes()); // entries = 1
        img[3 * BS + 4..3 * BS + 6].copy_from_slice(&4u16.to_le_bytes()); // max = 4
        img[3 * BS + 6..3 * BS + 8].copy_from_slice(&0u16.to_le_bytes()); // depth = 0 (leaf)
                                                                          // Leaf entry at bytes 12..24:
                                                                          //   ee_block at [12..16] = 0
                                                                          //   ee_len at [16..18] = 1 (1 block, not unwritten)
                                                                          //   ee_start_hi at [18..20] = 0
                                                                          //   ee_start_lo at [20..24] = 10
        img[3 * BS + 16..3 * BS + 18].copy_from_slice(&1u16.to_le_bytes()); // ee_len = 1
        img[3 * BS + 20..3 * BS + 24].copy_from_slice(&10u32.to_le_bytes()); // phys = 10

        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let mut c = Cursor::new(img);
        let extents = collect_extents(&mut c, &sb, 0, &root, 5).expect("collect_extents");
        assert_eq!(extents.len(), 1);
        assert_eq!(extents[0].phys, 10);
        assert_eq!(extents[0].len, 1);
        assert!(!extents[0].unwritten);
    }

    // ── single_run_location edge cases ────────────────────────────────────────

    #[test]
    fn single_run_location_returns_none_for_empty_inode() {
        let inode = Inode {
            mode: S_IFREG,
            size: 0,
            flags: 0,
            i_block: [0; 15],
        };
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: 0,
            desc_size: 32,
        };
        let mut c = Cursor::new(vec![0u8; 0]);
        let loc = single_run_location(&mut c, &sb, 0, &inode).unwrap();
        assert!(loc.is_none());
    }

    #[test]
    fn single_run_location_returns_none_for_inline_inode() {
        let inode = Inode {
            mode: S_IFREG,
            size: 10,
            flags: EXT4_INLINE_DATA_FL,
            i_block: [0; 15],
        };
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: 0,
            desc_size: 32,
        };
        let mut c = Cursor::new(vec![0u8; 0]);
        let loc = single_run_location(&mut c, &sb, 0, &inode).unwrap();
        assert!(loc.is_none());
    }

    #[test]
    fn single_run_location_extent_unwritten_returns_none() {
        // Build an inode with EXT4_EXTENTS_FL and a single UNWRITTEN extent.
        // single_run_location should return None because unwritten extents
        // contain stale on-disk data.
        let em = EXTENT_MAGIC.to_le_bytes();
        let mut i_block_bytes = [0u8; 60];
        i_block_bytes[0..2].copy_from_slice(&em); // magic
        i_block_bytes[2..4].copy_from_slice(&1u16.to_le_bytes()); // entries = 1
        i_block_bytes[4..6].copy_from_slice(&4u16.to_le_bytes()); // max
        i_block_bytes[6..8].copy_from_slice(&0u16.to_le_bytes()); // depth = 0 (leaf)
                                                                  // Leaf entry: ee_len = 0x8001 (unwritten flag in high bit + len=1)
        i_block_bytes[16..18].copy_from_slice(&0x8001u16.to_le_bytes()); // unwritten
        i_block_bytes[20..24].copy_from_slice(&5u32.to_le_bytes()); // phys = 5

        // Convert bytes to i_block [u32; 15].
        let mut i_block = [0u32; 15];
        for (i, slot) in i_block.iter_mut().enumerate() {
            let off = i * 4;
            *slot = u32::from_le_bytes(i_block_bytes[off..off + 4].try_into().unwrap());
        }

        let inode = Inode {
            mode: S_IFREG,
            size: 1024,
            flags: EXT4_EXTENTS_FL,
            i_block,
        };
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let mut c = Cursor::new(vec![0u8; 0]);
        let loc = single_run_location(&mut c, &sb, 0, &inode).unwrap();
        assert!(loc.is_none(), "unwritten extent should yield no location");
    }

    #[test]
    fn collect_extents_bad_magic_returns_empty() {
        // node_data with bad magic → parse_extent_header returns None → empty vec.
        let data = vec![0u8; 60]; // all zeros, magic = 0x0000 ≠ EXTENT_MAGIC
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: 0,
            desc_size: 32,
        };
        let mut c = Cursor::new(vec![0u8; 0]);
        let extents = collect_extents(&mut c, &sb, 0, &data, 5).unwrap();
        assert!(extents.is_empty());
    }

    #[test]
    fn collect_extents_remaining_depth_zero_returns_empty() {
        // A node with depth=1 (internal) but remaining_depth=0 → safety cap, returns empty.
        let em = EXTENT_MAGIC.to_le_bytes();
        let mut data = vec![0u8; 60];
        data[0..2].copy_from_slice(&em); // magic
        data[2..4].copy_from_slice(&1u16.to_le_bytes()); // entries = 1
        data[6..8].copy_from_slice(&1u16.to_le_bytes()); // depth = 1 (internal)

        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: 0,
            desc_size: 32,
        };
        let mut c = Cursor::new(vec![0u8; 0]);
        let extents = collect_extents(&mut c, &sb, 0, &data, 0).unwrap();
        assert!(extents.is_empty());
    }

    #[test]
    fn parse_leaf_extents_overflow_breaks() {
        // entries=3 but data only has room for 2 entries after the header (36 bytes).
        // Third iteration: off = 12 + 2*12 = 36, off+12 = 48 > 36 → break.
        let mut data = vec![0u8; 36]; // header (12) + 2 entries (24) = 36 bytes
                                      // Fill the two valid entries.
        data[16..18].copy_from_slice(&1u16.to_le_bytes()); // ee_len for entry 0
        data[28..30].copy_from_slice(&1u16.to_le_bytes()); // ee_len for entry 1
        let extents = parse_leaf_extents(&data, 3);
        assert_eq!(extents.len(), 2, "should stop at 2 due to buffer overflow");
    }

    // ── read_ptr_block + single-indirect directory ────────────────────────────

    /// Make an ext2 image where the root directory's data is reached via a
    /// single-indirect block pointer (i_block[12]) rather than a direct pointer.
    /// Layout (1 KiB blocks):
    ///   0: boot  1: superblock  2: BGD  3: block-bitmap  4: inode-bitmap
    ///   5: inode-table  6: dir data  7: file data  8: SI pointer block
    fn make_ext2_single_indirect_dir() -> Vec<u8> {
        const BS: usize = 1024;
        const INODE_SIZE: usize = 128;
        const INODES_PER_GROUP: usize = 256;
        const TOTAL_BLOCKS: usize = 256;
        const INODE_TABLE_BLK: usize = 5;
        const DIR_DATA_BLK: usize = 6;
        const FILE_DATA_BLK: usize = 7;
        const SI_BLK: usize = 8; // single-indirect pointer block
        const ROOT_INUM: usize = 2;
        const FILE_INUM: usize = 3;

        let mut img = vec![0u8; (TOTAL_BLOCKS + 4) * BS];

        // Superblock at block 1.
        {
            let sb = &mut img[BS..BS + 264];
            sb[0..4].copy_from_slice(&(INODES_PER_GROUP as u32).to_le_bytes());
            sb[4..8].copy_from_slice(&(TOTAL_BLOCKS as u32).to_le_bytes());
            sb[20..24].copy_from_slice(&1u32.to_le_bytes()); // s_first_data_block=1
            sb[24..28].copy_from_slice(&0u32.to_le_bytes()); // log_block_size=0 → 1 KiB
            sb[32..36].copy_from_slice(&(TOTAL_BLOCKS as u32).to_le_bytes());
            sb[40..44].copy_from_slice(&(INODES_PER_GROUP as u32).to_le_bytes());
            sb[56..58].copy_from_slice(&EXT_MAGIC.to_le_bytes());
            sb[76..80].copy_from_slice(&1u32.to_le_bytes()); // rev_level=1
            sb[84..88].copy_from_slice(&11u32.to_le_bytes()); // first_ino=11
            sb[88..90].copy_from_slice(&(INODE_SIZE as u16).to_le_bytes());
            sb[96..100].copy_from_slice(&INCOMPAT_FILETYPE.to_le_bytes());
            sb[236..238].copy_from_slice(&32u16.to_le_bytes()); // desc_size=32
        }

        // BGD at block 2.
        {
            let bgd = &mut img[2 * BS..2 * BS + 32];
            bgd[0..4].copy_from_slice(&3u32.to_le_bytes()); // block_bitmap
            bgd[4..8].copy_from_slice(&4u32.to_le_bytes()); // inode_bitmap
            bgd[8..12].copy_from_slice(&(INODE_TABLE_BLK as u32).to_le_bytes());
        }

        // Root dir inode (#2): i_block[0]=0 (no direct block), i_block[12]=SI_BLK.
        {
            let off = INODE_TABLE_BLK * BS + (ROOT_INUM - 1) * INODE_SIZE;
            let ino = &mut img[off..off + INODE_SIZE];
            ino[0..2].copy_from_slice(&(S_IFDIR | 0o755).to_le_bytes());
            ino[4..8].copy_from_slice(&(BS as u32).to_le_bytes()); // size=1024
            ino[26..28].copy_from_slice(&2u16.to_le_bytes());
            ino[32..36].copy_from_slice(&0u32.to_le_bytes()); // no extents
                                                              // i_block[0..12] = 0 (no direct blocks)
                                                              // i_block[12] = SI_BLK (single-indirect pointer block)
            let si_offset = 40 + 12 * 4;
            ino[si_offset..si_offset + 4].copy_from_slice(&(SI_BLK as u32).to_le_bytes());
        }

        // File inode (#3).
        {
            let off = INODE_TABLE_BLK * BS + (FILE_INUM - 1) * INODE_SIZE;
            let ino = &mut img[off..off + INODE_SIZE];
            ino[0..2].copy_from_slice(&(S_IFREG | 0o644).to_le_bytes());
            ino[4..8].copy_from_slice(&12u32.to_le_bytes());
            ino[26..28].copy_from_slice(&1u16.to_le_bytes());
            ino[40..44].copy_from_slice(&(FILE_DATA_BLK as u32).to_le_bytes());
        }

        // Single-indirect pointer block: first pointer = DIR_DATA_BLK.
        {
            let off = SI_BLK * BS;
            img[off..off + 4].copy_from_slice(&(DIR_DATA_BLK as u32).to_le_bytes());
        }

        // Directory data block: ".", "..", "hello.txt".
        {
            let d = &mut img[DIR_DATA_BLK * BS..DIR_DATA_BLK * BS + BS];
            // "."
            d[0..4].copy_from_slice(&(ROOT_INUM as u32).to_le_bytes());
            d[4..6].copy_from_slice(&12u16.to_le_bytes());
            d[6] = 1;
            d[7] = 2;
            d[8] = b'.';
            // ".."
            d[12..16].copy_from_slice(&(ROOT_INUM as u32).to_le_bytes());
            d[16..18].copy_from_slice(&12u16.to_le_bytes());
            d[18] = 2;
            d[19] = 2;
            d[20] = b'.';
            d[21] = b'.';
            // "hello.txt"
            let name = b"hello.txt";
            d[24..28].copy_from_slice(&(FILE_INUM as u32).to_le_bytes());
            d[28..30].copy_from_slice(&((BS - 24) as u16).to_le_bytes());
            d[30] = name.len() as u8;
            d[31] = 1; // file_type=regular
            d[32..32 + name.len()].copy_from_slice(name);
        }

        // File data block.
        img[FILE_DATA_BLK * BS..FILE_DATA_BLK * BS + 12].copy_from_slice(b"hello world\n");

        img
    }

    #[test]
    fn single_indirect_dir_parsed_correctly() {
        // Root directory uses i_block[12] (single-indirect) → exercises read_ptr_block
        // and the SI branch of collect_classical_blocks (lines 469-483, 518-525).
        let img = make_ext2_single_indirect_dir();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("SI dir image should parse");
        assert_eq!(root.name, "/");
        let child = root.children.iter().find(|n| n.name == "hello.txt");
        assert!(child.is_some(), "hello.txt should appear via SI dir");
    }

    // ── Extent-based directory reading (read_dir_entries extent path) ─────────

    fn make_ext4_extent_dir() -> Vec<u8> {
        // Root dir inode has EXT4_EXTENTS_FL; its extent tree points to DIR_DATA_BLK.
        const BS: usize = 1024;
        let mut img = make_ext2_single_indirect_dir();
        const INODE_SIZE: usize = 128;
        const INODE_TABLE_BLK: usize = 5;
        const ROOT_INUM: usize = 2;
        const DIR_DATA_BLK: usize = 6;

        let off = INODE_TABLE_BLK * BS + (ROOT_INUM - 1) * INODE_SIZE;
        // Set EXT4_EXTENTS_FL on root inode.
        img[off + 32..off + 36].copy_from_slice(&EXT4_EXTENTS_FL.to_le_bytes());
        // Clear all i_block bytes, then write extent tree.
        img[off + 40..off + 100].fill(0);
        let ea = &mut img[off + 40..off + 100];
        ea[0..2].copy_from_slice(&EXTENT_MAGIC.to_le_bytes());
        ea[2..4].copy_from_slice(&1u16.to_le_bytes()); // entries=1
        ea[4..6].copy_from_slice(&4u16.to_le_bytes()); // max=4
        ea[6..8].copy_from_slice(&0u16.to_le_bytes()); // depth=0 (leaf)
                                                       // Leaf extent at offset 12: ee_block=0, ee_len=1, phys=DIR_DATA_BLK.
        ea[12..16].copy_from_slice(&0u32.to_le_bytes());
        ea[16..18].copy_from_slice(&1u16.to_le_bytes()); // ee_len=1
        ea[18..20].copy_from_slice(&0u16.to_le_bytes()); // ee_start_hi
        ea[20..24].copy_from_slice(&(DIR_DATA_BLK as u32).to_le_bytes());
        img
    }

    #[test]
    fn extent_dir_read_entries_extent_path() {
        // Root directory uses EXT4_EXTENTS_FL → read_dir_entries takes extent
        // branch (lines 631-640) to reach directory data.
        let img = make_ext4_extent_dir();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("extent dir image should parse");
        assert_eq!(root.name, "/");
        let child = root.children.iter().find(|n| n.name == "hello.txt");
        assert!(child.is_some(), "hello.txt should appear via extent dir");
    }

    // ── scan_dir_block: bad rec_len triggers break ────────────────────────────

    #[test]
    fn scan_dir_block_bad_rec_len_breaks() {
        // Entry at offset 0 has rec_len=4 < 8 → break immediately (line 603).
        let mut data = vec![0u8; 64];
        data[0..4].copy_from_slice(&2u32.to_le_bytes()); // inode=2 (non-zero)
        data[4..6].copy_from_slice(&4u16.to_le_bytes()); // rec_len=4 < 8 → break
        data[6] = 1; // name_len
        let mut entries: Vec<DirEntry> = Vec::new();
        scan_dir_block(&data, false, &mut entries);
        assert!(entries.is_empty(), "bad rec_len should break immediately");
    }

    // ── single_run_location: first block zero → None ──────────────────────────

    #[test]
    fn single_run_location_first_block_zero_returns_none() {
        // Regular file with size=12 but i_block[0]=0 → first=0 → Ok(None) (line 709).
        let inode = Inode {
            mode: S_IFREG | 0o644,
            size: 12,
            flags: 0,
            i_block: [0; 15], // all zero → first=i_block[0]=0
        };
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let mut c = Cursor::new(vec![0u8; 0]);
        let loc = single_run_location(&mut c, &sb, 0, &inode).unwrap();
        assert!(loc.is_none(), "zero first block → no location");
    }

    // ── build_tree: block-device inode is skipped ─────────────────────────────

    #[test]
    fn block_device_inode_skipped_in_tree() {
        // Add a block-device inode (#4) to the root directory; build_tree returns
        // None for it (lines 767-768: else branch of is_dir/is_reg/is_symlink).
        const BS: usize = 1024;
        const INODE_SIZE: usize = 128;
        const INODE_TABLE_BLK: usize = 5;
        const ROOT_DATA_BLK: usize = 6;
        const DEVNODE_INUM: usize = 4;

        let mut img = make_ext2_image();

        // Device inode (#4): S_IFBLK = 0x6000.
        let dev_off = INODE_TABLE_BLK * BS + (DEVNODE_INUM - 1) * INODE_SIZE;
        img[dev_off..dev_off + 2].copy_from_slice(&0x6000u16.to_le_bytes()); // S_IFBLK
        img[dev_off + 26..dev_off + 28].copy_from_slice(&1u16.to_le_bytes());

        // Add "devnode" entry to root directory.
        // Existing layout: "."(12) + ".."(12) + "hello.txt"(fills to 1024).
        // Shrink hello.txt rec_len to fit, then add devnode after it.
        let dir = ROOT_DATA_BLK * BS;
        img[dir + 24 + 4..dir + 24 + 6].copy_from_slice(&20u16.to_le_bytes()); // shrink
        let e_off = 44;
        img[dir + e_off..dir + e_off + 4].copy_from_slice(&(DEVNODE_INUM as u32).to_le_bytes());
        img[dir + e_off + 4..dir + e_off + 6].copy_from_slice(&((BS - e_off) as u16).to_le_bytes());
        img[dir + e_off + 6] = 7; // name_len = "devnode"
        img[dir + e_off + 7] = 6; // file_type = block device
        img[dir + e_off + 8..dir + e_off + 15].copy_from_slice(b"devnode");

        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("image with device inode should parse");
        // Device inode is silently skipped → should not appear in tree.
        assert!(
            root.find_node("/devnode").is_none(),
            "device inode should be skipped"
        );
        // Regular file is still present.
        assert!(root.find_node("/hello.txt").is_some());
    }

    // ── collect_classical_blocks: SI covered-before-si early return ──────────

    #[test]
    fn classical_blocks_si_covered_before_use() {
        // If covered >= size after the direct block loop, returns before reaching SI.
        // The direct block loop covers exactly `size` bytes → line 511 returns.
        // Use the regular ext2 image: root dir has size=1024, i_block[0]=6 → 1 direct
        // block covers all 1024 bytes → collect_classical_blocks returns at line 511.
        // This is the existing make_ext2_image path; SI is never reached for the root.
        let img = make_ext2_image();
        let mut c = cursor_of(&img);
        let root = detect_and_parse(&mut c).expect("parse");
        assert!(root.find_node("/hello.txt").is_some());
    }

    // ── collect_classical_blocks: double-indirect path ────────────────────────

    #[test]
    fn classical_blocks_double_indirect() {
        // Direct call to collect_classical_blocks exercising the DI path
        // (lines 532-549, 551-553).
        // Setup (20 KiB image with 1 KiB blocks):
        //   blocks 1-12: direct data (12 KB → covered=12288)
        //   block 13: SI pointer block — all zeros → SI adds nothing, covered stays 12288
        //   block 14: DI-L1 pointer block → first ptr = block 15
        //   block 15: DI-L2 pointer block → first ptr = block 16
        //   block 16: the 13th data block
        // size = 12289 (one byte past the 12 direct blocks) → DI is needed.
        const BS: usize = 1024;
        let mut img = vec![0u8; 20 * BS];
        // DI-L1 block at 14: pointer to block 15.
        img[14 * BS..14 * BS + 4].copy_from_slice(&15u32.to_le_bytes());
        // DI-L2 block at 15: pointer to block 16.
        img[15 * BS..15 * BS + 4].copy_from_slice(&16u32.to_le_bytes());

        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0, // 1 KiB blocks
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let mut i_block = [0u32; 15];
        for (i, b) in i_block[0..12].iter_mut().enumerate() {
            *b = (i + 1) as u32; // direct blocks 1..12
        }
        i_block[12] = 13; // SI block (all zeros → no extra blocks)
        i_block[13] = 14; // DI-L1 block
        let inode = Inode {
            mode: S_IFREG,
            size: 12289,
            flags: 0,
            i_block,
        };

        let mut c = Cursor::new(img);
        let blocks = collect_classical_blocks(&mut c, &sb, 0, &inode, 12289).unwrap();
        // Should have 12 direct + 1 DI block = 13 total.
        assert_eq!(blocks.len(), 13);
        assert_eq!(blocks[0], 1);
        assert_eq!(blocks[12], 16); // DI-resolved block
    }

    // ── collect_classical_blocks: triple-indirect path ────────────────────────

    #[test]
    fn classical_blocks_triple_indirect() {
        // Direct call to collect_classical_blocks exercising the TI path
        // (lines 555-578, 580).
        // Setup (25 KiB image with 1 KiB blocks):
        //   blocks 1-12: direct (SI=0, DI-L1 all zeros → DI adds nothing)
        //   block 17: TI-L1 → first ptr = block 18
        //   block 18: TI-L2 → first ptr = block 19
        //   block 19: TI-L3 → first ptr = block 20 (the data block)
        // size = 12289 so TI is reached after direct (12288) + no SI/DI contribution.
        const BS: usize = 1024;
        let mut img = vec![0u8; 25 * BS];
        // TI-L1 at 17: ptr = 18.
        img[17 * BS..17 * BS + 4].copy_from_slice(&18u32.to_le_bytes());
        // TI-L2 at 18: ptr = 19.
        img[18 * BS..18 * BS + 4].copy_from_slice(&19u32.to_le_bytes());
        // TI-L3 at 19: ptr = 20.
        img[19 * BS..19 * BS + 4].copy_from_slice(&20u32.to_le_bytes());

        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let mut i_block = [0u32; 15];
        for (i, b) in i_block[0..12].iter_mut().enumerate() {
            *b = (i + 1) as u32; // direct blocks 1..12
        }
        // SI=0, DI=0 → neither adds blocks; proceeds to TI.
        i_block[14] = 17; // TI-L1 block
        let inode = Inode {
            mode: S_IFREG,
            size: 12289,
            flags: 0,
            i_block,
        };

        let mut c = Cursor::new(img);
        let blocks = collect_classical_blocks(&mut c, &sb, 0, &inode, 12289).unwrap();
        // Should have 12 direct + 1 TI block = 13 total.
        assert_eq!(blocks.len(), 13);
        assert_eq!(blocks[12], 20); // TI-resolved block
    }

    // ── build_tree: depth > MAX_DEPTH returns None ────────────────────────────

    #[test]
    fn build_tree_exceeds_max_depth_returns_none() {
        // build_tree with depth=MAX_DEPTH+1 → immediately returns Ok(None) (line 732).
        let img = make_ext2_image();
        let sb = Superblock {
            inodes_per_group: 256,
            first_data_block: 1,
            log_block_size: 0,
            inode_size: 128,
            feature_incompat: INCOMPAT_FILETYPE,
            desc_size: 32,
        };
        let mut c = cursor_of(&img);
        let result = build_tree(&mut c, &sb, 0, "deep".to_string(), 2, MAX_DEPTH + 1);
        assert!(
            result.unwrap().is_none(),
            "depth > MAX_DEPTH should return None"
        );
    }
}