ferrosys 0.8.0

Pure-Rust filesystem formatter and reader: ext4, ext3, ext2, FAT32, FAT16, FAT12, exFAT, btrfs, and APFS — rootless, in userspace, byte-reproducible
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
//! The inode model: a pure, geometry-independent transform from a source's entries
//! into the inode tree the materializer writes.
//!
//! This module decides everything about *what* inodes exist, independent of *where*
//! their blocks land: it assigns inode numbers deterministically in sorted path
//! order, coalesces hard links onto one inode with the right link count, builds each
//! directory's `.`/`..` entries and the parent link accounting they imply, and
//! chooses the fast (inline) or slow (in-block) form for each symlink by its target
//! length. It performs no I/O and never touches a [`Layout`](crate::geometry::Layout).
//!
//! The root directory (inode 2) and `/lost+found` (inode 11) always exist; user
//! entries take inode 11's successors. A source entry whose path names the root
//! supplies the root directory's own mode, ownership, times, and extended attributes;
//! without one the root keeps its `0755` root-owned defaults. An input this profile
//! cannot represent is a typed [`ModelError`], never a dropped or truncated entry.

use std::collections::{BTreeMap, HashMap};

use crate::acl::Acl;
use crate::feature::{FeatureSet, LARGE_FILE_MIN_SIZE};
use crate::ondisk::{
    FileType, Inode, has_empty_name, longest_stored_name, split_for_storage, xattr_block_len,
};
use crate::path::canonical_parts;
use crate::source::{
    Darwin, EntryKind, FileContent, MODE_TYPE_MASK, Metadata, Source, SourceEntry,
};
use crate::time::Timestamp;
use crate::xattr::Xattr;

/// The widest device major number the on-disk encoding represents (12 bits).
const MAX_DEVICE_MAJOR: u32 = (1 << 12) - 1;
/// The widest device minor number the on-disk encoding represents (20 bits).
const MAX_DEVICE_MINOR: u32 = (1 << 20) - 1;

/// The root directory's inode number.
pub const ROOT_INO: u32 = 2;
/// The `/lost+found` inode number, the first non-reserved inode.
pub const LOST_FOUND_INO: u32 = 11;
/// The lowest inode number a user entry can take: the first past `/lost+found`. A
/// feature that claims an inode of its own at format time — the orphan file does —
/// takes it from here, and [`ModelConfig::first_user_inode`] moves the entries up
/// accordingly.
pub const FIRST_USER_INO: u32 = 12;

/// The size of the inode's inline block area. A symlink target shorter than this is
/// stored inline (a fast symlink), so the longest inline target is one byte less; a
/// target of this length or more is written to a data block.
const FAST_SYMLINK_MAX: usize = 60;

/// The most links an inode's `i_links_count` records: ext4 allows an inode no more than
/// 65,000 hard links, so a directory no more than 64,998 subdirectories unless `dir_nlink`
/// lets it store `1` instead, meaning the count is not known (the ext4 documentation's Index
/// Nodes page, `i_links_count`).
const MAX_LINKS: u16 = 65000;

/// Refuse an entry carrying BSD flags, which ext holds none of.
fn validate_darwin(path: &[u8], darwin: Option<&Darwin>) -> Result<(), ModelError> {
    match darwin.map(Darwin::stated_flags) {
        Some(flags) if flags != 0 => Err(ModelError::BsdFlagsNotHeld {
            path: path.to_vec(),
            flags,
        }),
        _ => Ok(()),
    }
}

/// Refuse a stated mode that carries file-type bits.
///
/// The entry's kind supplies them, and a mode arriving with its own — a raw `st_mode`
/// passed through whole is the natural way — would put a second type on the inode, which
/// the write would accept and every checker and driver would read as corruption. Every
/// other unrepresentable input here is a typed refusal, and so is this.
fn validate_mode(path: &[u8], mode: u16) -> Result<(), ModelError> {
    if mode & MODE_TYPE_MASK != 0 {
        return Err(ModelError::ModeCarriesFileType {
            path: path.to_vec(),
            mode,
        });
    }
    Ok(())
}

/// An input the model cannot represent.
///
/// A path in a message is rendered rather than repeated: an ext4 path is a byte string,
/// which need not be UTF-8 and may hold anything a terminal acts on. A message naming the
/// offending path is worth far more than one that refuses to guess at a byte, so an
/// unrepresentable byte becomes U+FFFD and the path stays recognizable — and anything a
/// terminal would act on becomes a visible escape rather than an instruction.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ModelError {
    /// A file declared by its length alone, whose bytes the source does not hold.
    ///
    /// This family's writer reads every file's bytes itself as it places them, so a file with
    /// none to read is refused when the plan is made rather than part of the way through
    /// writing the image.
    #[error(
        "{}: its contents are declared by length alone, and this writer reads a file's bytes \
         itself",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    ContentsNotHeld {
        /// The file's path.
        path: Vec<u8>,
    },
    /// A path resolved to the root where a name was required — a hard link cannot
    /// target the root directory.
    #[error("path is empty or names the root, where a name is required")]
    EmptyPath,
    /// An entry carries a `system.posix_acl_*` attribute whose value is not a POSIX ACL.
    ///
    /// The value is refused rather than stored: written through as opaque bytes it would be
    /// an attribute the kernel reads as an ACL and cannot parse, which is a filesystem that
    /// grants access nobody described.
    #[error(
        "entry {} has an invalid ACL: {source}",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    Acl {
        /// The offending path.
        path: Vec<u8>,
        /// The underlying ACL error.
        #[source]
        source: crate::acl::AclError,
    },
    /// An entry naming the root is not a directory. The root is a directory, so an
    /// entry that would place anything else there is rejected rather than applying its
    /// metadata to a directory it does not describe.
    #[error("entry {} names the root but is not a directory", crate::escape::printable(.path))]
    #[non_exhaustive]
    RootNotDirectory {
        /// The offending path.
        path: Vec<u8>,
    },
    /// The configured first user inode names an inode the filesystem reserves, so the
    /// entries would overwrite the root, `/lost+found`, or another reserved inode.
    #[error("the first user inode {given} is below {floor}, the first non-reserved inode")]
    #[non_exhaustive]
    FirstUserInodeReserved {
        /// The configured value.
        given: u32,
        /// The lowest inode a user entry may take.
        floor: u32,
    },
    /// A path component was empty, `.`, `..`, or longer than 255 bytes.
    #[error(
        "path {} has an invalid component {}",
        crate::escape::printable(.path),
        crate::escape::printable(.component)
    )]
    #[non_exhaustive]
    InvalidComponent {
        /// The offending path.
        path: Vec<u8>,
        /// The offending component.
        component: Vec<u8>,
    },
    /// Two entries resolve to the same path. This is a hard error: an input naming one
    /// path twice is rejected rather than resolved by keeping the last entry, so the
    /// filesystem an ambiguous source would produce is never guessed at.
    #[error("path {} is used by more than one entry", crate::escape::printable(.path))]
    #[non_exhaustive]
    Duplicate {
        /// The duplicated path.
        path: Vec<u8>,
    },
    /// An entry's parent directory was not declared.
    #[error("path {} has no parent directory", crate::escape::printable(.path))]
    #[non_exhaustive]
    ParentMissing {
        /// The path whose parent is absent.
        path: Vec<u8>,
    },
    /// An entry's parent path exists but is not a directory.
    #[error("path {} has a parent that is not a directory", crate::escape::printable(.path))]
    #[non_exhaustive]
    ParentNotDir {
        /// The path whose parent is not a directory.
        path: Vec<u8>,
    },
    /// An entry uses a path the filesystem reserves (such as `/lost+found`).
    #[error("path {} is reserved", crate::escape::printable(.path))]
    #[non_exhaustive]
    ReservedPath {
        /// The reserved path.
        path: Vec<u8>,
    },
    /// An entry's `mode` carries file-type bits, which the entry's kind supplies.
    ///
    /// [`Metadata::mode`](crate::Metadata::mode) holds the permission and
    /// set-user/group/sticky bits alone. A raw `st_mode` passed through whole would put a
    /// second file type on the inode — one the directory entry contradicts — and the write
    /// would succeed while every checker and driver reads the result as corrupt.
    #[error(
        "{}: mode {mode:#o} carries file-type bits, which the entry's kind supplies",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    ModeCarriesFileType {
        /// The offending path.
        path: Vec<u8>,
        /// The mode as given.
        mode: u16,
    },
    /// An entry carries BSD flags, which a Darwin filesystem records and this one does not.
    ///
    /// Refused rather than dropped. A caller who accepts the loss for an entry clears its
    /// [`darwin`](crate::SourceEntry::darwin) part; a compressed file's stored form is not a
    /// loss, since its content arrives decoded.
    #[error(
        "{}: BSD flags {flags:#x} are a Darwin filesystem's, and this one holds none",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    BsdFlagsNotHeld {
        /// The offending path.
        path: Vec<u8>,
        /// The flags it carries, but the one saying it is compressed.
        flags: u32,
    },
    /// An entry states a birth time and its inode has no field for one: a 128-byte inode
    /// ends before the creation time. Refused rather than dropped. A caller who accepts the
    /// loss for an entry clears its [`btime`](Metadata::btime).
    #[error(
        "{}: a 128-byte inode has no field for the birth time the entry states",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    BirthTimeNotHeld {
        /// The offending path.
        path: Vec<u8>,
    },
    /// A hard link's target does not exist.
    #[error(
        "hard link {} targets {}, which does not exist",
        crate::escape::printable(.path),
        crate::escape::printable(.target)
    )]
    #[non_exhaustive]
    HardlinkTargetMissing {
        /// The link's path.
        path: Vec<u8>,
        /// The missing target.
        target: Vec<u8>,
    },
    /// A hard link states extended attributes other than its target's, which no filesystem
    /// holds: a link is a name for an inode, and attributes belong to the inode. A member
    /// that repeats the target's attributes exactly states nothing new and is accepted —
    /// some archive producers write hard-link members that way — and anything else is
    /// refused rather than half-applied. State changes on the target instead.
    #[error(
        "hard link {} states extended attributes other than its target's, and attributes \
         belong to the target",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    LinkCarriesXattrs {
        /// The link's path.
        path: Vec<u8>,
    },
    /// A hard link's target is a directory. Every other file type may carry more than
    /// one name; a directory may not, since a second name would make the tree a cycle.
    #[error(
        "hard link {} targets {}, which is a directory",
        crate::escape::printable(.path),
        crate::escape::printable(.target)
    )]
    #[non_exhaustive]
    HardlinkTargetIsDirectory {
        /// The link's path.
        path: Vec<u8>,
        /// The directory target.
        target: Vec<u8>,
    },
    /// A chain of hard links closes on itself, so it names no inode.
    #[error(
        "hard link {} targets {} through a cycle of links",
        crate::escape::printable(.path),
        crate::escape::printable(.target)
    )]
    #[non_exhaustive]
    HardlinkCycle {
        /// The link's path.
        path: Vec<u8>,
        /// The target the chain began with.
        target: Vec<u8>,
    },
    /// A hard link would push its target's link count past what ext4 records.
    #[error(
        "hard link {} targets {}, which already holds the maximum links",
        crate::escape::printable(.path),
        crate::escape::printable(.target)
    )]
    #[non_exhaustive]
    TooManyLinks {
        /// The link's path.
        path: Vec<u8>,
        /// The target at its link limit.
        target: Vec<u8>,
    },
    /// A symlink target is longer than a single block.
    #[error(
        "symlink {} has a target of {len} bytes, more than a block holds",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    SymlinkTargetTooLong {
        /// The symlink's path.
        path: Vec<u8>,
        /// The target length.
        len: usize,
    },
    /// A symlink has an empty target, which points nowhere.
    #[error("symlink {} has an empty target", crate::escape::printable(.path))]
    #[non_exhaustive]
    EmptySymlinkTarget {
        /// The symlink's path.
        path: Vec<u8>,
    },
    /// A symlink target contains an embedded NUL, which the kernel reads as its end.
    #[error(
        "symlink {} has a target containing an embedded NUL",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    SymlinkTargetHasNul {
        /// The symlink's path.
        path: Vec<u8>,
    },
    /// A directory holds more subdirectories than a link count can track without the
    /// `dir_nlink` feature, which the emitted feature set does not carry.
    #[error(
        "directory {} has {subdirs} subdirectories, past the {limit} a link count holds \
         without the dir_nlink feature",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    DirectoryLinkCountOverflow {
        /// The directory's path.
        path: Vec<u8>,
        /// The subdirectory count that overran the limit.
        subdirs: u64,
        /// The most subdirectories representable without `dir_nlink`.
        limit: u16,
    },
    /// A device node's major or minor number exceeds what the on-disk form holds.
    #[error(
        "device {} has out-of-range numbers {major}:{minor}",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    DeviceNumberTooLarge {
        /// The device node's path.
        path: Vec<u8>,
        /// The requested major number.
        major: u32,
        /// The requested minor number.
        minor: u32,
    },
    /// An extended attribute's stored name is longer than 255 bytes.
    #[error(
        "entry {} has an extended attribute name longer than 255 bytes",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    XattrNameTooLong {
        /// The entry's path.
        path: Vec<u8>,
    },
    /// An extended attribute name the on-disk format cannot store as a distinct,
    /// addressable entry: empty (which an index-0 entry turns into the end-of-list
    /// terminator, hiding every attribute after it), carrying an embedded NUL (which the
    /// syscall boundary reads as the name's end), or duplicated within one entry's set
    /// (a state `setxattr(2)` cannot produce: it replaces an attribute of the same name).
    /// It is rejected rather than written
    /// into a set the kernel, `e2fsck`, and this crate's own reader would each misread.
    #[error(
        "entry {} has an invalid extended attribute name ({reason}): {}",
        crate::escape::printable(.path),
        crate::escape::printable(.name)
    )]
    #[non_exhaustive]
    InvalidXattrName {
        /// The entry's path.
        path: Vec<u8>,
        /// The offending attribute name.
        name: Vec<u8>,
        /// Why it cannot be stored: `empty`, `embedded NUL`, or `duplicate`.
        reason: &'static str,
    },
    /// An entry's extended attributes overflow the storage an inode commands: after
    /// filling the inode's inline region, the spilled remainder does not fit the one
    /// xattr block an inode can charge.
    #[error(
        "entry {} has extended attributes spilling {needed} bytes past the inode, more than a block holds",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    XattrsTooLarge {
        /// The entry's path.
        path: Vec<u8>,
        /// Bytes the spilled attributes need in the block.
        needed: usize,
    },
    /// An entry carries extended attributes on a feature set without `ext_attr`, which is
    /// the feature that says a filesystem holds any. Writing them regardless would leave
    /// inodes pointing at an attribute block the feature words deny, which `e2fsck`
    /// faults; dropping them would lose data the source supplied. Neither is done: the
    /// conflict between the attributes and the profile is stated instead.
    #[error(
        "entry {} carries extended attributes, which the feature set cannot hold without \
         ext_attr",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    XattrsWithoutFeature {
        /// The entry's path.
        path: Vec<u8>,
    },
    /// A regular file reaches [`LARGE_FILE_MIN_SIZE`] on a feature set without
    /// `large_file`, the feature that describes a file that large. The kernel sets the
    /// feature when it writes such a file and `e2fsck` faults an image carrying one
    /// without it, so the file is refused rather than written into a filesystem whose
    /// feature words deny it.
    #[error(
        "file {} is {size} bytes, past the {limit} a regular file may reach without the \
         large_file feature",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    FileTooLargeWithoutFeature {
        /// The file's path.
        path: Vec<u8>,
        /// The file's size in bytes.
        size: u64,
        /// The size a regular file must stay under without the feature.
        limit: u64,
    },
    /// An entry carries a timestamp its inode cannot represent: its seconds lie outside the
    /// range the inode holds, or its nanoseconds are not a fraction of a second. An inode
    /// larger than 128 bytes holds 1901 to 2446 to the nanosecond; a 128-byte inode holds a
    /// signed 32-bit second, 1901 to 2038, and no fraction, which is
    /// [`FractionNotHeld`](Self::FractionNotHeld). It is rejected rather than wrapped to a
    /// different instant or rounded.
    #[error(
        "entry {} has a timestamp of {secs}s + {nanos}ns outside the representable range",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    TimestampOutOfRange {
        /// The entry's path.
        path: Vec<u8>,
        /// The out-of-range seconds value.
        secs: i64,
        /// The nanosecond fraction.
        nanos: u32,
    },
    /// An entry carries a time with a fraction of a second, whose seconds a 128-byte inode
    /// holds and whose fraction it does not: such an inode ends before the words a fraction
    /// is stored in. It is rejected rather than rounded to the second.
    #[error(
        "entry {} has a time of {secs}s + {nanos}ns, and a 128-byte inode holds whole seconds \
         alone",
        crate::escape::printable(.path)
    )]
    #[non_exhaustive]
    FractionNotHeld {
        /// The entry's path.
        path: Vec<u8>,
        /// The seconds, which the inode holds.
        secs: i64,
        /// The nanosecond fraction it does not.
        nanos: u32,
    },
}

/// One entry inside a directory: a name pointing at an inode.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct DirChild {
    /// Entry name.
    pub name: Vec<u8>,
    /// Inode the name points at.
    pub inode: u32,
    /// File type of the named inode.
    pub file_type: FileType,
}

/// What an inode holds.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Content {
    /// A directory's ordered entries, beginning with `.` and `..`.
    Directory(Vec<DirChild>),
    /// A regular file's contents, in memory or still on the host.
    File(FileContent),
    /// A symlink whose target is stored inline in the inode block area.
    FastSymlink(Vec<u8>),
    /// A symlink whose target is stored in a data block.
    SlowSymlink(Vec<u8>),
    /// A device node; whether it is character- or block-special is carried in the
    /// mode, and the major/minor pair is stored in the inode's block area.
    Device {
        /// Device major number.
        major: u32,
        /// Device minor number.
        minor: u32,
    },
    /// A FIFO or socket: no data and no device number, its type carried in the mode.
    Special,
}

/// A modeled inode: its metadata and its contents, ready for the materializer to
/// place and write.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct ModelInode {
    /// Inode number.
    pub number: u32,
    /// Full mode, including the `S_IF*` type bits.
    pub mode: u16,
    /// Owning user id.
    pub uid: u32,
    /// Owning group id.
    pub gid: u32,
    /// Link count.
    pub links_count: u16,
    /// Access time.
    pub atime: Timestamp,
    /// Change (status) time.
    pub ctime: Timestamp,
    /// Modification time.
    pub mtime: Timestamp,
    /// Creation time: the entry's birth time, or its modification time where the source
    /// states none.
    pub crtime: Timestamp,
    /// Extended attributes attached to this inode.
    pub xattrs: Vec<Xattr>,
    /// The inode's contents.
    pub content: Content,
}

impl ModelInode {
    /// Whether this inode is a directory.
    #[must_use]
    pub fn is_dir(&self) -> bool {
        matches!(self.content, Content::Directory(_))
    }

    /// The file type a directory entry naming this inode records. It follows from the
    /// content, with the mode's type bits distinguishing the two kinds of device node
    /// and a FIFO from a socket.
    fn file_type(&self) -> FileType {
        match self.content {
            Content::Directory(_) => FileType::Dir,
            Content::File(_) => FileType::RegFile,
            Content::FastSymlink(_) | Content::SlowSymlink(_) => FileType::Symlink,
            Content::Device { .. } => match self.mode & MODE_TYPE_MASK {
                0o020000 => FileType::CharDev,
                _ => FileType::BlockDev,
            },
            Content::Special => match self.mode & MODE_TYPE_MASK {
                0o140000 => FileType::Socket,
                _ => FileType::Fifo,
            },
        }
    }
}

/// The complete inode tree: every inode the source implies, plus the always-present
/// root and `/lost+found`.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct FsModel {
    /// Inodes by number. Numbers are contiguous from [`ROOT_INO`] through
    /// `first_free_inode - 1` once the materializer's reserved inodes fill the gaps.
    pub inodes: BTreeMap<u32, ModelInode>,
    /// The next unused inode number; `first_free_inode - 1` inodes are in use.
    pub first_free_inode: u32,
}

impl FsModel {
    /// Inodes in use: every number below [`first_free_inode`](Self::first_free_inode).
    #[must_use]
    pub fn used_inode_count(&self) -> u32 {
        self.first_free_inode - 1
    }

    /// The root directory inode.
    #[must_use]
    pub fn root(&self) -> &ModelInode {
        &self.inodes[&ROOT_INO]
    }
}

/// Inputs the model needs beyond the source: the block size (which bounds a slow
/// symlink target), the inode size (which fixes the inline extended-attribute
/// region), the default time for the always-present directories, the inode number the
/// source's entries start at, and the feature answers that decide which entries the
/// filesystem can hold at all.
///
/// Build one with [`new`](Self::new), which derives every feature-driven field from one
/// [`FeatureSet`] so they cannot disagree with the image the writer goes on to emit, then
/// set [`fixed_time`](Self::fixed_time) if the format clamps timestamps.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct ModelConfig {
    /// Block size in bytes.
    pub block_size: u32,
    /// Inode size in bytes, which fixes the inline extended-attribute region an
    /// entry's attributes may occupy before spilling to a block.
    pub inode_size: u16,
    /// The inode number the first source entry takes. It is [`FIRST_USER_INO`] unless
    /// the feature set claims inodes of its own at format time — the orphan file takes
    /// inode 12 — in which case the entries begin above them. It may not name a
    /// reserved inode.
    pub first_user_inode: u32,
    /// Time recorded on the root and `/lost+found` directories, and the fallback for
    /// any entry when `fixed_time` is set.
    pub default_time: Timestamp,
    /// When set, every inode's four timestamps are forced to this value, overriding
    /// the per-entry times. Makes output byte-reproducible regardless of the
    /// source's timestamps.
    pub fixed_time: Option<Timestamp>,
    /// Whether the feature set permits a directory link count past 65 000
    /// (`dir_nlink`). When it does, an over-limit directory stores the sentinel `1`;
    /// when it does not, such a directory is rejected rather than given a sentinel no
    /// feature backs.
    pub dir_nlink: bool,
    /// Whether the feature set permits extended attributes (`ext_attr`). When it does not,
    /// an entry carrying any is rejected rather than written into a filesystem whose
    /// feature words say it holds none.
    pub ext_attr: bool,
    /// Whether the feature set permits a regular file of [`LARGE_FILE_MIN_SIZE`] or more
    /// (`large_file`). When it does not, a file that large is rejected rather than written
    /// into a filesystem whose feature words say it holds no such file.
    pub large_file: bool,
}

/// The four inode timestamps.
#[derive(Clone, Copy, Debug)]
struct Times {
    atime: Timestamp,
    ctime: Timestamp,
    mtime: Timestamp,
    crtime: Timestamp,
}

impl Times {
    /// Reject any of the times an inode of `inode_size` stores that it cannot represent,
    /// naming `path` in the error. Checked once per entry, before the times reach an inode.
    /// A 128-byte inode stores no creation time, so only the other three are asked of it.
    fn validate(&self, path: &[u8], inode_size: u16) -> Result<(), ModelError> {
        let extra = crate::ondisk::extra_isize_for(inode_size);
        let stored = if crate::ondisk::Inode::has_crtime(inode_size, extra) {
            &[self.atime, self.ctime, self.mtime, self.crtime][..]
        } else {
            &[self.atime, self.ctime, self.mtime][..]
        };
        for &t in stored {
            if crate::ondisk::time_is_representable(t, inode_size) {
                continue;
            }
            let whole = Timestamp::from_secs(t.secs);
            if t.nanos != 0 && crate::ondisk::time_is_representable(whole, inode_size) {
                return Err(ModelError::FractionNotHeld {
                    path: path.to_vec(),
                    secs: t.secs,
                    nanos: t.nanos,
                });
            }
            return Err(ModelError::TimestampOutOfRange {
                path: path.to_vec(),
                secs: t.secs,
                nanos: t.nanos,
            });
        }
        Ok(())
    }
}

impl ModelConfig {
    /// The configuration a `feature` set implies, for a source whose entries start at
    /// `first_user_inode` and whose always-present directories take `default_time`.
    ///
    /// Five of the fields — the block and inode sizes, and the three feature answers —
    /// are properties of the feature set alone, so they are read from it here rather than
    /// supplied one by one. Wiring them by hand is how a model comes to judge a source
    /// against a filesystem the writer is not about to emit: a `dir_nlink` answer that
    /// says yes to a set without the feature, or an `ext_attr` answer that says yes to one
    /// that cannot hold an attribute. There is one derivation, and this is it.
    ///
    /// [`fixed_time`](Self::fixed_time) starts unset — each entry keeps its own times —
    /// and is set afterward by a format that clamps them.
    #[must_use]
    pub fn new(feature: FeatureSet, first_user_inode: u32, default_time: Timestamp) -> Self {
        Self {
            block_size: feature.block_size,
            inode_size: feature.inode_size,
            first_user_inode,
            default_time,
            fixed_time: None,
            dir_nlink: feature.has_dir_nlink(),
            ext_attr: feature.has_ext_attr(),
            large_file: feature.has_large_file(),
        }
    }

    /// Resolve an entry's four timestamps, refusing any its inode cannot hold and naming
    /// `path`: the fixed time on every field when set, otherwise the entry's access, change
    /// and modification times, with its birth time as the creation time, or the modification
    /// time where it states none. A 128-byte inode has no creation field, so a birth time
    /// stated for one is refused rather than dropped.
    fn times(&self, meta: &Metadata, path: &[u8]) -> Result<Times, ModelError> {
        let times = match self.fixed_time {
            Some(t) => Times {
                atime: t,
                ctime: t,
                mtime: t,
                crtime: t,
            },
            None => {
                let extra = crate::ondisk::extra_isize_for(self.inode_size);
                if meta.btime.is_some() && !crate::ondisk::Inode::has_crtime(self.inode_size, extra)
                {
                    return Err(ModelError::BirthTimeNotHeld {
                        path: path.to_vec(),
                    });
                }
                Times {
                    atime: meta.atime,
                    ctime: meta.ctime,
                    mtime: meta.mtime,
                    crtime: meta.btime.unwrap_or(meta.mtime),
                }
            }
        };
        times.validate(path, self.inode_size)?;
        Ok(times)
    }

    /// The timestamp for the always-present directories: the fixed time when set,
    /// otherwise the default.
    fn base_time(&self) -> Times {
        let t = self.fixed_time.unwrap_or(self.default_time);
        Times {
            atime: t,
            ctime: t,
            mtime: t,
            crtime: t,
        }
    }
}

/// Validate an entry's extended attributes: the feature set must say the filesystem holds
/// attributes at all; each name must be present, free of NUL, and unique within the set;
/// names must fit `e_name_len`; and the set must fit the storage an inode commands — its
/// inline region plus one xattr block, split exactly as the writer will split it. The name
/// rules mirror the non-empty/no-NUL/unique discipline the path components enforce, and
/// for the same reason — a name the on-disk format cannot represent as a distinct,
/// addressable entry is rejected rather than written into a set that would silently lose
/// attributes.
/// The attribute set as ext stores it, narrowing each POSIX ACL from the form every
/// boundary speaks into the compact one this format packs it into.
///
/// This runs before [`validate_xattrs`] rather than after, because the compact form is
/// shorter than the one it came from: sizing the set that arrived would refuse attribute
/// sets that fit, and would size the spill block against bytes no inode ever holds.
fn stored_xattrs(path: &[u8], xattrs: &[Xattr]) -> Result<Vec<Xattr>, ModelError> {
    xattrs
        .iter()
        .map(|x| {
            if x.name != Acl::ACCESS_NAME && x.name != Acl::DEFAULT_NAME {
                return Ok(x.clone());
            }
            let acl = Acl::decode(&x.value).map_err(|source| ModelError::Acl {
                path: path.to_vec(),
                source,
            })?;
            Ok(Xattr {
                name: x.name.clone(),
                value: crate::ondisk::encode_acl(&acl),
            })
        })
        .collect()
}

fn validate_xattrs(path: &[u8], xattrs: &[Xattr], config: &ModelConfig) -> Result<(), ModelError> {
    if xattrs.is_empty() {
        return Ok(());
    }
    // `ext_attr` is what says a filesystem carries attributes: the inline region and the
    // external block both belong to it. A set on a profile without the feature is a
    // conflict between the input and the words the image would advertise, so it is named
    // before anything about the attributes themselves.
    if !config.ext_attr {
        return Err(ModelError::XattrsWithoutFeature {
            path: path.to_vec(),
        });
    }
    for x in xattrs {
        let reason = if has_empty_name(&x.name) {
            // An empty name is the end-of-list terminator under index 0 and an
            // unaddressable entry under any other index.
            Some("empty")
        } else if x.name.contains(&0) {
            Some("embedded NUL")
        } else {
            None
        };
        if let Some(reason) = reason {
            return Err(ModelError::InvalidXattrName {
                path: path.to_vec(),
                name: x.name.clone(),
                reason,
            });
        }
    }
    if let Some(name) = crate::xattr::repeated_name(xattrs) {
        return Err(ModelError::InvalidXattrName {
            path: path.to_vec(),
            name: name.to_vec(),
            reason: "duplicate",
        });
    }
    if longest_stored_name(xattrs) > 255 {
        return Err(ModelError::XattrNameTooLong {
            path: path.to_vec(),
        });
    }
    // The attributes that do not fit the inline region spill to the one block an
    // inode can charge; a spill the block cannot hold is the set's hard ceiling.
    let region_len = Inode::inline_xattr_capacity_for(config.inode_size);
    let (_, spilled) = split_for_storage(xattrs, region_len);
    let needed = xattr_block_len(&spilled);
    if !spilled.is_empty() && needed > config.block_size as usize {
        return Err(ModelError::XattrsTooLarge {
            path: path.to_vec(),
            needed,
        });
    }
    Ok(())
}

/// Reject a regular file the feature set cannot describe: one reaching
/// [`LARGE_FILE_MIN_SIZE`] without `large_file`. The bound is on regular files alone —
/// a directory of any size needs no such feature, which is also how `e2fsck` counts
/// them.
fn validate_file_size(path: &[u8], size: u64, config: &ModelConfig) -> Result<(), ModelError> {
    if size >= LARGE_FILE_MIN_SIZE && !config.large_file {
        return Err(ModelError::FileTooLargeWithoutFeature {
            path: path.to_vec(),
            size,
            limit: LARGE_FILE_MIN_SIZE,
        });
    }
    Ok(())
}

/// Whether a path names the filesystem root itself, having no component beyond
/// separators and no-op `.` elements — `/`, `.`, `./`, and the empty path all do. Such
/// an entry describes the root directory rather than something inside it.
fn names_the_root(path: &[u8]) -> bool {
    canonical_parts(path).is_empty()
}

/// Split a path into its meaningful components, and refuse the ones ext cannot hold.
///
/// Which components a path *has* is [`canonical_parts`], the rule every path in this crate
/// is normalized by — so `/etc/hostname`, `//etc//hostname`, and `etc/./hostname` are one
/// path here exactly as they are to a caller keying entries outside a model. Validation is
/// what this adds on top: `..` would traverse out of the tree, a component past 255 bytes
/// does not fit a directory entry's name field, and a NUL cannot appear in one at all.
///
/// Normalizing once and validating the result is what keeps the two from disagreeing: a
/// second normalization would not fail if it drifted, it would quietly key two entries apart
/// that the model considers one path.
fn components(path: &[u8]) -> Result<Vec<Vec<u8>>, ModelError> {
    let mut out = Vec::new();
    for part in canonical_parts(path) {
        if part == b".." || part.len() > 255 || part.contains(&0) {
            return Err(ModelError::InvalidComponent {
                path: path.to_vec(),
                component: part.to_vec(),
            });
        }
        out.push(part.to_vec());
    }
    if out.is_empty() {
        return Err(ModelError::EmptyPath);
    }
    Ok(out)
}

/// Join components back into a canonical key for the path map.
///
/// The same join [`canonical_key`](crate::path::canonical_key) makes, over the same
/// components — which is what the test below pins.
fn key(parts: &[Vec<u8>]) -> Vec<u8> {
    parts.join(&b'/')
}

/// One entry, normalized: its components and its parent/name split.
struct Normalized {
    parts: Vec<Vec<u8>>,
    entry: SourceEntry,
}

/// A directory in progress: its collected children and the parent it links back to.
struct DirBuild {
    parent: u32,
    children: Vec<DirChild>,
    /// The directory's path, kept for naming it in a finalization-time error.
    path: Vec<u8>,
}

/// Build the inode model from `source`.
///
/// An entry whose path names the root describes the root directory itself: its mode,
/// ownership, times, and extended attributes are applied to inode 2 rather than
/// creating an inode. At most one entry may name the root, and it must be a directory.
///
/// # Errors
///
/// A [`ModelError`] naming the offending path when an entry cannot be represented:
/// an invalid or duplicate path, a missing or non-directory parent, a reserved
/// path, an unresolvable or directory hard-link target, or an over-long symlink.
pub fn build_model(source: impl Source, config: ModelConfig) -> Result<FsModel, ModelError> {
    let mut inodes: BTreeMap<u32, ModelInode> = BTreeMap::new();
    let mut path_ino: BTreeMap<Vec<u8>, u32> = BTreeMap::new();
    let mut dirs: BTreeMap<u32, DirBuild> = BTreeMap::new();

    if config.first_user_inode < FIRST_USER_INO {
        return Err(ModelError::FirstUserInodeReserved {
            given: config.first_user_inode,
            floor: FIRST_USER_INO,
        });
    }

    // The format-wide default and fixed times reach the always-present directories, so
    // an unrepresentable one is caught once here rather than per inode.
    config.base_time().validate(b"/", config.inode_size)?;

    // Split the source: an entry naming the root describes inode 2, which already
    // exists, while every other entry creates one. The rest are processed in sorted
    // path order, so inode numbering is deterministic and parents precede their
    // children.
    let mut root_entry: Option<SourceEntry> = None;
    let mut normalized: Vec<Normalized> = Vec::new();
    for entry in source.into_entries() {
        if names_the_root(&entry.path) {
            if root_entry.is_some() {
                return Err(ModelError::Duplicate { path: entry.path });
            }
            if !matches!(entry.kind, EntryKind::Directory) {
                return Err(ModelError::RootNotDirectory { path: entry.path });
            }
            root_entry = Some(entry);
            continue;
        }
        let parts = components(&entry.path)?;
        normalized.push(Normalized { parts, entry });
    }
    normalized.sort_by_key(|a| key(&a.parts));

    // Root and lost+found always exist. The root takes the source's root entry when it
    // has one, and the standard 0755 root-owned directory otherwise.
    let root = match &root_entry {
        Some(entry) => {
            let times = config.times(&entry.meta, &entry.path)?;
            validate_mode(&entry.path, entry.meta.mode)?;
            validate_darwin(&entry.path, entry.darwin.as_ref())?;
            let xattrs = stored_xattrs(&entry.path, &entry.xattrs)?;
            validate_xattrs(&entry.path, &xattrs, &config)?;
            let mut root = dir_inode(ROOT_INO, 0o040000 | entry.meta.mode, times, xattrs);
            root.uid = entry.meta.uid;
            root.gid = entry.meta.gid;
            root
        }
        None => dir_inode(ROOT_INO, 0o040755, config.base_time(), Vec::new()),
    };
    inodes.insert(ROOT_INO, root);
    dirs.insert(
        ROOT_INO,
        DirBuild {
            parent: ROOT_INO,
            children: Vec::new(),
            path: b"/".to_vec(),
        },
    );
    path_ino.insert(Vec::new(), ROOT_INO);

    inodes.insert(
        LOST_FOUND_INO,
        dir_inode(LOST_FOUND_INO, 0o040700, config.base_time(), Vec::new()),
    );
    dirs.insert(
        LOST_FOUND_INO,
        DirBuild {
            parent: ROOT_INO,
            children: Vec::new(),
            path: b"/lost+found".to_vec(),
        },
    );
    path_ino.insert(b"lost+found".to_vec(), LOST_FOUND_INO);
    dirs.get_mut(&ROOT_INO)
        .expect("root was just inserted")
        .children
        .push(DirChild {
            name: b"lost+found".to_vec(),
            inode: LOST_FOUND_INO,
            file_type: FileType::Dir,
        });

    // Non-hard-link entries first: they create the inodes hard links later reference.
    let mut next_ino = config.first_user_inode;
    for n in &normalized {
        // `/lost+found` is the filesystem's own directory, so neither it nor anything
        // beneath it may come from the source — a hard link's name no more than any other.
        if n.parts.first().map(Vec::as_slice) == Some(b"lost+found".as_slice()) {
            return Err(ModelError::ReservedPath {
                path: n.entry.path.clone(),
            });
        }
        if matches!(n.entry.kind, EntryKind::HardLink { .. }) {
            continue;
        }
        let path_key = key(&n.parts);
        if path_ino.contains_key(&path_key) {
            return Err(ModelError::Duplicate {
                path: n.entry.path.clone(),
            });
        }
        let (parent_ino, name) = resolve_parent(&n.parts, &path_ino, &dirs, &n.entry.path)?;
        let ino = next_ino;
        next_ino += 1;
        let meta = &n.entry.meta;
        let times = config.times(meta, &n.entry.path)?;
        validate_mode(&n.entry.path, meta.mode)?;
        validate_darwin(&n.entry.path, n.entry.darwin.as_ref())?;
        let xattrs = stored_xattrs(&n.entry.path, &n.entry.xattrs)?;
        validate_xattrs(&n.entry.path, &xattrs, &config)?;
        // Every kind but a directory shares this leaf construction; a directory's
        // content and link count are filled in during finalization.
        let leaf = |mode: u16, content: Content| ModelInode {
            number: ino,
            mode,
            uid: meta.uid,
            gid: meta.gid,
            links_count: 1,
            atime: times.atime,
            ctime: times.ctime,
            mtime: times.mtime,
            crtime: times.crtime,
            xattrs: xattrs.clone(),
            content,
        };
        match &n.entry.kind {
            EntryKind::Directory => {
                let mut dir = dir_inode(ino, 0o040000 | meta.mode, times, xattrs.clone());
                dir.uid = meta.uid;
                dir.gid = meta.gid;
                inodes.insert(ino, dir);
                dirs.insert(
                    ino,
                    DirBuild {
                        parent: parent_ino,
                        children: Vec::new(),
                        path: n.entry.path.clone(),
                    },
                );
            }
            EntryKind::File(content) => {
                if matches!(content, FileContent::Declared { .. }) {
                    return Err(ModelError::ContentsNotHeld {
                        path: n.entry.path.clone(),
                    });
                }
                // The length is known without reading, so a file the feature set cannot
                // describe is refused here — naming its path — whether its bytes are in
                // memory or still on the host.
                validate_file_size(&n.entry.path, content.len(), &config)?;
                inodes.insert(
                    ino,
                    leaf(0o100000 | meta.mode, Content::File(content.clone())),
                );
            }
            EntryKind::Symlink(target) => {
                if target.is_empty() {
                    return Err(ModelError::EmptySymlinkTarget {
                        path: n.entry.path.clone(),
                    });
                }
                // The kernel reads a symlink target as a C string, stopping at the first
                // NUL. A target with an embedded NUL is rejected rather than stored to be
                // silently truncated on read — the same guard a directory component gets.
                if target.contains(&0) {
                    return Err(ModelError::SymlinkTargetHasNul {
                        path: n.entry.path.clone(),
                    });
                }
                // A slow symlink stores its target in a data block that must hold a
                // terminating NUL within the block, so the longest representable target
                // is one byte short of a block. A target of exactly `block_size` bytes
                // would fill the block with no room for the NUL and e2fsck faults it.
                if target.len() >= config.block_size as usize {
                    return Err(ModelError::SymlinkTargetTooLong {
                        path: n.entry.path.clone(),
                        len: target.len(),
                    });
                }
                let content = if target.len() < FAST_SYMLINK_MAX {
                    Content::FastSymlink(target.clone())
                } else {
                    Content::SlowSymlink(target.clone())
                };
                inodes.insert(ino, leaf(0o120777, content));
            }
            EntryKind::CharDevice { major, minor } => {
                check_device(&n.entry.path, *major, *minor)?;
                let content = Content::Device {
                    major: *major,
                    minor: *minor,
                };
                inodes.insert(ino, leaf(0o020000 | meta.mode, content));
            }
            EntryKind::BlockDevice { major, minor } => {
                check_device(&n.entry.path, *major, *minor)?;
                let content = Content::Device {
                    major: *major,
                    minor: *minor,
                };
                inodes.insert(ino, leaf(0o060000 | meta.mode, content));
            }
            EntryKind::Fifo => {
                inodes.insert(ino, leaf(0o010000 | meta.mode, Content::Special));
            }
            EntryKind::Socket => {
                inodes.insert(ino, leaf(0o140000 | meta.mode, Content::Special));
            }
            EntryKind::HardLink { .. } => unreachable!("hard links handled in the second pass"),
        }
        let file_type = inodes[&ino].file_type();
        path_ino.insert(path_key, ino);
        dirs.get_mut(&parent_ino)
            .expect("parent verified to be a directory")
            .children
            .push(DirChild {
                name,
                inode: ino,
                file_type,
            });
    }

    // Hard links: each is another name for an inode the first pass created. Collect
    // them all before resolving any, so a link that targets another link resolves
    // whichever order the two names sort in.
    let mut links: BTreeMap<Vec<u8>, &Normalized> = BTreeMap::new();
    for n in &normalized {
        if !matches!(n.entry.kind, EntryKind::HardLink { .. }) {
            continue;
        }
        let path_key = key(&n.parts);
        if path_ino.contains_key(&path_key) || links.contains_key(&path_key) {
            return Err(ModelError::Duplicate {
                path: n.entry.path.clone(),
            });
        }
        links.insert(path_key, n);
    }
    let mut resolved: HashMap<Vec<u8>, u32> = HashMap::new();
    for (path_key, n) in &links {
        let EntryKind::HardLink { target } = &n.entry.kind else {
            unreachable!("only hard links were collected");
        };
        let target_ino = resolve_link(&n.entry.path, target, &path_ino, &links, &mut resolved)?;
        // Every file type but a directory may carry more than one name. A second name
        // for a directory would turn the tree into a cycle, which no kernel permits.
        if inodes[&target_ino].is_dir() {
            return Err(ModelError::HardlinkTargetIsDirectory {
                path: n.entry.path.clone(),
                target: target.clone(),
            });
        }
        // Attributes belong to the inode, which is the target's: no filesystem holds an
        // attribute of a name. A member repeating the target's attributes exactly states
        // nothing new — archive producers exist that write hard-link members that way —
        // and anything else is refused rather than half-applied. Compared in stored form,
        // so the same list stated two ways is the same list.
        if !n.entry.xattrs.is_empty() {
            let stated = stored_xattrs(&n.entry.path, &n.entry.xattrs)?;
            if !crate::xattr::same_xattrs(&stated, &inodes[&target_ino].xattrs) {
                return Err(ModelError::LinkCarriesXattrs {
                    path: n.entry.path.clone(),
                });
            }
        }
        let (parent_ino, name) = resolve_parent(&n.parts, &path_ino, &dirs, &n.entry.path)?;
        let target_inode = inodes
            .get_mut(&target_ino)
            .expect("hard-link target verified to exist");
        // An inode's link count is the number of names pointing at it, so it cannot be
        // capped without contradicting the directory entries. Past ext4's limit the
        // link is refused rather than overflowing the 16-bit field.
        if target_inode.links_count >= MAX_LINKS {
            return Err(ModelError::TooManyLinks {
                path: n.entry.path.clone(),
                target: target.clone(),
            });
        }
        target_inode.links_count += 1;
        let file_type = target_inode.file_type();
        path_ino.insert(path_key.clone(), target_ino);
        dirs.get_mut(&parent_ino)
            .expect("parent verified to be a directory")
            .children
            .push(DirChild {
                name,
                inode: target_ino,
                file_type,
            });
    }

    // Finalize directories: link counts (2 + subdirectories) and the entry list with
    // `.` and `..` ahead of the name-sorted children.
    for (ino, build) in dirs {
        let subdirs = build
            .children
            .iter()
            .filter(|c| c.file_type == FileType::Dir)
            .count();
        let mut children = build.children;
        children.sort_by(|a, b| a.name.cmp(&b.name));
        let mut entries = Vec::with_capacity(children.len() + 2);
        entries.push(DirChild {
            name: b".".to_vec(),
            inode: ino,
            file_type: FileType::Dir,
        });
        entries.push(DirChild {
            name: b"..".to_vec(),
            inode: build.parent,
            file_type: FileType::Dir,
        });
        entries.extend(children);
        // A directory links `.`, its own name in its parent, and each subdirectory's
        // `..`. Past ext4's link limit the count is not tracked and stored as the
        // `dir_nlink` sentinel `1`, exactly as the kernel does, without wrapping the
        // 16-bit field. That sentinel means nothing without the `dir_nlink` feature to
        // back it, and without the feature the kernel cannot even reach this many
        // subdirectories, so an over-limit directory is rejected rather than given a
        // sentinel `e2fsck` would flag as inconsistent.
        let links = 2 + subdirs as u64;
        let links_count = if links > u64::from(MAX_LINKS) {
            if !config.dir_nlink {
                return Err(ModelError::DirectoryLinkCountOverflow {
                    path: build.path.clone(),
                    subdirs: subdirs as u64,
                    limit: MAX_LINKS,
                });
            }
            1
        } else {
            links as u16
        };
        let inode = inodes
            .get_mut(&ino)
            .expect("inode inserted for this directory");
        inode.links_count = links_count;
        inode.content = Content::Directory(entries);
    }

    Ok(FsModel {
        inodes,
        first_free_inode: next_ino,
    })
}

/// A directory inode with an empty entry list, filled in during finalization.
fn dir_inode(number: u32, mode: u16, times: Times, xattrs: Vec<Xattr>) -> ModelInode {
    ModelInode {
        number,
        mode,
        uid: 0,
        gid: 0,
        links_count: 2,
        atime: times.atime,
        ctime: times.ctime,
        mtime: times.mtime,
        crtime: times.crtime,
        xattrs,
        content: Content::Directory(Vec::new()),
    }
}

/// Reject a device node whose major or minor number the on-disk form cannot hold.
fn check_device(path: &[u8], major: u32, minor: u32) -> Result<(), ModelError> {
    if major > MAX_DEVICE_MAJOR || minor > MAX_DEVICE_MINOR {
        return Err(ModelError::DeviceNumberTooLarge {
            path: path.to_vec(),
            major,
            minor,
        });
    }
    Ok(())
}

/// Resolve the inode a hard link ultimately names, following any chain of links along
/// the way: a link may target another link, whose target may itself be a link, and the
/// chain ends at the one entry that created an inode.
///
/// `links` holds every hard link in the source, so resolution does not depend on the
/// order the names sort in. A chain that closes on itself names no inode and is
/// rejected; the hop count bounds the walk at the number of links, past which a
/// revisit — and so a cycle — is certain.
///
/// `resolved` carries every answer across calls, and every hop of a walk deposits its
/// own: the caller resolves each link of the source in turn, and without the memo a
/// source declaring one long chain would walk its tail once per member — quadratic in
/// the links for the same set of answers.
fn resolve_link(
    path: &[u8],
    target: &[u8],
    path_ino: &BTreeMap<Vec<u8>, u32>,
    links: &BTreeMap<Vec<u8>, &Normalized>,
    resolved: &mut HashMap<Vec<u8>, u32>,
) -> Result<u32, ModelError> {
    let mut trail: Vec<Vec<u8>> = Vec::new();
    let mut hop = key(&components(target)?);
    for _ in 0..=links.len() {
        if let Some(&ino) = resolved.get(&hop).or_else(|| path_ino.get(&hop)) {
            for walked in trail {
                resolved.insert(walked, ino);
            }
            return Ok(ino);
        }
        let next = links
            .get(&hop)
            .ok_or_else(|| ModelError::HardlinkTargetMissing {
                path: path.to_vec(),
                target: target.to_vec(),
            })?;
        let EntryKind::HardLink { target: onward } = &next.entry.kind else {
            unreachable!("only hard links were collected");
        };
        let onward = key(&components(onward)?);
        trail.push(std::mem::replace(&mut hop, onward));
    }
    Err(ModelError::HardlinkCycle {
        path: path.to_vec(),
        target: target.to_vec(),
    })
}

/// Resolve an entry's parent inode and its own name, checking the parent exists and
/// is a directory.
fn resolve_parent(
    parts: &[Vec<u8>],
    path_ino: &BTreeMap<Vec<u8>, u32>,
    dirs: &BTreeMap<u32, DirBuild>,
    path: &[u8],
) -> Result<(u32, Vec<u8>), ModelError> {
    let (name, parent_parts) = parts
        .split_last()
        .expect("components() rejects empty paths");
    let parent_ino =
        *path_ino
            .get(&key(parent_parts))
            .ok_or_else(|| ModelError::ParentMissing {
                path: path.to_vec(),
            })?;
    if !dirs.contains_key(&parent_ino) {
        return Err(ModelError::ParentNotDir {
            path: path.to_vec(),
        });
    }
    Ok((parent_ino, name.clone()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::{Metadata, TreeBuilder};

    fn config() -> ModelConfig {
        // The default feature set carries `dir_nlink`, `ext_attr`, and `large_file`, so
        // the derived configuration says yes to all three; a test that needs one of them
        // off overrides that field.
        let cfg = ModelConfig::new(
            FeatureSet::DEFAULT,
            FIRST_USER_INO,
            Timestamp::from_secs(1_700_000_000),
        );
        assert!(cfg.dir_nlink && cfg.ext_attr && cfg.large_file);
        assert_eq!((cfg.block_size, cfg.inode_size), (4096, 256));
        cfg
    }

    fn meta(mode: u16) -> Metadata {
        Metadata::new(mode, Timestamp::from_secs(1_700_000_000))
    }

    /// The smallest well-formed ACL, in the boundary form a source states one in.
    fn minimal_acl() -> Vec<u8> {
        use crate::acl::{AclEntry, AclQualifier};
        Acl::new(vec![
            AclEntry {
                who: AclQualifier::UserObj,
                perm: Acl::READ | Acl::WRITE,
            },
            AclEntry {
                who: AclQualifier::GroupObj,
                perm: Acl::READ,
            },
            AclEntry {
                who: AclQualifier::Other,
                perm: Acl::READ,
            },
        ])
        .expect("a well-formed ACL")
        .encode()
    }

    fn model(src: TreeBuilder) -> FsModel {
        build_model(src, config()).expect("model")
    }

    #[test]
    fn the_canonical_key_is_the_key_the_model_itself_uses() {
        // `canonical_key` exists so a caller keying entries by path outside the model —
        // `LayeredSource` — decides "same path" the way the model does. They normalize
        // through one function now, so what is left to disagree is the *join*, and this is
        // what pins it: for every path the model accepts, the shared key is the one the
        // model derives for itself. The samples still range over each way a path can be
        // written, because a joining rule that dropped or doubled a separator would only
        // show on some of them.
        for path in [
            &b"/etc/hostname"[..],
            b"//etc//hostname",
            b"etc/./hostname",
            b"etc/hostname/",
            b"/a",
            b"a/b/c/d/e",
            b"/var/log/./messages",
        ] {
            let theirs = key(&components(path).expect("the model accepts this path"));
            assert_eq!(
                crate::path::canonical_key(path),
                theirs,
                "{}: the shared key must be the model's",
                String::from_utf8_lossy(path)
            );
        }
        // The root is the one path `components` refuses while still naming something real,
        // and it keys as empty — which is what puts it before every other key and makes its
        // subtree the whole tree.
        for root in [&b"/"[..], b"", b".", b"./", b"///"] {
            assert!(names_the_root(root));
            assert!(crate::path::canonical_key(root).is_empty());
        }
    }

    #[test]
    fn empty_source_has_root_and_lost_found() {
        let m = model(TreeBuilder::new());
        assert_eq!(m.inodes.len(), 2);
        assert_eq!(m.first_free_inode, FIRST_USER_INO);
        // Root: mode 040755, links 3 (., its entry, and lost+found's ..).
        let root = m.root();
        assert_eq!(root.mode, 0o040755);
        assert_eq!(root.links_count, 3);
        // lost+found: mode 040700, links 2.
        let lf = &m.inodes[&LOST_FOUND_INO];
        assert_eq!(lf.mode, 0o040700);
        assert_eq!(lf.links_count, 2);
    }

    #[test]
    fn a_hard_link_stating_attributes_other_than_its_targets_is_refused() {
        // Attributes belong to the inode and a link is a name for one, so an attribute
        // stated on the link alone is one no image can carry: applying it to the target
        // would be guessing, and dropping it would lose what the source stated.
        let time = Timestamp::from_secs(1_700_000_000);
        let src = TreeBuilder::new()
            .file(
                b"/target".to_vec(),
                b"x".to_vec(),
                Metadata::new(0o644, time),
            )
            .hardlink(
                b"/link".to_vec(),
                b"/target".to_vec(),
                Metadata::new(0o644, time),
            )
            .xattr(b"user.note".to_vec(), b"v".to_vec());
        let err = build_model(src, config()).unwrap_err();
        assert!(
            matches!(err, ModelError::LinkCarriesXattrs { .. }),
            "{err:?}"
        );

        // A member that repeats the target's attributes exactly states nothing new —
        // archive producers exist that write hard-link members that way — and builds the
        // image the target alone describes.
        let src = TreeBuilder::new()
            .file(
                b"/target".to_vec(),
                b"x".to_vec(),
                Metadata::new(0o644, time),
            )
            .xattr(b"user.note".to_vec(), b"v".to_vec())
            .hardlink(
                b"/link".to_vec(),
                b"/target".to_vec(),
                Metadata::new(0o644, time),
            )
            .xattr(b"user.note".to_vec(), b"v".to_vec());
        let m = build_model(src, config()).expect("a repeated set states nothing new");
        let target = m
            .inodes
            .values()
            .find(|inode| inode.links_count == 2 && !inode.is_dir())
            .expect("the target has two names");
        assert_eq!(target.xattrs.len(), 1, "the one attribute, held once");
    }

    #[test]
    fn a_mode_carrying_file_type_bits_is_rejected() {
        // The natural mistake: a raw `st_mode` passed through whole. Accepted, it would
        // write an inode whose mode says one file type while its directory entry says
        // another — a filesystem `e2fsck` faults and a kernel misreads — so it is the
        // typed refusal every other unrepresentable input here gets.
        let time = Timestamp::from_secs(1_700_000_000);
        let src = TreeBuilder::new().file(
            b"/f".to_vec(),
            b"x".to_vec(),
            Metadata::new(0o100_644, time),
        );
        let err = build_model(src, config()).unwrap_err();
        assert!(
            matches!(
                err,
                ModelError::ModeCarriesFileType {
                    mode: 0o100_644,
                    ..
                }
            ),
            "expected ModeCarriesFileType, got {err:?}"
        );
        // The root entry passes through its own arm of the build, and must be held to
        // the same rule.
        let src = TreeBuilder::new().directory(b"/".to_vec(), Metadata::new(0o040_755, time));
        let err = build_model(src, config()).unwrap_err();
        assert!(
            matches!(err, ModelError::ModeCarriesFileType { .. }),
            "expected ModeCarriesFileType for the root entry, got {err:?}"
        );
    }

    #[test]
    fn an_unrepresentable_entry_timestamp_is_rejected() {
        // A file mtime the on-disk format cannot hold is a typed error, not a silent
        // wrap to a different instant.
        let mut m = Metadata::new(0o644, Timestamp::from_secs(1_700_000_000));
        m.mtime = Timestamp::from_secs(crate::ondisk::TIME_SECS_MAX + 1);
        let src = TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), m);
        let err = build_model(src, config()).unwrap_err();
        assert!(
            matches!(err, ModelError::TimestampOutOfRange { secs, .. } if secs == crate::ondisk::TIME_SECS_MAX + 1),
            "expected TimestampOutOfRange, got {err:?}"
        );
    }

    #[test]
    fn a_birth_time_a_small_inode_has_no_field_for_is_refused() {
        let born = Metadata::new(0o644, Timestamp::from_secs(1_700_000_000))
            .with_birth_time(Timestamp::from_secs(1_600_000_000));
        let file = || TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), born);
        let small = ModelConfig {
            inode_size: 128,
            ..config()
        };
        assert!(matches!(
            build_model(file(), small),
            Err(ModelError::BirthTimeNotHeld { path }) if path == b"/f"
        ));
        // The fixed time states every time of every inode, the creation time among them, so
        // nothing the source stated is lost by its having no field.
        let fixed = ModelConfig {
            fixed_time: Some(Timestamp::from_secs(1_500_000_000)),
            ..small
        };
        build_model(file(), fixed).expect("the fixed time over it");
        // A larger inode holds it, as the creation time.
        let m = build_model(file(), config()).expect("held");
        let crtime = m
            .inodes
            .values()
            .find(|i| matches!(i.content, Content::File(_)))
            .expect("the file")
            .crtime;
        assert_eq!(crtime, Timestamp::from_secs(1_600_000_000));
    }

    #[test]
    fn a_time_a_small_inode_holds_no_field_for_is_rejected() {
        // A 128-byte inode ends before each time's extra word: a second past 2038, or a
        // fraction of one, has nowhere to go and would be written as another instant.
        let small = ModelConfig {
            inode_size: 128,
            ..config()
        };
        let at = |mtime: Timestamp| {
            let m = Metadata::new(0o644, Timestamp::from_secs(1_700_000_000));
            let m = m.with_times(m.atime, m.ctime, mtime);
            build_model(
                TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), m),
                small,
            )
        };
        let past = Timestamp::from_secs(i64::from(i32::MAX) + 1);
        assert!(matches!(
            at(past),
            Err(ModelError::TimestampOutOfRange { secs, .. }) if secs == past.secs
        ));
        let fraction = Timestamp {
            secs: 1_700_000_000,
            nanos: 1,
        };
        assert!(matches!(
            at(fraction),
            Err(ModelError::FractionNotHeld {
                secs: 1_700_000_000,
                nanos: 1,
                ..
            })
        ));
        at(Timestamp::from_secs(i64::from(i32::MAX))).expect("the field's last second");
        // A larger inode holds both.
        let large = ModelConfig {
            inode_size: 256,
            ..config()
        };
        let m = Metadata::new(0o644, past).with_times(fraction, fraction, past);
        build_model(
            TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), m),
            large,
        )
        .expect("held");
        // The format's own instant reaches the root, and is held to the same rule.
        let cfg = ModelConfig {
            default_time: fraction,
            ..small
        };
        assert!(matches!(
            build_model(TreeBuilder::new(), cfg),
            Err(ModelError::FractionNotHeld { path, .. }) if path == b"/"
        ));
    }

    #[test]
    fn an_unrepresentable_default_time_is_rejected() {
        // The format-wide default time reaches the always-present directories, so an
        // unrepresentable one fails the build up front.
        let cfg = ModelConfig {
            default_time: Timestamp::from_secs(crate::ondisk::TIME_SECS_MIN - 1),
            ..config()
        };
        let err = build_model(TreeBuilder::new(), cfg).unwrap_err();
        assert!(matches!(err, ModelError::TimestampOutOfRange { .. }));
    }

    #[test]
    fn root_entries_begin_with_dot_and_dotdot() {
        let m = model(TreeBuilder::new());
        let Content::Directory(children) = &m.root().content else {
            panic!("root is a directory");
        };
        assert_eq!(children[0].name, b".");
        assert_eq!(children[0].inode, ROOT_INO);
        assert_eq!(children[1].name, b"..");
        assert_eq!(children[1].inode, ROOT_INO, "root's .. points at itself");
        assert_eq!(children[2].name, b"lost+found");
    }

    #[test]
    fn inode_numbers_are_deterministic_in_sorted_path_order() {
        // Added out of order; numbering follows sorted paths, not addition order.
        let m = model(
            TreeBuilder::new()
                .directory(b"/b".to_vec(), meta(0o755))
                .directory(b"/a".to_vec(), meta(0o755))
                .file(b"/a/z".to_vec(), b"z".to_vec(), meta(0o644))
                .file(b"/a/y".to_vec(), b"y".to_vec(), meta(0o644)),
        );
        // Sorted: /a (12), /a/y (13), /a/z (14), /b (15).
        assert_eq!(*m.inodes.keys().max().unwrap(), 15);
        let a = m.inodes.values().find(|i| i.number == 12).unwrap();
        assert!(a.is_dir());
    }

    #[test]
    fn subdirectories_raise_the_parent_link_count() {
        let m = model(
            TreeBuilder::new()
                .directory(b"/a".to_vec(), meta(0o755))
                .directory(b"/a/sub1".to_vec(), meta(0o755))
                .directory(b"/a/sub2".to_vec(), meta(0o755)),
        );
        let a = m.inodes.values().find(|i| matches!(&i.content, Content::Directory(c) if c.iter().any(|e| e.name == b"sub1"))).unwrap();
        // /a: 2 + two subdirectories = 4.
        assert_eq!(a.links_count, 4);
        // Root gained /a as a subdirectory: 2 + lost+found + a = 4.
        assert_eq!(m.root().links_count, 4);
    }

    #[test]
    fn hardlinks_coalesce_onto_one_inode() {
        let m = model(
            TreeBuilder::new()
                .file(b"/a".to_vec(), b"data".to_vec(), meta(0o644))
                .hardlink(b"/b".to_vec(), b"/a".to_vec(), meta(0o644)),
        );
        // Only one file inode exists; it has link count 2.
        let files: Vec<_> = m
            .inodes
            .values()
            .filter(|i| matches!(i.content, Content::File(_)))
            .collect();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].links_count, 2);
        // Both names point at the same inode.
        let Content::Directory(root) = &m.root().content else {
            unreachable!()
        };
        let a = root.iter().find(|e| e.name == b"a").unwrap().inode;
        let b = root.iter().find(|e| e.name == b"b").unwrap().inode;
        assert_eq!(a, b);
    }

    #[test]
    fn symlink_form_follows_target_length() {
        let short = vec![b'x'; 59];
        let long = vec![b'x'; 60];
        let m = model(
            TreeBuilder::new()
                .symlink(b"/short".to_vec(), short.clone(), meta(0o777))
                .symlink(b"/long".to_vec(), long.clone(), meta(0o777)),
        );
        let s = m
            .inodes
            .values()
            .find(|i| matches!(&i.content, Content::FastSymlink(t) if *t == short));
        let l = m
            .inodes
            .values()
            .find(|i| matches!(&i.content, Content::SlowSymlink(t) if *t == long));
        assert!(s.is_some(), "59-byte target is a fast symlink");
        assert!(l.is_some(), "60-byte target is a slow symlink");
        assert_eq!(s.unwrap().mode, 0o120777);
    }

    #[test]
    fn a_symlink_target_with_an_embedded_nul_is_rejected() {
        // The kernel reads a symlink target as a C string and stops at the first NUL, so
        // an interior NUL would silently truncate the target on read. It is a typed error
        // at model time, the same guard a directory-entry name gets.
        let err = build_model(
            TreeBuilder::new().symlink(b"/link".to_vec(), b"a\0b".to_vec(), meta(0o777)),
            config(),
        )
        .unwrap_err();
        assert!(
            matches!(err, ModelError::SymlinkTargetHasNul { .. }),
            "an embedded NUL must be a typed error, got {err:?}"
        );
    }

    #[test]
    fn a_directory_past_the_link_limit_requires_dir_nlink() {
        // A directory's link count is 2 (`.` and its name in the parent) plus one per
        // subdirectory (its `..`). 64_999 subdirectories reach 65_001, one past
        // MAX_LINKS, where ext4 stores the `dir_nlink` sentinel `1` — but that sentinel
        // means nothing without the feature, and the kernel could not have created this
        // many subdirectories without it either.
        let build = || {
            let mut b = TreeBuilder::new().directory(b"/d".to_vec(), meta(0o755));
            for i in 0..64_999u32 {
                b = b.directory(format!("/d/{i:05}").into_bytes(), meta(0o755));
            }
            b
        };

        // Without dir_nlink the over-limit directory is refused rather than given a
        // sentinel `e2fsck` would flag as inconsistent.
        let cfg_off = ModelConfig {
            dir_nlink: false,
            ..config()
        };
        let err = build_model(build(), cfg_off).unwrap_err();
        assert!(
            matches!(
                err,
                ModelError::DirectoryLinkCountOverflow { subdirs, limit, .. }
                    if subdirs == 64_999 && limit == 65_000
            ),
            "without dir_nlink the overflow must be a typed error, got {err:?}"
        );

        // With dir_nlink it stores the sentinel `1`, as the kernel does.
        let m = build_model(build(), config()).expect("dir_nlink permits the overflow");
        let d = m
            .inodes
            .values()
            .find(|i| matches!(&i.content, Content::Directory(e) if e.len() > 65_000))
            .expect("the large directory is present");
        assert_eq!(d.links_count, 1, "the dir_nlink sentinel");
    }

    #[test]
    fn ownership_and_mode_are_preserved() {
        let m = model(TreeBuilder::new().file(
            b"/f".to_vec(),
            b"x".to_vec(),
            meta(0o4755).owned_by(1000, 2000),
        ));
        let f = m
            .inodes
            .values()
            .find(|i| matches!(i.content, Content::File(_)))
            .unwrap();
        assert_eq!(f.mode, 0o104755, "setuid bit and perms preserved");
        assert_eq!(f.uid, 1000);
        assert_eq!(f.gid, 2000);
    }

    #[test]
    fn missing_parent_is_rejected() {
        let err = build_model(
            TreeBuilder::new().file(b"/nodir/f".to_vec(), b"x".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert!(matches!(err, ModelError::ParentMissing { .. }));
    }

    #[test]
    fn parent_that_is_a_file_is_rejected() {
        let err = build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"x".to_vec(), meta(0o644))
                .file(b"/f/child".to_vec(), b"y".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert!(matches!(err, ModelError::ParentNotDir { .. }));
    }

    #[test]
    fn reserved_and_duplicate_and_dotdot_paths_are_rejected() {
        assert!(matches!(
            build_model(
                TreeBuilder::new().directory(b"/lost+found".to_vec(), meta(0o700)),
                config()
            ),
            Err(ModelError::ReservedPath { .. })
        ));
        // A hard link's name is a name the source supplies like any other.
        assert!(matches!(
            build_model(
                TreeBuilder::new()
                    .file(b"/a".to_vec(), b"1".to_vec(), meta(0o644))
                    .hardlink(b"/lost+found/x".to_vec(), b"/a".to_vec(), meta(0o644)),
                config()
            ),
            Err(ModelError::ReservedPath { .. })
        ));
        assert!(matches!(
            build_model(
                TreeBuilder::new()
                    .file(b"/a".to_vec(), b"1".to_vec(), meta(0o644))
                    .file(b"/a".to_vec(), b"2".to_vec(), meta(0o644)),
                config()
            ),
            Err(ModelError::Duplicate { .. })
        ));
        assert!(matches!(
            build_model(
                TreeBuilder::new().file(b"/a/../b".to_vec(), b"x".to_vec(), meta(0o644)),
                config()
            ),
            Err(ModelError::InvalidComponent { .. })
        ));
    }

    #[test]
    fn hardlink_to_a_directory_is_rejected() {
        let err = build_model(
            TreeBuilder::new()
                .directory(b"/d".to_vec(), meta(0o755))
                .hardlink(b"/l".to_vec(), b"/d".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert!(matches!(err, ModelError::HardlinkTargetIsDirectory { .. }));
    }

    #[test]
    fn hardlink_resolves_regardless_of_order() {
        // The link sorts before its target; the two-pass build still resolves it.
        let m = model(
            TreeBuilder::new()
                .hardlink(b"/aaa".to_vec(), b"/zzz".to_vec(), meta(0o644))
                .file(b"/zzz".to_vec(), b"data".to_vec(), meta(0o644)),
        );
        let files: Vec<_> = m
            .inodes
            .values()
            .filter(|i| matches!(i.content, Content::File(_)))
            .collect();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].links_count, 2);
    }

    #[test]
    fn a_hardlink_names_any_kind_but_a_directory() {
        // Every file type but a directory may carry a second name, and the directory
        // entry records the type of the inode it points at, not a regular file.
        let m = model(
            TreeBuilder::new()
                .symlink(b"/sym".to_vec(), b"/target".to_vec(), meta(0o777))
                .hardlink(b"/sym-link".to_vec(), b"/sym".to_vec(), meta(0o777))
                .char_device(b"/null".to_vec(), 1, 3, meta(0o666))
                .hardlink(b"/null-link".to_vec(), b"/null".to_vec(), meta(0o666))
                .fifo(b"/pipe".to_vec(), meta(0o644))
                .hardlink(b"/pipe-link".to_vec(), b"/pipe".to_vec(), meta(0o644)),
        );
        let Content::Directory(root) = &m.root().content else {
            unreachable!()
        };
        let child = |name: &[u8]| root.iter().find(|e| e.name == name).expect("entry");
        for (link, target, file_type) in [
            (&b"/sym-link"[..], &b"/sym"[..], FileType::Symlink),
            (b"/null-link", b"/null", FileType::CharDev),
            (b"/pipe-link", b"/pipe", FileType::Fifo),
        ] {
            let link = child(&link[1..]);
            let target = child(&target[1..]);
            assert_eq!(link.inode, target.inode, "the link shares the inode");
            assert_eq!(link.file_type, file_type);
            assert_eq!(m.inodes[&link.inode].links_count, 2);
        }
    }

    #[test]
    fn a_hardlink_to_a_hardlink_resolves_to_the_inode_beneath_both() {
        // The chain runs backwards through the sort order — /a targets /b, which targets
        // /c — so resolving one link at a time in name order would leave /a unresolved.
        let m = model(
            TreeBuilder::new()
                .hardlink(b"/a".to_vec(), b"/b".to_vec(), meta(0o644))
                .hardlink(b"/b".to_vec(), b"/c".to_vec(), meta(0o644))
                .file(b"/c".to_vec(), b"data".to_vec(), meta(0o644)),
        );
        let files: Vec<_> = m
            .inodes
            .values()
            .filter(|i| matches!(i.content, Content::File(_)))
            .collect();
        assert_eq!(files.len(), 1, "all three names share one inode");
        assert_eq!(files[0].links_count, 3);
    }

    #[test]
    fn a_cycle_of_hardlinks_is_rejected() {
        // Two links naming each other reach no inode; the walk must report the cycle
        // rather than loop.
        let err = build_model(
            TreeBuilder::new()
                .hardlink(b"/a".to_vec(), b"/b".to_vec(), meta(0o644))
                .hardlink(b"/b".to_vec(), b"/a".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert!(
            matches!(err, ModelError::HardlinkCycle { .. }),
            "expected HardlinkCycle, got {err:?}"
        );
    }

    #[test]
    fn an_empty_nul_or_duplicate_xattr_name_is_rejected() {
        // An empty name serializes to the end-of-list terminator and would hide every
        // attribute after it; a bare namespace prefix has no name past it; a NUL is a
        // false C-string end. Each is refused rather than written into a set that
        // silently drops attributes.
        for (name, reason) in [
            (&b""[..], "empty"),
            (b"user.", "empty"),
            (b"user.a\0b", "embedded NUL"),
        ] {
            let err = build_model(
                TreeBuilder::new()
                    .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                    .xattr(name.to_vec(), b"v".to_vec()),
                config(),
            )
            .unwrap_err();
            assert!(
                matches!(&err, ModelError::InvalidXattrName { reason: r, .. } if *r == reason),
                "name {:?} should be rejected as {reason}, got {err:?}",
                String::from_utf8_lossy(name)
            );
        }

        // A name written twice is a state the kernel cannot produce; the second occurrence
        // is the offending one.
        let err = build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(b"user.a".to_vec(), b"1".to_vec())
                .xattr(b"user.a".to_vec(), b"2".to_vec()),
            config(),
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                ModelError::InvalidXattrName {
                    reason: "duplicate",
                    ..
                }
            ),
            "a duplicate xattr name should be rejected, got {err:?}"
        );
    }

    #[test]
    fn a_xattr_set_larger_than_one_block_is_accepted_when_it_splits() {
        // At a 4096-byte block, `user.huge` alone needs the whole block (32-byte
        // header + 20-byte entry + 4040-byte value + 4-byte terminator = 4096), and
        // `user.tiny` fits the 256-byte inode's 88 free inline bytes. Together they
        // exceed one block, and only the split makes the set representable — the
        // same storage a kernel-written inode holds it in.
        let m = build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(b"user.huge".to_vec(), vec![0xAA; 4040])
                .xattr(b"user.tiny".to_vec(), vec![0xBB; 60]),
            config(),
        )
        .expect("a set that fits split across the inode and one block");
        let f = m
            .inodes
            .values()
            .find(|i| matches!(i.content, Content::File(_)))
            .unwrap();
        assert_eq!(f.xattrs.len(), 2, "both attributes reach the inode");
    }

    #[test]
    fn a_xattr_spill_no_block_holds_is_rejected() {
        // One more word in the huge value pushes the spilled side past the block:
        // 32 + 20 + align4(4041) + 4 = 4100. The inline attribute is not part of
        // that count — the error names only what the block must hold.
        let err = build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(b"user.huge".to_vec(), vec![0xAA; 4041])
                .xattr(b"user.tiny".to_vec(), vec![0xBB; 60]),
            config(),
        )
        .unwrap_err();
        assert!(
            matches!(err, ModelError::XattrsTooLarge { needed: 4100, .. }),
            "the spill alone overflows a block, got {err:?}"
        );
    }

    #[test]
    fn attributes_on_a_profile_without_ext_attr_are_refused() {
        // `ext_attr` is the feature that says a filesystem holds attributes at all. A
        // source carrying one on a profile without it is a conflict between the input and
        // the words the image would advertise: writing the attribute anyway leaves an
        // inode pointing at a block the feature word denies (which `e2fsck` faults), and
        // dropping it silently loses what the source supplied. The conflict is named.
        let cfg = ModelConfig {
            ext_attr: false,
            ..config()
        };
        let src = || {
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(b"user.a".to_vec(), b"1".to_vec())
        };
        let err = build_model(src(), cfg).unwrap_err();
        assert!(
            matches!(
                err,
                ModelError::XattrsWithoutFeature { ref path } if path == b"/f"
            ),
            "expected XattrsWithoutFeature naming the entry, got {err:?}"
        );

        // With the feature the same source builds, and a profile without it accepts every
        // entry that carries no attribute.
        build_model(src(), config()).expect("ext_attr holds the same set");
        build_model(
            TreeBuilder::new().file(b"/f".to_vec(), b"data".to_vec(), meta(0o644)),
            cfg,
        )
        .expect("an entry with no attributes needs no feature");
    }

    #[test]
    fn a_regular_file_past_the_large_file_bound_requires_the_feature() {
        // The rule is checked against a size rather than against bytes, so it is exercised
        // here without materializing two gigabytes. The bound is the documentation's
        // RO_COMPAT_LARGE_FILE, and inclusive: without the feature the pinned `e2fsck`
        // accepts a regular file of 2^31 - 1 bytes and faults one of 2^31 (observed).
        let with = config();
        let without = ModelConfig {
            large_file: false,
            ..config()
        };
        let at = LARGE_FILE_MIN_SIZE;

        assert!(validate_file_size(b"/f", at - 1, &without).is_ok());
        let err = validate_file_size(b"/f", at, &without).unwrap_err();
        assert!(
            matches!(
                err,
                ModelError::FileTooLargeWithoutFeature { size, limit, ref path }
                    if size == LARGE_FILE_MIN_SIZE && limit == LARGE_FILE_MIN_SIZE && path == b"/f"
            ),
            "expected FileTooLargeWithoutFeature naming the file, got {err:?}"
        );
        // The feature is what lifts the bound.
        assert!(validate_file_size(b"/f", at, &with).is_ok());
    }

    #[test]
    fn an_acl_xattr_name_with_an_empty_stored_name_is_accepted() {
        // `system.posix_acl_access` is a whole-name index: its stored name is empty by
        // design and must not be taken for an empty attribute name.
        build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(b"system.posix_acl_access".to_vec(), minimal_acl()),
            config(),
        )
        .expect("a whole-name ACL attribute is a valid, non-empty name");
    }

    #[test]
    fn an_acl_attribute_is_narrowed_to_the_form_ext_stores() {
        // The value a source states is the boundary form; what the inode carries is this
        // format's packing of it. Storing the stated bytes would be an attribute the kernel
        // reads as an ACL and cannot parse.
        let m = model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(Acl::ACCESS_NAME.to_vec(), minimal_acl()),
        );
        let stored = &m
            .inodes
            .values()
            .find(|i| i.xattrs.iter().any(|x| x.name == Acl::ACCESS_NAME))
            .expect("the file carries the ACL")
            .xattrs[0];
        assert_eq!(
            stored.value,
            crate::ondisk::encode_acl(&Acl::decode(&minimal_acl()).expect("the stated ACL"))
        );
        assert!(
            stored.value.len() < minimal_acl().len(),
            "the stored form is the narrower one"
        );
    }

    #[test]
    fn an_acl_attribute_already_in_the_stored_form_is_refused_rather_than_narrowed_twice() {
        // The two forms are told apart by their version header, so the narrowing is not
        // idempotent and must not pretend to be: a value that is already what the inode
        // carries is a caller stating the wrong form, and narrowing it again would pack a
        // header and entries that were never a boundary ACL. It is the one confusion
        // available between the two, so it is refused by name rather than misread.
        let compact = crate::ondisk::encode_acl(&Acl::decode(&minimal_acl()).expect("an ACL"));
        let err = build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(Acl::ACCESS_NAME.to_vec(), compact),
            config(),
        )
        .expect_err("the stored form is not a value a source may state");
        assert!(matches!(err, ModelError::Acl { .. }), "{err:?}");
    }

    #[test]
    fn an_acl_attribute_that_is_not_an_acl_is_refused() {
        // Written through as opaque bytes this would be an attribute the kernel reads as an
        // ACL and cannot parse, which is access nobody described.
        let err = build_model(
            TreeBuilder::new()
                .file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
                .xattr(Acl::ACCESS_NAME.to_vec(), b"not an ACL".to_vec()),
            config(),
        )
        .expect_err("a value that is not an ACL is refused");
        assert!(matches!(err, ModelError::Acl { .. }), "{err:?}");
    }

    #[test]
    fn a_root_entry_supplies_the_root_directorys_metadata() {
        // The root already exists, so an entry naming it describes inode 2 rather than
        // adding one: its mode, ownership, and extended attributes are the root's, and
        // the inode numbering is untouched.
        let m = model(
            TreeBuilder::new()
                .root(meta(0o700).owned_by(1000, 2000))
                .xattr(b"user.label".to_vec(), b"rootfs".to_vec())
                .file(b"/f".to_vec(), b"x".to_vec(), meta(0o644)),
        );
        let root = m.root();
        assert_eq!(root.mode, 0o040700);
        assert_eq!((root.uid, root.gid), (1000, 2000));
        assert_eq!(root.xattrs[0].name, b"user.label");
        assert_eq!(root.links_count, 3, "., lost+found's .., and its own");
        assert_eq!(
            m.first_free_inode, 13,
            "the root entry consumed no inode number"
        );
    }

    #[test]
    fn entries_begin_at_the_configured_first_user_inode() {
        // A feature that claims an inode at format time — the orphan file takes 12 —
        // moves the entries up, and the used count still spans every inode below them.
        let cfg = ModelConfig {
            first_user_inode: FIRST_USER_INO + 1,
            ..config()
        };
        let src = TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), meta(0o644));
        let m = build_model(src, cfg).expect("model");
        let f = m
            .inodes
            .values()
            .find(|i| matches!(i.content, Content::File(_)))
            .unwrap();
        assert_eq!(f.number, 13, "the entry sits above the claimed inode");
        assert_eq!(m.first_free_inode, 14);
        assert_eq!(
            m.used_inode_count(),
            13,
            "the claimed inode is counted as in use, though the model never holds it"
        );
    }

    #[test]
    fn a_first_user_inode_inside_the_reserved_range_is_rejected() {
        let cfg = ModelConfig {
            first_user_inode: LOST_FOUND_INO,
            ..config()
        };
        let err = build_model(TreeBuilder::new(), cfg).unwrap_err();
        assert!(matches!(
            err,
            ModelError::FirstUserInodeReserved { given, floor }
                if given == LOST_FOUND_INO && floor == FIRST_USER_INO
        ));
    }

    #[test]
    fn a_root_entry_that_is_not_a_directory_is_rejected() {
        let err = build_model(
            TreeBuilder::new().file(b"/".to_vec(), b"x".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert!(matches!(err, ModelError::RootNotDirectory { .. }));
    }

    #[test]
    fn a_second_root_entry_is_a_duplicate() {
        // `.` and `/` name the same directory, so the second is a duplicate — the same
        // rule every other path follows.
        let err = build_model(
            TreeBuilder::new()
                .root(meta(0o755))
                .directory(b".".to_vec(), meta(0o700)),
            config(),
        )
        .unwrap_err();
        assert!(matches!(err, ModelError::Duplicate { .. }));
    }

    #[test]
    fn an_error_message_names_the_path_as_text() {
        // A path is a byte string, and the message must read as one: the point of naming
        // the offending path is that the caller can find it.
        let err = build_model(
            TreeBuilder::new().file(b"/etc/hostname".to_vec(), b"x".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "path /etc/hostname has no parent directory"
        );

        // A path that is not UTF-8 still names itself, with the bytes it cannot render
        // replaced rather than the whole path withheld.
        let err = build_model(
            TreeBuilder::new().file(b"/\xff\xfe/x".to_vec(), b"x".to_vec(), meta(0o644)),
            config(),
        )
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "path /\u{fffd}\u{fffd}/x has no parent directory"
        );
    }
}