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
//! What populates a filesystem: the [`Source`] trait and a programmatic builder.
//!
//! A source yields a flat list of entries — a path, a kind, and the ownership,
//! mode, and timestamp to record — that the model turns into an inode tree. This
//! module defines that vocabulary and one source, the in-memory [`TreeBuilder`];
//! the archive and host-directory sources are separate, feature-gated
//! implementations of the same trait.
//!
//! A source states what it wants written; whether the current feature profile can
//! represent it is decided when the model consumes it. An input the profile cannot
//! hold — a name over 255 bytes, an unresolvable hard link — becomes a typed error
//! there, never a silently dropped or truncated entry.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::image_source::ImageFile;
use crate::path::canonical_key;
use crate::time::Timestamp;
use crate::xattr::Xattr;

/// A regular file's contents: bytes in memory, a range of a file on the host read at the
/// moment it is placed, a file in an image this crate reads, read the same way, or a length
/// alone, whose bytes a caller writing the image supplies.
///
/// The first two coexist in one entry list, deliberately. A source that maps an on-host archive
/// yields handles; a caller that computes an entry's bytes — rewriting one file of a tree
/// it is otherwise passing through — supplies them owned, in the same `Vec<SourceEntry>`.
///
/// # Why this is not just `Vec<u8>`
///
/// A format's peak memory is otherwise the sum of every file it writes, because every
/// file's bytes are built before the first block is placed. A handle defers the bytes
/// until the file is written, and a writer places a handle's bytes a window at a time, so
/// what a file costs in memory while it is placed is one window rather than its length.
///
/// The [`len`](Self::len) is known without reading, which is what lets the model check a
/// file against the `large_file` feature — and name the offending path — before any bytes
/// are read.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum FileContent {
    /// Bytes held in memory.
    Owned(Vec<u8>),
    /// A range of a file on the host, read when the content is placed.
    Range(FileRange),
    /// A file in an image this crate reads, read from the image when the content is placed:
    /// what an [`ImageSource`](crate::ImageSource) gives a regular file.
    Image(ImageFile),
    /// A file declared by its length alone. The source holds none of its bytes: a caller
    /// that writes the image itself puts them where the plan places the file, and knows the
    /// file by `key`, which it chose.
    ///
    /// Only a plan that hands its writes back to the caller can place one, which is the exFAT
    /// family's `FormatPlan::stages`. Every other family's writer reads a file's bytes itself,
    /// and refuses a declared one when the plan is made.
    Declared {
        /// The file's length in bytes.
        len: u64,
        /// The caller's name for the file, handed back with the place its bytes go.
        key: u64,
    },
}

/// The most bytes of one file a writer holds at once while placing it.
///
/// A whole number of blocks and sectors in every family, since each of those is a power of
/// two no larger than this, so a window boundary is never inside a block a writer has to
/// fill whole.
#[cfg(any(
    feature = "ext",
    feature = "fat",
    feature = "exfat",
    feature = "btrfs",
    feature = "apfs"
))]
pub(crate) const CONTENT_WINDOW: usize = 1 << 20;

impl FileContent {
    /// The file's length in bytes, without reading it.
    #[must_use]
    pub fn len(&self) -> u64 {
        match self {
            Self::Owned(bytes) => bytes.len() as u64,
            Self::Range(range) => range.len(),
            Self::Image(file) => file.len(),
            Self::Declared { len, .. } => *len,
        }
    }

    /// Fill `buf` with the file's bytes from offset `at` onward.
    ///
    /// The read names its own position, so a caller copying a large file through a buffer of
    /// its choosing holds that buffer and nothing else.
    ///
    /// # Errors
    ///
    /// [`std::io::ErrorKind::InvalidInput`] if `at` plus the buffer's length runs past the
    /// end of the file, and otherwise what [`FileRange::read_at`] reports for a range and
    /// [`ImageFile::read_at`] for a file in an image. An owned
    /// entry fails only on the bound. A declared one is [`std::io::ErrorKind::Unsupported`],
    /// since it has no bytes to read.
    pub fn read_at(&self, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
        match self {
            Self::Owned(bytes) => {
                let within = usize::try_from(at).ok().filter(|from| {
                    from.checked_add(buf.len())
                        .is_some_and(|end| end <= bytes.len())
                });
                let Some(from) = within else {
                    return Err(past_the_end(at, buf.len(), bytes.len() as u64));
                };
                buf.copy_from_slice(&bytes[from..from + buf.len()]);
                Ok(())
            }
            Self::Range(range) => range.read_at(at, buf),
            Self::Image(file) => file.read_at(at, buf),
            Self::Declared { key, .. } => Err(not_held(*key)),
        }
    }

    /// Hand the file's bytes to `each` in order, a window at a time: each window's offset
    /// within the file, and its bytes.
    ///
    /// Every window but the last is [`CONTENT_WINDOW`] bytes, so each offset is a multiple of
    /// it. Owned bytes are lent in place; a range is read into one buffer that every window
    /// reuses. An empty file calls `each` not at all.
    ///
    /// The ext, FAT and APFS writers call this, and the exFAT writer for a file in an image;
    /// for a range it holds the range's piece and reaches [`FileRange::for_each_window`]. The
    /// btrfs writer steps its extents by the window itself, through
    /// [`read_at`](Self::read_at).
    #[cfg(any(feature = "ext", feature = "fat", feature = "exfat", feature = "apfs"))]
    pub(crate) fn for_each_window<E: From<std::io::Error>>(
        &self,
        mut each: impl FnMut(u64, &[u8]) -> Result<(), E>,
    ) -> Result<(), E> {
        match self {
            Self::Owned(bytes) => {
                for (n, window) in bytes.chunks(CONTENT_WINDOW).enumerate() {
                    each((n * CONTENT_WINDOW) as u64, window)?;
                }
                Ok(())
            }
            Self::Range(range) => range.for_each_window(each),
            Self::Image(file) => windows(file.len(), |at, buf| file.read_at(at, buf), each),
            Self::Declared { len: 0, .. } => Ok(()),
            Self::Declared { key, .. } => Err(not_held(*key).into()),
        }
    }

    /// Whether the file is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The file's bytes, reading them from the host if they are not already in memory.
    ///
    /// Bytes already held are borrowed, not copied: reading an [`Owned`](Self::Owned)
    /// entry costs nothing, so a caller that reads every entry in turn never holds two
    /// copies of one file. Only a [`Range`](Self::Range) and an [`Image`](Self::Image)
    /// allocate, and only for as long as the caller keeps what it returned — the whole file
    /// at once, which [`read_at`](Self::read_at) is the bounded alternative to.
    ///
    /// # Errors
    ///
    /// [`std::io::Error`] if the backing file cannot be read — including the case where
    /// it is shorter than the range claims, which means the file changed after the source
    /// that named it was built. An owned entry cannot fail.
    pub fn read(&self) -> std::io::Result<Cow<'_, [u8]>> {
        match self {
            Self::Owned(bytes) => Ok(Cow::Borrowed(bytes)),
            Self::Range(range) => Ok(Cow::Owned(range.read()?)),
            Self::Image(file) => {
                let mut bytes = vec![
                    0u8;
                    usize::try_from(file.len()).map_err(|_| {
                        std::io::Error::new(
                            std::io::ErrorKind::OutOfMemory,
                            "a file in an image is larger than this machine addresses",
                        )
                    })?
                ];
                file.read_at(0, &mut bytes)?;
                Ok(Cow::Owned(bytes))
            }
            Self::Declared { key, .. } => Err(not_held(*key)),
        }
    }
}

impl From<Vec<u8>> for FileContent {
    fn from(bytes: Vec<u8>) -> Self {
        Self::Owned(bytes)
    }
}

impl From<FileRange> for FileContent {
    fn from(range: FileRange) -> Self {
        Self::Range(range)
    }
}

impl From<ImageFile> for FileContent {
    fn from(file: ImageFile) -> Self {
        Self::Image(file)
    }
}

// The borrowed forms of a file's bytes, each copied into an owned buffer. A caller writing
// a small file writes it as a literal — `b"ferrosys\n"`, `"#!/bin/sh\n"` — and having to
// spell `.to_vec()` on every one of them is noise that says nothing about the filesystem
// being built. `String` and `&str` are here because a text file is text; the bytes stored
// are the UTF-8 the string already holds, with no re-encoding.
impl From<&[u8]> for FileContent {
    fn from(bytes: &[u8]) -> Self {
        Self::Owned(bytes.to_vec())
    }
}

impl<const N: usize> From<&[u8; N]> for FileContent {
    fn from(bytes: &[u8; N]) -> Self {
        Self::Owned(bytes.to_vec())
    }
}

impl From<&str> for FileContent {
    fn from(text: &str) -> Self {
        Self::Owned(text.as_bytes().to_vec())
    }
}

impl From<String> for FileContent {
    fn from(text: String) -> Self {
        Self::Owned(text.into_bytes())
    }
}

/// A range of bytes within a file on the host, read at the moment the content is placed.
///
/// The handle is a plain owned value: no lifetime parameter reaches [`SourceEntry`], and a
/// caller may hold, clone, sort, and splice a list of them freely. Clones share what backs
/// them and may be read concurrently: every read names its own offset, so two reads of one
/// file never move a cursor the other depends on.
///
/// # Three forms, and what each costs
///
/// [`new`](Self::new) carries an open descriptor, shared, so a whole archive's worth of
/// ranges into one file costs one descriptor. [`at_path`](Self::at_path) carries only the
/// path and opens it for each read, which is what lets a source name a range in each of a
/// hundred thousand separate files without holding a descriptor for every one.
///
/// The third form is the one a walked host directory yields, and only the walk builds it. It
/// carries the walk's handle to the tree's root, the file's place beneath that root, and the
/// file's identity on the host. A read reaches the file from the root one name at a time,
/// following no symbolic link at any step, and refuses a file that is not the one the walk
/// recorded. So what reaches the image is a file the walk found inside the tree, whatever was
/// renamed or linked into the tree after it.
///
/// # The file must not change while the source is alive
///
/// The bytes are read when the file is placed, not when the source is built, so an edit in
/// between reaches the image — as wrong bytes rather than as an error, unless the file
/// shrank enough for the read to run short. The format's own destination is one such edit:
/// writing an image over a file its source reads truncates that file, and what is read back
/// is the image being written rather than the source.
///
/// Which edits reach it depends on the form. A held descriptor names an inode: a
/// replacement written to a new file and renamed into place leaves the original inode
/// readable and the format unaffected, and only an **in-place** modification or a
/// truncation of that inode is seen. A path is resolved afresh at each read, so whatever
/// the name resolves to then is what reaches the image. A walked file is the inode the walk
/// recorded or an error: an in-place modification is seen, and a replacement is refused.
#[derive(Clone)]
pub struct FileRange {
    /// Where the bytes are fetched from.
    backing: Backing,
    /// The path the bytes come from: what a range built from a descriptor names for
    /// diagnostics and identity, what one built by path opens, and what a walked file is
    /// called on the host.
    path: Arc<PathBuf>,
    offset: u64,
    len: u64,
}

/// What a [`FileRange`] reads its bytes through.
#[derive(Clone)]
enum Backing {
    /// An open descriptor, shared by every range into one file.
    Descriptor(Arc<File>),
    /// The range's path, opened at each read without following a final symbolic link.
    Path,
    /// A file a host directory walk recorded, reached again from the walk's root.
    #[cfg(all(feature = "dir", any(target_os = "linux", target_os = "android")))]
    Walked(crate::host::Walked),
}

impl FileRange {
    /// A handle to `len` bytes at `offset` in `file`, which was opened from `path`.
    ///
    /// The path is carried for diagnostics and identity; it is not re-opened, so the
    /// range keeps reading the file this descriptor names even if the path is replaced.
    #[must_use]
    pub fn new(file: Arc<File>, path: impl Into<PathBuf>, offset: u64, len: u64) -> Self {
        Self {
            backing: Backing::Descriptor(file),
            path: Arc::new(path.into()),
            offset,
            len,
        }
    }

    /// A handle to `len` bytes at `offset` in the file at `path`, opened when the range is
    /// read rather than now.
    ///
    /// This is the form for a source that names ranges in many separate files: it holds no
    /// descriptor, so the number of files it can name is unbounded. The cost is that the
    /// path is resolved at each read, so a file replaced under that name between building
    /// the source and formatting reaches the image. The final component is opened without
    /// following a symbolic link; the directories above it are resolved as any path is.
    #[must_use]
    pub fn at_path(path: impl Into<PathBuf>, offset: u64, len: u64) -> Self {
        Self {
            backing: Backing::Path,
            path: Arc::new(path.into()),
            offset,
            len,
        }
    }

    /// A handle to `len` bytes at `offset` in a file a host directory walk recorded, which
    /// is called `path` on the host.
    #[cfg(all(feature = "dir", any(target_os = "linux", target_os = "android")))]
    pub(crate) fn walked(
        walked: crate::host::Walked,
        path: impl Into<PathBuf>,
        offset: u64,
        len: u64,
    ) -> Self {
        Self {
            backing: Backing::Walked(walked),
            path: Arc::new(path.into()),
            offset,
            len,
        }
    }

    /// The path the backing file was opened from.
    #[must_use]
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    /// Byte offset of the range within the backing file.
    #[must_use]
    pub const fn offset(&self) -> u64 {
        self.offset
    }

    /// Length of the range in bytes.
    #[must_use]
    pub const fn len(&self) -> u64 {
        self.len
    }

    /// Whether the range is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Read the range's bytes.
    ///
    /// The whole range is read into one buffer of its length; [`read_at`](Self::read_at) is
    /// the same read a piece at a time.
    ///
    /// # Errors
    ///
    /// What [`read_at`](Self::read_at) reports, and an error naming the range if it is longer
    /// than this platform addresses in memory.
    pub fn read(&self) -> std::io::Result<Vec<u8>> {
        let len = usize::try_from(self.len).map_err(|_| {
            std::io::Error::other(format!(
                "{}: {} bytes at offset {} is more than this platform addresses",
                crate::escape::printable_path(&self.path),
                self.len,
                self.offset
            ))
        })?;
        let mut buf = vec![0u8; len];
        self.read_at(0, &mut buf)?;
        Ok(buf)
    }

    /// Fill `buf` with the range's bytes from `at` onward, `at` counting from the start of
    /// the range rather than of the file.
    ///
    /// Every failure names the path, the offset, and the length, since that is what a
    /// caller has to act on: the error surfaces through a family's own format error
    /// transparently, so what this message says is the whole of what a person sees. A
    /// short read in particular — the file changed after the source was built — is
    /// otherwise indistinguishable from any other truncation, and names neither the file
    /// that changed nor the range that was lost.
    ///
    /// A range named by path, or recorded by a walk, is opened afresh by each call, and a
    /// walked file is checked to be the file the walk recorded each time.
    ///
    /// # Errors
    ///
    /// [`std::io::ErrorKind::InvalidInput`] if `at` plus the buffer's length runs past the
    /// end of the range. Otherwise [`std::io::Error`] if the file cannot be opened or read,
    /// or if it is shorter than the range claims — which is what a file edited after the
    /// source was built looks like. A walked file that is no longer the file the walk
    /// recorded is an error too.
    pub fn read_at(&self, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
        let len = buf.len();
        let context = |e: std::io::Error| {
            std::io::Error::new(
                e.kind(),
                format!(
                    "{}: reading {len} bytes at offset {}: {e}",
                    crate::escape::printable_path(&self.path),
                    self.offset.saturating_add(at)
                ),
            )
        };
        let start = at
            .checked_add(len as u64)
            .filter(|end| *end <= self.len)
            .and_then(|_| self.offset.checked_add(at))
            .ok_or_else(|| context(past_the_end(at, len, self.len)))?;
        match &self.backing {
            Backing::Descriptor(file) => read_exact_at(file, buf, start),
            // Opened without following a final symbolic link. A walk records a symlink as a
            // symlink and never reads through one, and a caller naming files by path gets
            // the same promise for the last name: one replaced with a link between building
            // the source and the placement is an error rather than the target's bytes.
            Backing::Path => open_no_follow(self.path.as_path())
                .and_then(|file| read_exact_at(&file, buf, start)),
            #[cfg(all(feature = "dir", any(target_os = "linux", target_os = "android")))]
            Backing::Walked(walked) => walked
                .open()
                .and_then(|file| read_exact_at(&file, buf, start)),
        }
        .map_err(context)
    }

    /// Hand the range's bytes to `each` in order, a window at a time, through one buffer
    /// every window reuses: each window's offset within the range, and its bytes.
    ///
    /// Every window but the last is [`CONTENT_WINDOW`] bytes. An empty range calls `each`
    /// not at all.
    #[cfg(any(feature = "ext", feature = "fat", feature = "exfat", feature = "apfs"))]
    pub(crate) fn for_each_window<E: From<std::io::Error>>(
        &self,
        each: impl FnMut(u64, &[u8]) -> Result<(), E>,
    ) -> Result<(), E> {
        windows(self.len, |at, buf| self.read_at(at, buf), each)
    }
}

/// Hand `len` bytes that `read` fills to `each` in order, a window at a time, through one
/// buffer every window reuses: each window's offset, and its bytes. Every window but the last
/// is [`CONTENT_WINDOW`] bytes.
#[cfg(any(feature = "ext", feature = "fat", feature = "exfat", feature = "apfs"))]
fn windows<E: From<std::io::Error>>(
    len: u64,
    mut read: impl FnMut(u64, &mut [u8]) -> std::io::Result<()>,
    mut each: impl FnMut(u64, &[u8]) -> Result<(), E>,
) -> Result<(), E> {
    // Bounded by the window, so neither conversion can lose a value.
    let mut buffer = vec![0u8; len.min(CONTENT_WINDOW as u64) as usize];
    let mut at = 0u64;
    while at < len {
        let n = (len - at).min(CONTENT_WINDOW as u64) as usize;
        read(at, &mut buffer[..n])?;
        each(at, &buffer[..n])?;
        at += n as u64;
    }
    Ok(())
}

/// The error for a read of a file declared by its length alone, under `key`, which holds no
/// bytes to read.
fn not_held(key: u64) -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        format!("a file declared by its length alone, under key {key}, holds no bytes to read"),
    )
}

/// The error for a read of `len` bytes at `at` in contents `size` bytes long, which runs past
/// their end.
fn past_the_end(at: u64, len: usize, size: u64) -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::InvalidInput,
        format!("{len} bytes at {at} run past the end of {size} bytes of contents"),
    )
}

/// Fill `buf` from `file` at `offset`, at a position the read names rather than through
/// the descriptor's cursor.
///
/// Every range into one archive shares one open file, and a cursor belongs to the open file
/// rather than to a handle — a duplicated descriptor moves the same one — so a seek and then
/// a read are two steps another range's read can land between, and both then return the
/// wrong bytes. A positional read is one step and leaves no cursor for another read to move.
fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        std::os::unix::fs::FileExt::read_exact_at(file, buf, offset)
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::FileExt as _;
        // Each call reads at the offset it names, and may return fewer bytes than asked for
        // without being at the end, so the range is filled a call at a time.
        let mut done = 0;
        while done < buf.len() {
            let at = offset
                .checked_add(done as u64)
                .ok_or_else(|| std::io::Error::other("the range ends past the 64-bit range"))?;
            match file.seek_read(&mut buf[done..], at) {
                Ok(0) => return Err(std::io::ErrorKind::UnexpectedEof.into()),
                Ok(read) => done += read,
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    {
        use std::io::{Read as _, Seek as _};
        // A platform with no positional read: the seek and the read are made one step by
        // holding one lock across both, for every range there is.
        static CURSOR: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _held = CURSOR
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut file = file;
        file.seek(std::io::SeekFrom::Start(offset))?;
        file.read_exact(buf)
    }
}

/// Open a regular file by path without following a symbolic link at the end of it.
///
/// `O_NOFOLLOW` is not in the standard library's options, so the raw flag is set through the
/// Unix extension; on a platform with no such flag the plain open is what there is, and the
/// walk that produced the path is the same platform's.
fn open_no_follow(path: &Path) -> std::io::Result<File> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        std::fs::OpenOptions::new()
            .read(true)
            .custom_flags(o_nofollow())
            .open(path)
    }
    #[cfg(not(unix))]
    {
        File::open(path)
    }
}

/// `O_NOFOLLOW` for this target.
///
/// Spelled here rather than pulled from a C-binding crate, which this crate does not depend
/// on for one integer, and which is not compiled at all in the feature sets that carry no
/// host directory. The value is part of each kernel's stable syscall interface, and it is
/// one value per architecture rather than one value: Linux's generic definition is
/// `0o400000`, and arm, aarch64, m68k, powerpc and powerpc64 each define `0o100000` in its
/// place, where `0o400000` means `O_LARGEFILE` — a bit the kernel accepts and ignores, so
/// the generic value on one of those is an open that quietly follows the link. The BSDs
/// including macOS use `0x0100`, and the Solaris lineage the Linux generic value.
///
/// A unix target outside those families is a build failure rather than a guess: what a guess
/// costs is a read through a link, silently. The value is proved rather than asserted —
/// `a_link_is_refused_by_the_flag_this_target_defines` opens one on whatever target the suite
/// is running on.
#[cfg(unix)]
const fn o_nofollow() -> i32 {
    #[cfg(any(target_os = "linux", target_os = "android"))]
    {
        if cfg!(any(
            target_arch = "arm",
            target_arch = "aarch64",
            target_arch = "m68k",
            target_arch = "powerpc",
            target_arch = "powerpc64"
        )) {
            0o100_000
        } else {
            0o400_000
        }
    }
    #[cfg(any(target_os = "solaris", target_os = "illumos"))]
    {
        0o400_000
    }
    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "watchos",
        target_os = "visionos",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly"
    ))]
    {
        0x0100
    }
    #[cfg(not(any(
        target_os = "linux",
        target_os = "android",
        target_os = "solaris",
        target_os = "illumos",
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "watchos",
        target_os = "visionos",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly"
    )))]
    {
        compile_error!(
            "no O_NOFOLLOW value is known for this target, and an open that follows a \
             symbolic link would read through a name recorded as a link"
        );
        0
    }
}

impl PartialEq for FileRange {
    /// Two handles are equal when they name the same range of the same path. The open
    /// descriptors are not compared: a path re-opened is the same range by every measure
    /// a caller can act on.
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path && self.offset == other.offset && self.len == other.len
    }
}

impl Eq for FileRange {}

impl std::fmt::Debug for FileRange {
    /// The range, without the descriptor: `FileRange { path, offset, len }`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FileRange")
            .field("path", &self.path)
            .field("offset", &self.offset)
            .field("len", &self.len)
            .finish()
    }
}

/// Ownership, permission bits, and timestamps for one entry.
///
/// The `mode` is the permission and set-user/group/sticky bits only; the file-type
/// bits come from the entry's [`EntryKind`]. Access, change, and modification times
/// are carried independently, matching what ext4 stores and what an archive can
/// supply. A birth time is carried where the source states one: a tree read from an image
/// whose format records one states it, and a host directory, an archive and a built tree
/// state none. Every family's format has a field for one, and writes the modification time
/// there where none is stated; APFS writes the format's instant instead where the modification
/// time is before 1970 or after that instant, since macOS refuses to read an inode created
/// before 1970.
///
/// Built with [`new`](Self::new) and the builders beside it, or by assigning a public
/// field of a value one of them returned. The type is `#[non_exhaustive]`, so a field it
/// gains is an addition rather than a break.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Metadata {
    /// Permission and `setuid`/`setgid`/sticky bits (the low twelve bits of the
    /// mode).
    pub mode: u16,
    /// Owning user id.
    pub uid: u32,
    /// Owning group id.
    pub gid: u32,
    /// Access time (`atime`).
    pub atime: Timestamp,
    /// Change (status) time (`ctime`).
    pub ctime: Timestamp,
    /// Modification time (`mtime`).
    pub mtime: Timestamp,
    /// Birth time (`btime`): when the entry was created, where the source states it. A
    /// format writes the modification time in its place where it is [`None`], as the type's
    /// documentation says.
    pub btime: Option<Timestamp>,
}

/// The file-type bits of a mode (`S_IFMT`), which [`Metadata::mode`] must not carry: the
/// entry's [`EntryKind`] supplies them. Every model that writes POSIX modes refuses a
/// `mode` with any of these set, so a raw `st_mode` passed through whole is a typed error
/// rather than an inode carrying two file types.
#[cfg(any(feature = "ext", feature = "btrfs", feature = "apfs"))]
pub(crate) const MODE_TYPE_MASK: u16 = 0o170000;

impl Metadata {
    /// Metadata with the given permission bits, owned by root, whose access,
    /// change, and modification times are all `mtime` — the common case where one
    /// time is known.
    #[must_use]
    pub fn new(mode: u16, mtime: Timestamp) -> Self {
        Self {
            mode,
            uid: 0,
            gid: 0,
            atime: mtime,
            ctime: mtime,
            mtime,
            btime: None,
        }
    }

    /// Set the owning user and group.
    #[must_use]
    pub fn owned_by(mut self, uid: u32, gid: u32) -> Self {
        self.uid = uid;
        self.gid = gid;
        self
    }

    /// Set the access, change, and modification times independently, for a source
    /// that carries all three.
    #[must_use]
    pub fn with_times(mut self, atime: Timestamp, ctime: Timestamp, mtime: Timestamp) -> Self {
        self.atime = atime;
        self.ctime = ctime;
        self.mtime = mtime;
        self
    }

    /// Set the birth time, for a source that states one.
    #[must_use]
    pub fn with_birth_time(mut self, btime: Timestamp) -> Self {
        self.btime = Some(btime);
        self
    }
}

/// What an entry is: a regular file, directory, symlink, hard link, device node,
/// FIFO, or socket — the full set of POSIX file types ext4 represents.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum EntryKind {
    /// A directory.
    Directory,
    /// A regular file with the given contents, held in memory or read from the host
    /// when the file is placed.
    File(FileContent),
    /// A symbolic link to the given target path.
    Symlink(Vec<u8>),
    /// A hard link: another name for the entry already present at `target`, which may
    /// be of any kind but a directory, and may itself be a hard link.
    HardLink {
        /// Path of the existing entry this name also points at.
        target: Vec<u8>,
    },
    /// A character-special device node with the given major and minor numbers.
    CharDevice {
        /// Device major number.
        major: u32,
        /// Device minor number.
        minor: u32,
    },
    /// A block-special device node with the given major and minor numbers.
    BlockDevice {
        /// Device major number.
        major: u32,
        /// Device minor number.
        minor: u32,
    },
    /// A named pipe (FIFO).
    Fifo,
    /// A Unix-domain socket node.
    Socket,
}

/// One thing to place in the filesystem: where it goes, what it is, its metadata,
/// and any extended attributes.
///
/// Built with [`new`](Self::new), and [`with_xattrs`](Self::with_xattrs) where the entry
/// carries attributes. The type is `#[non_exhaustive]`, so a field it gains is an addition
/// rather than a break; its public fields stay readable and assignable.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct SourceEntry {
    /// Path from the filesystem root, e.g. `b"/etc/hostname"`. Leading and repeated
    /// slashes are ignored, as is a `.` component; a `..` component is rejected by the
    /// model. A path naming the root itself (`b"/"`) describes the root directory,
    /// whose metadata and extended attributes the model applies to inode 2.
    pub path: Vec<u8>,
    /// What to place at `path`.
    pub kind: EntryKind,
    /// Ownership, mode, and times.
    pub meta: Metadata,
    /// Extended attributes attached to this entry, each a fully-qualified name and
    /// its value in the boundary form [`Xattr`] describes. Empty for an entry with none.
    pub xattrs: Vec<Xattr>,
    /// What a Darwin filesystem records of the entry beyond the rest: its BSD flags, and a
    /// compressed file's content as stored. [`None`] for an entry from anywhere else.
    pub darwin: Option<Darwin>,
}

/// What a Darwin filesystem records of an entry that no other family's vocabulary holds.
///
/// APFS keeps it, as HFS+ does. Every other family writes the entry's decoded content as it
/// always has, and reports BSD flags it cannot hold as a loss, refusing them unless the caller
/// accepts it; a caller accepts it for one entry by clearing [`SourceEntry::darwin`].
#[derive(Clone, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct Darwin {
    /// The BSD flags `chflags` sets: `UF_HIDDEN`, `UF_NODUMP`, `UF_IMMUTABLE` and the rest.
    /// [`Darwin::COMPRESSED`] among them says the file's content is held compressed, which a
    /// [`compressed`](Self::compressed) form gives. A writer keeping the form takes the flag
    /// from it, set where a form is given and cleared where none is, whatever this field holds.
    pub bsd_flags: u32,
    /// A compressed file's content as the filesystem stores it, where the entry is one.
    ///
    /// A writer keeping the form writes it as the file's content and does not read the
    /// entry's own content, which it holds only to be as long as the form's header says. A
    /// caller changing an entry's content clears the form, or gives the form of the new
    /// content: a form left beside content of the same length is what is written.
    pub compressed: Option<CompressedFile>,
}

impl Darwin {
    /// `UF_COMPRESSED`: the flag a compressed file carries, and a storage detail rather than a
    /// property of the file. Its content is the same bytes compressed or not, so a family
    /// writing the content decoded loses nothing of it.
    pub const COMPRESSED: u32 = 0x20;

    /// A part holding `bsd_flags` and no compressed form.
    #[must_use]
    pub const fn new(bsd_flags: u32) -> Self {
        Self {
            bsd_flags,
            compressed: None,
        }
    }

    /// This part with `form` as the file's compressed content, and the flag that says so.
    #[must_use]
    pub fn compressed(mut self, form: CompressedFile) -> Self {
        self.bsd_flags |= Self::COMPRESSED;
        self.compressed = Some(form);
        self
    }

    /// The flags the entry states of itself: every one but [`COMPRESSED`](Self::COMPRESSED),
    /// which follows from the form its content is stored in. A Darwin filesystem keeps them;
    /// a family that holds no BSD flags loses them.
    #[must_use]
    pub const fn stated_flags(&self) -> u32 {
        self.bsd_flags & !Self::COMPRESSED
    }
}

/// A compressed file's content as a Darwin filesystem stores it: its compression header, the
/// `com.apple.decmpfs` attribute, and its resource fork, `com.apple.ResourceFork`, where the
/// compressed content is held there.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct CompressedFile {
    /// The compression header, which names the method and the decoded length and, for small
    /// content, holds it.
    pub header: Vec<u8>,
    /// The resource fork holding the compressed content, where the header does not.
    pub fork: Option<Vec<u8>>,
}

impl CompressedFile {
    /// A compressed form of `header` and, where the content is held there, `fork`.
    #[must_use]
    pub const fn new(header: Vec<u8>, fork: Option<Vec<u8>>) -> Self {
        Self { header, fork }
    }
}

impl SourceEntry {
    /// An entry placing `kind` at `path` with `meta`, carrying no extended attributes.
    #[must_use]
    pub fn new(path: impl Into<Vec<u8>>, kind: EntryKind, meta: Metadata) -> Self {
        Self {
            path: path.into(),
            kind,
            meta,
            xattrs: Vec::new(),
            darwin: None,
        }
    }

    /// Set the entry's extended attributes, replacing any it carries.
    #[must_use]
    pub fn with_xattrs(mut self, xattrs: Vec<Xattr>) -> Self {
        self.xattrs = xattrs;
        self
    }

    /// Set what a Darwin filesystem records of the entry, replacing any it carries.
    #[must_use]
    pub fn with_darwin(mut self, darwin: Darwin) -> Self {
        self.darwin = Some(darwin);
        self
    }
}

/// Something that produces the entries to write into a filesystem.
///
/// The model consumes a source once. An archive parser, a walk of a host directory, and
/// the in-memory [`TreeBuilder`] are all sources; the model does not care which.
///
/// # Why the entries are a `Vec` and not an iterator
///
/// Inode numbers are assigned in sorted path order, which is what makes two formats of the
/// same tree byte-identical — so the model sorts the whole list before it places anything.
/// The list is therefore materialized whatever a source hands over, and an iterator would
/// be collected on arrival rather than streamed.
///
/// What that costs is bounded by the entry *count*, not by the bytes: a regular file's
/// contents may be a [`FileContent::Range`], which is a path, an offset, and a length until
/// the file is placed. A tree of a million entries is tens of megabytes of entry records
/// however large the files in it are.
pub trait Source {
    /// Produce the entries, consuming the source.
    fn into_entries(self) -> Vec<SourceEntry>;
}

/// A list of entries is a source as it stands: what a caller that takes another source's
/// entries to look at them, or to change some, hands on to a format.
impl Source for Vec<SourceEntry> {
    fn into_entries(self) -> Vec<SourceEntry> {
        self
    }
}

/// An in-memory, programmatic source: add entries, then hand it to the model.
///
/// Order of addition does not affect the result — the model sorts by path so the
/// inode numbering is deterministic — but a directory's contents are only valid if
/// the directory itself is also added.
#[derive(Clone, Default, Debug)]
pub struct TreeBuilder {
    entries: Vec<SourceEntry>,
}

impl TreeBuilder {
    /// A builder with no entries. The root directory always exists implicitly and
    /// is not added here.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a directory at `path`.
    #[must_use]
    pub fn directory(mut self, path: impl Into<Vec<u8>>, meta: Metadata) -> Self {
        self.push(path, EntryKind::Directory, meta);
        self
    }

    /// Set the root directory's own metadata, overriding the `0755` root-owned default.
    ///
    /// The root already exists, so this describes it rather than adding an entry; any
    /// [`xattr`](Self::xattr) that follows attaches to the root. Naming it once is
    /// enough — a second root entry is a duplicate the model rejects.
    #[must_use]
    pub fn root(mut self, meta: Metadata) -> Self {
        self.push(b"/".to_vec(), EntryKind::Directory, meta);
        self
    }

    /// Add a regular file at `path` with `contents`.
    ///
    /// `contents` is anything that converts into a [`FileContent`]: an owned `Vec<u8>` or
    /// `String`, a borrowed `&[u8]`, `&[u8; N]`, or `&str` — each copied into the entry —
    /// or a [`FileRange`], which names bytes on the host and reads them when the file is
    /// placed rather than now.
    #[must_use]
    pub fn file(
        mut self,
        path: impl Into<Vec<u8>>,
        contents: impl Into<FileContent>,
        meta: Metadata,
    ) -> Self {
        self.push(path, EntryKind::File(contents.into()), meta);
        self
    }

    /// Add a symbolic link at `path` pointing at `target`.
    #[must_use]
    pub fn symlink(
        mut self,
        path: impl Into<Vec<u8>>,
        target: impl Into<Vec<u8>>,
        meta: Metadata,
    ) -> Self {
        self.push(path, EntryKind::Symlink(target.into()), meta);
        self
    }

    /// Add a hard link at `path` to the entry already declared at `target`, which may
    /// be of any kind but a directory, and may itself be a hard link.
    ///
    /// The link shares the target's inode, so the two names are one file: the
    /// metadata, extended attributes, and contents are the inode's, and the `meta`
    /// given here is not applied.
    #[must_use]
    pub fn hardlink(
        mut self,
        path: impl Into<Vec<u8>>,
        target: impl Into<Vec<u8>>,
        meta: Metadata,
    ) -> Self {
        self.push(
            path,
            EntryKind::HardLink {
                target: target.into(),
            },
            meta,
        );
        self
    }

    /// Add a character-special device node at `path`.
    #[must_use]
    pub fn char_device(
        mut self,
        path: impl Into<Vec<u8>>,
        major: u32,
        minor: u32,
        meta: Metadata,
    ) -> Self {
        self.push(path, EntryKind::CharDevice { major, minor }, meta);
        self
    }

    /// Add a block-special device node at `path`.
    #[must_use]
    pub fn block_device(
        mut self,
        path: impl Into<Vec<u8>>,
        major: u32,
        minor: u32,
        meta: Metadata,
    ) -> Self {
        self.push(path, EntryKind::BlockDevice { major, minor }, meta);
        self
    }

    /// Add a named pipe (FIFO) at `path`.
    #[must_use]
    pub fn fifo(mut self, path: impl Into<Vec<u8>>, meta: Metadata) -> Self {
        self.push(path, EntryKind::Fifo, meta);
        self
    }

    /// Add a Unix-domain socket node at `path`.
    #[must_use]
    pub fn socket(mut self, path: impl Into<Vec<u8>>, meta: Metadata) -> Self {
        self.push(path, EntryKind::Socket, meta);
        self
    }

    /// Attach an extended attribute to the most recently added entry.
    ///
    /// `name` is the fully-qualified attribute name (e.g. `b"security.capability"`).
    /// If no entry has been added yet, the call has no effect.
    #[must_use]
    pub fn xattr(mut self, name: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) -> Self {
        if let Some(entry) = self.entries.last_mut() {
            entry.xattrs.push(Xattr {
                name: name.into(),
                value: value.into(),
            });
        }
        self
    }

    fn push(&mut self, path: impl Into<Vec<u8>>, kind: EntryKind, meta: Metadata) {
        self.entries.push(SourceEntry::new(path, kind, meta));
    }
}

impl Source for TreeBuilder {
    fn into_entries(self) -> Vec<SourceEntry> {
        self.entries
    }
}

/// Several sources composed into one, where a later layer's entry replaces an earlier
/// layer's at the same path.
///
/// This is the shape an image build takes when a base tree is customized: a root
/// filesystem from an archive, then a directory of configuration over it, then a handful
/// of computed files over that. Each layer is a [`Source`] of any kind — they need not be
/// the same kind — and is consumed as it is added.
///
/// # What replacement means
///
/// A path present in more than one layer takes the last layer's entry whole: its kind, its
/// metadata, and its extended attributes, which replace the earlier set rather than merging
/// with it name by name. Paths are compared as the model compares them, so `/etc/hostname`
/// and `//etc//hostname` are one path and the second does replace the first.
///
/// A directory is the case where replacement is not the whole story. Its own entry is
/// replaced like any other, so the last layer decides its mode, ownership, times, and
/// attributes — but its *contents* are separate entries at their own paths, so a directory
/// named by two layers ends up holding the union of what each put in it. That is what makes
/// a configuration layer additive: naming `/etc` again does not empty it.
///
/// Replacing a directory with something that is not one is different: the entries beneath
/// it would have no directory to live in, so they are dropped along with it. A file at
/// `/etc` removes `/etc/hostname` from an earlier layer.
///
/// # Removing a path
///
/// A layer states what is present, so it replaces a path and leaves every other in place.
/// Taking a path out is [`remove`](Self::remove), a step of its own over what the layers so
/// far compose: the path goes, with everything beneath it, and a later layer may place it
/// again. A path nothing composed holds is refused, so a misspelled removal is an error
/// rather than a step that did nothing.
///
/// A name is what goes, and a file with another name keeps it. Where a hard link elsewhere
/// names a file that a removal, or a layer replacing a directory, takes away, the first of
/// the file's remaining names in path order holds the file whole — its content, metadata,
/// extended attributes and [`Darwin`] part — and every other remaining name links to that
/// one.
///
/// Nothing is validated here. A layer may name a path the model refuses — one holding a
/// `..` element, say — and the refusal comes from the model when the composed list is read,
/// naming the path the caller wrote.
///
/// # Example
///
/// ```
/// use ferrosys::ext::{EntryKind, LayeredSource, Metadata, Source, TreeBuilder, Timestamp};
///
/// let time = Timestamp::from_secs(1_700_000_000);
/// let base = TreeBuilder::new()
///     .directory(b"/etc".to_vec(), Metadata::new(0o755, time))
///     .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), Metadata::new(0o644, time))
///     .file(b"/etc/issue".to_vec(), b"welcome\n".to_vec(), Metadata::new(0o644, time));
/// let overlay = TreeBuilder::new()
///     .file(b"/etc/hostname".to_vec(), b"overlaid\n".to_vec(), Metadata::new(0o600, time));
///
/// let entries = LayeredSource::new().layer(base).layer(overlay).into_entries();
///
/// // Three paths: the overlay replaced one and added none.
/// assert_eq!(entries.len(), 3);
/// let hostname = entries.iter().find(|e| e.path == b"/etc/hostname").unwrap();
/// assert_eq!(hostname.meta.mode, 0o600);
/// assert!(matches!(&hostname.kind, EntryKind::File(c) if c.read().unwrap().as_ref() == b"overlaid\n"));
/// ```
#[derive(Clone, Default, Debug)]
pub struct LayeredSource {
    /// Entries by canonical path, so a later layer's entry replaces an earlier one and the
    /// ordered keys make a subtree a contiguous range.
    entries: BTreeMap<Vec<u8>, SourceEntry>,
}

impl LayeredSource {
    /// A composition with no layers, which yields no entries.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a layer over the ones already added, replacing their entries where the paths
    /// agree.
    ///
    /// The source is consumed here rather than held, so layers of different kinds compose
    /// and each layer's own cost is paid once. Order is the whole contract: the last call
    /// wins.
    #[must_use]
    pub fn layer(mut self, source: impl Source) -> Self {
        for entry in source.into_entries() {
            let key = canonical_key(&entry.path);
            // Something that is not a directory cannot hold the entries an earlier layer
            // put beneath this path, so they go with it.
            if !matches!(entry.kind, EntryKind::Directory) {
                let beneath = self.beneath(&key);
                self.drop_names(&beneath);
            }
            // A name replaced is a name that goes: the file it named keeps any other name it
            // has, so a hard link to it goes on naming that file rather than the entry that
            // replaces it. A directory replaced by a directory merges, and no link names one.
            if self
                .entries
                .get(&key)
                .is_some_and(|old| !matches!(old.kind, EntryKind::Directory))
            {
                self.drop_names(std::slice::from_ref(&key));
            }
            self.entries.insert(key, entry);
        }
        self
    }

    /// Remove `path` and everything beneath it from what the layers so far compose.
    ///
    /// Paths are compared as the model compares them, so `//etc//ssl` removes `/etc/ssl`. A
    /// file that has a name outside what is removed keeps that name, as the type's
    /// documentation describes.
    ///
    /// ```
    /// use ferrosys::{LayeredSource, Metadata, Source, Timestamp, TreeBuilder};
    ///
    /// let time = Timestamp::from_secs(1_700_000_000);
    /// let base = TreeBuilder::new()
    ///     .directory(b"/etc".to_vec(), Metadata::new(0o755, time))
    ///     .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), Metadata::new(0o644, time))
    ///     .file(b"/etc/issue".to_vec(), b"welcome\n".to_vec(), Metadata::new(0o644, time));
    ///
    /// let entries = LayeredSource::new().layer(base).remove("/etc/issue")?.into_entries();
    /// assert_eq!(entries.len(), 2);
    /// assert!(LayeredSource::new().remove("/etc").is_err(), "nothing holds /etc");
    /// # Ok::<(), ferrosys::RemovalError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`RemovalError::NotHeld`] when nothing composed is at `path` or beneath it, and
    /// [`RemovalError::Root`] when `path` names the root directory.
    pub fn remove(mut self, path: impl AsRef<[u8]>) -> Result<Self, RemovalError> {
        let path = path.as_ref();
        let key = canonical_key(path);
        if key.is_empty() {
            return Err(RemovalError::Root);
        }
        let mut doomed = self.beneath(&key);
        if self.entries.contains_key(&key) {
            doomed.push(key);
        }
        if doomed.is_empty() {
            return Err(RemovalError::NotHeld {
                path: path.to_vec(),
            });
        }
        self.drop_names(&doomed);
        Ok(self)
    }

    /// The keys strictly beneath `key`. The keys are canonical and ordered, so a subtree is
    /// the contiguous range beginning `key/` — and for the root, whose key is empty, that is
    /// every other key.
    fn beneath(&self, key: &[u8]) -> Vec<Vec<u8>> {
        let mut prefix = key.to_vec();
        if !prefix.is_empty() {
            prefix.push(b'/');
        }
        self.entries
            .range(prefix.clone()..)
            .take_while(|(k, _)| k.starts_with(&prefix))
            // The root's own key is inside its range, its prefix being empty.
            .filter(|(k, _)| k.as_slice() != key)
            .map(|(k, _)| k.clone())
            .collect()
    }

    /// Take the names `doomed` out, keeping each file they name that has a name outside them.
    ///
    /// A hard link is another name for the file at the end of its chain. Where that file's
    /// own name goes, the first surviving link to it in path order takes its entry whole and
    /// the other surviving links name that one; where only a link in the chain goes, the
    /// links past it name the file directly. A link whose chain ends at nothing, at a
    /// directory, or back on itself is left as written, for the model to refuse naming it.
    fn drop_names(&mut self, doomed: &[Vec<u8>]) {
        if doomed.is_empty() {
            return;
        }
        let doomed: std::collections::BTreeSet<&[u8]> = doomed.iter().map(Vec::as_slice).collect();
        // Each file a surviving link reaches through a doomed name, with those links in path
        // order.
        let mut reached: BTreeMap<Vec<u8>, Vec<Vec<u8>>> = BTreeMap::new();
        for (key, entry) in &self.entries {
            let EntryKind::HardLink { target } = &entry.kind else {
                continue;
            };
            if doomed.contains(key.as_slice()) {
                continue;
            }
            let through = std::cell::Cell::new(false);
            let end = follow_hard_link(target, self.entries.len(), |at| {
                if doomed.contains(at) {
                    through.set(true);
                }
                match self.entries.get(at).map(|e| &e.kind) {
                    None => LinkStep::Missing,
                    Some(EntryKind::Directory) => LinkStep::Directory,
                    Some(EntryKind::HardLink { target }) => LinkStep::Link(canonical_key(target)),
                    Some(_) => LinkStep::File(at.to_vec()),
                }
            });
            if let LinkEnd::File(file) = end
                && through.get()
            {
                reached.entry(file).or_default().push(key.clone());
            }
        }
        for (file, links) in reached {
            let target = if doomed.contains(file.as_slice()) {
                let held = self.entries[&file].clone();
                let holder = self
                    .entries
                    .get_mut(&links[0])
                    .expect("a surviving link is composed");
                holder.kind = held.kind;
                holder.meta = held.meta;
                holder.xattrs = held.xattrs;
                holder.darwin = held.darwin;
                holder.path.clone()
            } else {
                self.entries[&file].path.clone()
            };
            for link in &links {
                let entry = self
                    .entries
                    .get_mut(link)
                    .expect("a surviving link is composed");
                if let EntryKind::HardLink { target: named } = &mut entry.kind {
                    named.clone_from(&target);
                }
            }
        }
        for key in doomed {
            self.entries.remove(key);
        }
    }

    /// The number of distinct paths the layers hold between them.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the composition holds no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Source for LayeredSource {
    /// The composed entries, each path once, carrying the path the layer that won wrote
    /// rather than the canonical form used to compare them — so a model error names what
    /// the caller typed.
    fn into_entries(self) -> Vec<SourceEntry> {
        self.entries.into_values().collect()
    }
}

/// A removal [`LayeredSource::remove`] refused.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RemovalError {
    /// Nothing the layers compose is at the path or beneath it: a misspelled path, or one an
    /// earlier step already took out.
    #[error("nothing is at {} or beneath it to remove", crate::escape::printable(.path))]
    #[non_exhaustive]
    NotHeld {
        /// The path, as the caller wrote it.
        path: Vec<u8>,
    },
    /// The path names the root directory, which every filesystem holds.
    #[error("the root directory is part of every filesystem and is not removed")]
    Root,
}

/// A fault a path has whatever format is being asked to hold it.
#[cfg(any(
    feature = "fat",
    feature = "exfat",
    feature = "btrfs",
    feature = "apfs"
))]
pub(crate) enum PathFault {
    /// A component was `..`, which a source may not use — a path is where an entry goes, not a
    /// traversal to be resolved.
    Traversal,
    /// Two entries resolve to one path.
    Duplicate,
    /// An entry naming the root is not a directory. The root is a directory, so an entry that
    /// would place anything else there describes a filesystem that cannot exist.
    RootNotDirectory,
}

/// A classification that stopped: at a fault in a path, or at whatever the family decided about
/// what the entry holds.
#[cfg(any(
    feature = "fat",
    feature = "exfat",
    feature = "btrfs",
    feature = "apfs"
))]
pub(crate) enum ClassifyError<E> {
    /// A fault in a path, with the path as the caller wrote it — so a message names that rather
    /// than the canonical form used to compare it.
    Path(PathFault, Vec<u8>),
    /// The family refused what the entry holds.
    Class(E),
}

/// Decide what every declared path holds, refusing the faults a path has whatever format is
/// being asked to hold it.
///
/// One walk rather than one per family, for the reason the hard-link walk below is one: *which*
/// faults a path can have, and the rule that decides which components it even has, are
/// properties of a source rather than of any format. What each path *holds* is the family's, which is what
/// `class_of` answers — and it is handed the components rather than the path, so a family that
/// bounds a name checks the components this pass already split rather than splitting them again.
///
/// The pass exists because a hard link may name a target that sorts after it: nothing can be
/// placed until every path is known.
#[cfg(any(
    feature = "fat",
    feature = "exfat",
    feature = "btrfs",
    feature = "apfs"
))]
pub(crate) fn classify_paths<C, E>(
    entries: &[SourceEntry],
    mut class_of: impl FnMut(&SourceEntry, &[&[u8]]) -> Result<C, E>,
    is_directory: impl Fn(&C) -> bool,
) -> Result<BTreeMap<Vec<u8>, C>, ClassifyError<E>> {
    let mut classes = BTreeMap::new();
    for entry in entries {
        // Split once and key from the same parts, rather than joining a key and taking it apart
        // again: which components a path has is one rule, and asking it twice is two chances to
        // disagree about what this path even is.
        let parts = crate::path::canonical_parts(&entry.path);
        if parts.iter().any(|part| *part == b"..") {
            return Err(ClassifyError::Path(
                PathFault::Traversal,
                entry.path.clone(),
            ));
        }
        let key = parts.join(&b'/');
        if classes.contains_key(&key) {
            return Err(ClassifyError::Path(
                PathFault::Duplicate,
                entry.path.clone(),
            ));
        }
        let class = class_of(entry, &parts).map_err(ClassifyError::Class)?;
        if key.is_empty() && !is_directory(&class) {
            return Err(ClassifyError::Path(
                PathFault::RootNotDirectory,
                entry.path.clone(),
            ));
        }
        classes.insert(key, class);
    }
    Ok(classes)
}

/// What a source declares at one path, as far as following a hard link is concerned.
///
/// The file arm carries whatever the caller needs of the file it found, so a walk that ends at
/// one hands it back rather than leaving the caller to look the path up a second time.
pub(crate) enum LinkStep<T> {
    /// A regular file: the chain ends here, with what the caller keeps of it.
    File(T),
    /// A directory, which no filesystem lets a hard link name.
    Directory,
    /// Something the target format cannot hold, so there is nothing left to be a second name
    /// for. A format that holds every kind of entry, as APFS does, never answers this.
    #[cfg_attr(not(any(feature = "fat", feature = "exfat")), allow(dead_code))]
    Unrepresentable,
    /// Another hard link, naming this canonical key.
    Link(Vec<u8>),
    /// Nothing is declared at this path.
    Missing,
}

/// Where a chain of hard links ends.
pub(crate) enum LinkEnd<T> {
    /// A file, with what the caller keeps of it.
    File(T),
    /// Something the target format cannot hold.
    Unrepresentable,
    /// A directory.
    Directory,
    /// Nothing at all.
    Missing,
    /// The chain returns to somewhere it has been, so no end of it names a file.
    Cycle,
}

/// Follow the chain of hard links beginning at `target` to whatever is at its end.
///
/// A link may name another link, so this is a walk rather than a lookup — and one that has to
/// terminate on a source that names a cycle. `declared` is how many paths the source declares,
/// which is what bounds it: every step consumes one declared path, so a walk longer than that
/// has come back to somewhere it has been.
///
/// One walk for every family and for [`LayeredSource`], which follows a link to the file a
/// removed name leaves. What a caller does with each outcome is its own — the refusals are a
/// family's error taxonomy, and what it keeps of a file is its own value — but *which*
/// outcomes there are, and the bound that makes a cycle terminate rather than hang, are
/// properties of a source and not of any format.
///
/// Nothing here reads a file or resolves a path outside the source: `target` names something
/// the same source declared, which is why a hard link can be written as a second copy at all.
pub(crate) fn follow_hard_link<T>(
    target: &[u8],
    declared: usize,
    step: impl Fn(&[u8]) -> LinkStep<T>,
) -> LinkEnd<T> {
    let mut at = canonical_key(target);
    let mut seen = 0usize;
    loop {
        match step(&at) {
            LinkStep::File(found) => return LinkEnd::File(found),
            LinkStep::Directory => return LinkEnd::Directory,
            LinkStep::Unrepresentable => return LinkEnd::Unrepresentable,
            LinkStep::Missing => return LinkEnd::Missing,
            LinkStep::Link(next) => {
                seen += 1;
                if seen > declared {
                    return LinkEnd::Cycle;
                }
                at = next;
            }
        }
    }
}

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

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

    #[test]
    fn builder_collects_entries_in_addition_order() {
        let src = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"host\n".to_vec(), meta())
            .symlink(b"/etc/mtab".to_vec(), b"/proc/mounts".to_vec(), meta());
        let entries = src.into_entries();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].path, b"/etc");
        assert!(matches!(entries[1].kind, EntryKind::File(_)));
        assert!(matches!(entries[2].kind, EntryKind::Symlink(_)));
    }

    #[test]
    fn an_entry_built_by_its_constructor_is_the_one_the_builder_adds() {
        let built = SourceEntry::new(b"/etc/hostname".to_vec(), EntryKind::Fifo, meta());
        assert!(built.xattrs.is_empty());
        let added = TreeBuilder::new()
            .fifo(b"/etc/hostname".to_vec(), meta())
            .into_entries();
        assert_eq!(added, vec![built.clone()]);

        let attribute = Xattr {
            name: b"user.a".to_vec(),
            value: b"1".to_vec(),
        };
        let carried = built.with_xattrs(vec![attribute.clone()]);
        assert_eq!(carried.xattrs, vec![attribute.clone()]);
        // Setting the list replaces it rather than appending to it.
        let replaced = carried.with_xattrs(Vec::new());
        assert!(replaced.xattrs.is_empty());
    }

    /// The paths a composition yields, in order, as readable strings.
    fn paths(source: LayeredSource) -> Vec<String> {
        source
            .into_entries()
            .into_iter()
            .map(|e| String::from_utf8_lossy(&e.path).into_owned())
            .collect()
    }

    /// The contents of the regular file at `path`.
    fn contents_at(entries: &[SourceEntry], path: &[u8]) -> Vec<u8> {
        let entry = entries
            .iter()
            .find(|e| e.path == path)
            .expect("path is present");
        match &entry.kind {
            EntryKind::File(c) => c.read().expect("read").into_owned(),
            other => panic!("expected a file, got {other:?}"),
        }
    }

    #[test]
    fn a_later_layer_replaces_an_earlier_entry_whole() {
        let base = TreeBuilder::new()
            .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta())
            .xattr(b"user.from".to_vec(), b"base".to_vec());
        let over = TreeBuilder::new()
            .file(
                b"/etc/hostname".to_vec(),
                b"over\n".to_vec(),
                Metadata::new(0o600, meta().mtime),
            )
            .xattr(b"user.other".to_vec(), b"over".to_vec());

        let entries = LayeredSource::new().layer(base).layer(over).into_entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(contents_at(&entries, b"/etc/hostname"), b"over\n");
        assert_eq!(entries[0].meta.mode, 0o600);
        // The attributes are the later layer's set, not the union of the two.
        assert_eq!(entries[0].xattrs.len(), 1);
        assert_eq!(entries[0].xattrs[0].name, b"user.other");
    }

    #[test]
    fn naming_a_directory_again_does_not_empty_it() {
        // What makes a configuration layer additive: the later layer decides the
        // directory's own metadata, and the two layers' contents merge.
        let base = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta());
        let over = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o700, meta().mtime))
            .file(b"/etc/issue".to_vec(), b"over\n".to_vec(), meta());

        let composed = LayeredSource::new().layer(base).layer(over);
        assert_eq!(
            paths(composed.clone()),
            ["/etc", "/etc/hostname", "/etc/issue"]
        );
        let entries = composed.into_entries();
        assert_eq!(entries[0].meta.mode, 0o700, "the later layer's mode");
    }

    #[test]
    fn replacing_a_directory_with_a_file_drops_what_was_beneath_it() {
        let base = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta())
            .directory(b"/etc/ssl".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/ssl/cert".to_vec(), b"pem\n".to_vec(), meta())
            // A sibling whose name shares the replaced path's bytes but not its subtree.
            .file(b"/etcetera".to_vec(), b"kept\n".to_vec(), meta());
        let over = TreeBuilder::new().file(b"/etc".to_vec(), b"now a file\n".to_vec(), meta());

        // Everything under /etc goes with it; /etcetera is not under /etc and stays.
        assert_eq!(
            paths(LayeredSource::new().layer(base).layer(over)),
            ["/etc", "/etcetera"]
        );
    }

    #[test]
    fn a_directory_over_a_file_keeps_the_directory() {
        let base = TreeBuilder::new().file(b"/etc".to_vec(), b"a file\n".to_vec(), meta());
        let over = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"over\n".to_vec(), meta());

        let entries = LayeredSource::new().layer(base).layer(over).into_entries();
        assert_eq!(entries.len(), 2);
        assert!(matches!(entries[0].kind, EntryKind::Directory));
    }

    #[test]
    fn paths_that_spell_one_path_are_one_path() {
        // The model treats these three as one, so layering has to as well: otherwise the
        // replacement silently does not happen and the model sees a duplicate.
        let base = TreeBuilder::new().file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta());
        let over = TreeBuilder::new().file(b"//etc//hostname".to_vec(), b"over\n".to_vec(), meta());
        let last = TreeBuilder::new().file(b"etc/./hostname".to_vec(), b"last\n".to_vec(), meta());

        let entries = LayeredSource::new()
            .layer(base)
            .layer(over)
            .layer(last)
            .into_entries();
        assert_eq!(entries.len(), 1, "three spellings of one path");
        // The path is the winning layer's own spelling, so a model error names what the
        // caller wrote rather than a form it never used.
        assert_eq!(entries[0].path, b"etc/./hostname");
        assert_eq!(contents_at(&entries, b"etc/./hostname"), b"last\n");
    }

    #[test]
    fn the_root_is_a_path_like_any_other() {
        let base = TreeBuilder::new()
            .root(Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta());
        let over = TreeBuilder::new().root(Metadata::new(0o700, meta().mtime));

        let composed = LayeredSource::new().layer(base).layer(over);
        assert_eq!(paths(composed.clone()), ["/", "/etc/hostname"]);
        assert_eq!(
            composed.into_entries()[0].meta.mode,
            0o700,
            "the later root's mode, and the tree beneath it kept"
        );
    }

    #[test]
    fn a_removal_takes_the_path_and_everything_beneath_it() {
        let base = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta())
            .directory(b"/etc/ssl".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/ssl/cert".to_vec(), b"pem\n".to_vec(), meta())
            // Siblings whose names share the removed path's bytes but not its subtree.
            .file(b"/etc/ssl-old".to_vec(), b"kept\n".to_vec(), meta())
            .file(b"/etcetera".to_vec(), b"kept\n".to_vec(), meta());

        let composed = LayeredSource::new()
            .layer(base)
            .remove(b"//etc//ssl/.")
            .expect("held");
        assert_eq!(
            paths(composed.clone()),
            ["/etc", "/etc/hostname", "/etc/ssl-old", "/etcetera"],
            "a spelling of the path the model takes as it"
        );
        assert_eq!(paths(composed.remove("/etc").expect("held")), ["/etcetera"]);
    }

    #[test]
    fn a_removal_of_nothing_is_refused_naming_the_path_written() {
        let base = TreeBuilder::new().file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta());
        let composed = LayeredSource::new().layer(base);
        assert_eq!(
            composed.clone().remove("/etc/hostnmae").err(),
            Some(RemovalError::NotHeld {
                path: b"/etc/hostnmae".to_vec()
            })
        );
        // Once removed, a path is not there to remove again.
        let once = composed.clone().remove("/etc/hostname").expect("held");
        assert!(matches!(
            once.remove("/etc/hostname"),
            Err(RemovalError::NotHeld { .. })
        ));
        // An undeclared directory holding a declared entry is held: its subtree goes.
        assert!(composed.clone().remove("/etc").expect("held").is_empty());
        for root in ["/", "", "//.", "."] {
            assert_eq!(
                composed.clone().remove(root).err(),
                Some(RemovalError::Root),
                "{root:?}"
            );
        }
        let message = LayeredSource::new()
            .remove(b"/a\x1b[2J")
            .expect_err("nothing")
            .to_string();
        assert!(
            !message.contains('\x1b'),
            "the path is escaped: {message:?}"
        );
    }

    #[test]
    fn a_later_layer_replacing_one_name_of_a_linked_file_leaves_the_other_its_file() {
        // `/etc/b` is a second name for `/etc/a`'s file. An overlay replacing `/etc/a` replaces
        // a name, and the file it named keeps `/etc/b`: the overlay's content goes to `/etc/a`
        // alone, and `/etc/b` holds what it held.
        let time = meta().mtime;
        let base = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, time))
            .file(
                b"/etc/a".to_vec(),
                b"OLD".to_vec(),
                Metadata::new(0o644, time),
            )
            .hardlink(
                b"/etc/b".to_vec(),
                b"/etc/a".to_vec(),
                Metadata::new(0o644, time),
            );
        let over = TreeBuilder::new().file(
            b"/etc/a".to_vec(),
            b"NEW".to_vec(),
            Metadata::new(0o600, time),
        );
        let entries = LayeredSource::new().layer(base).layer(over).into_entries();
        let content = |path: &[u8]| {
            let entry = entries.iter().find(|e| e.path == path).expect("the entry");
            match &entry.kind {
                EntryKind::File(c) => (c.read().unwrap().as_ref().to_vec(), entry.meta.mode),
                other => panic!("{} is {other:?}", String::from_utf8_lossy(path)),
            }
        };
        assert_eq!(content(b"/etc/a"), (b"NEW".to_vec(), 0o600));
        assert_eq!(content(b"/etc/b"), (b"OLD".to_vec(), 0o644));
    }

    #[test]
    fn a_later_layer_places_a_removed_path_again() {
        let base = TreeBuilder::new().file(b"/motd".to_vec(), b"base\n".to_vec(), meta());
        let over = TreeBuilder::new().file(b"/motd".to_vec(), b"over\n".to_vec(), meta());
        let entries = LayeredSource::new()
            .layer(base)
            .remove("/motd")
            .expect("held")
            .layer(over)
            .into_entries();
        assert_eq!(contents_at(&entries, b"/motd"), b"over\n");
    }

    /// The kind of the entry at `path`, which must be present.
    fn kind_at<'a>(entries: &'a [SourceEntry], path: &[u8]) -> &'a EntryKind {
        &entries
            .iter()
            .find(|e| e.path == path)
            .unwrap_or_else(|| panic!("{} is present", String::from_utf8_lossy(path)))
            .kind
    }

    #[test]
    fn a_file_whose_name_is_removed_keeps_its_other_names() {
        let held = meta().owned_by(501, 20);
        let base = TreeBuilder::new()
            .file(b"/a".to_vec(), b"x".to_vec(), held)
            .xattr(b"user.k".to_vec(), b"v".to_vec())
            .hardlink(b"/c".to_vec(), b"/a".to_vec(), meta())
            .hardlink(b"/b".to_vec(), b"/a".to_vec(), meta())
            .into_entries();
        let mut base = base;
        base[0].darwin = Some(Darwin::new(0x8000));

        let entries = LayeredSource::new()
            .layer(base)
            .remove("/a")
            .expect("held")
            .into_entries();
        // The first remaining name in path order holds the file whole, the other names it.
        let b = entries.iter().find(|e| e.path == b"/b").expect("kept");
        assert_eq!(contents_at(&entries, b"/b"), b"x");
        assert_eq!(b.meta, held);
        assert_eq!(b.xattrs.len(), 1);
        assert_eq!(b.darwin, Some(Darwin::new(0x8000)));
        assert_eq!(
            kind_at(&entries, b"/c"),
            &EntryKind::HardLink {
                target: b"/b".to_vec()
            }
        );
        assert_eq!(entries.len(), 2);
    }

    #[test]
    fn a_link_past_a_removed_link_names_the_file() {
        let base = TreeBuilder::new()
            .file(b"/a".to_vec(), b"x".to_vec(), meta())
            .hardlink(b"/b".to_vec(), b"/a".to_vec(), meta())
            .hardlink(b"/c".to_vec(), b"//b".to_vec(), meta())
            // A link whose chain reaches nothing is left as written, for the model to refuse.
            .hardlink(b"/d".to_vec(), b"/nowhere".to_vec(), meta());
        let entries = LayeredSource::new()
            .layer(base)
            .remove("/b")
            .expect("held")
            .into_entries();
        assert_eq!(
            kind_at(&entries, b"/c"),
            &EntryKind::HardLink {
                target: b"/a".to_vec()
            }
        );
        assert_eq!(
            kind_at(&entries, b"/d"),
            &EntryKind::HardLink {
                target: b"/nowhere".to_vec()
            }
        );
    }

    #[test]
    fn a_file_beneath_a_replaced_directory_keeps_its_name_outside_it() {
        let base = TreeBuilder::new()
            .directory(b"/etc".to_vec(), Metadata::new(0o755, meta().mtime))
            .file(b"/etc/hostname".to_vec(), b"base\n".to_vec(), meta())
            .hardlink(b"/hostname".to_vec(), b"/etc/hostname".to_vec(), meta());
        let removed = LayeredSource::new()
            .layer(base.clone())
            .remove("/etc")
            .expect("held")
            .into_entries();
        assert_eq!(contents_at(&removed, b"/hostname"), b"base\n");

        let over = TreeBuilder::new().file(b"/etc".to_vec(), b"a file\n".to_vec(), meta());
        let replaced = LayeredSource::new().layer(base).layer(over).into_entries();
        assert_eq!(contents_at(&replaced, b"/hostname"), b"base\n");
        assert_eq!(contents_at(&replaced, b"/etc"), b"a file\n");
    }

    #[test]
    fn a_layer_over_nothing_is_that_layer() {
        let one = TreeBuilder::new().file(b"/a".to_vec(), b"x".to_vec(), meta());
        assert_eq!(paths(LayeredSource::new().layer(one)), ["/a"]);
        assert!(LayeredSource::new().is_empty());
        assert_eq!(LayeredSource::new().len(), 0);
    }

    #[test]
    fn metadata_ownership_builder() {
        let m = Metadata::new(0o600, Timestamp::from_secs(0)).owned_by(1000, 1000);
        assert_eq!(m.uid, 1000);
        assert_eq!(m.gid, 1000);
        assert_eq!(m.mode, 0o600);
    }

    #[test]
    fn hardlink_records_its_target() {
        let src = TreeBuilder::new()
            .file(b"/a".to_vec(), b"x".to_vec(), meta())
            .hardlink(b"/b".to_vec(), b"/a".to_vec(), meta());
        let entries = src.into_entries();
        match &entries[1].kind {
            EntryKind::HardLink { target } => assert_eq!(target, b"/a"),
            other => panic!("expected hardlink, got {other:?}"),
        }
    }

    #[test]
    fn device_fifo_and_socket_kinds_are_recorded() {
        let entries = TreeBuilder::new()
            .char_device(b"/dev/null".to_vec(), 1, 3, meta())
            .block_device(b"/dev/sda".to_vec(), 8, 0, meta())
            .fifo(b"/run/pipe".to_vec(), meta())
            .socket(b"/run/sock".to_vec(), meta())
            .into_entries();
        assert!(matches!(
            entries[0].kind,
            EntryKind::CharDevice { major: 1, minor: 3 }
        ));
        assert!(matches!(
            entries[1].kind,
            EntryKind::BlockDevice { major: 8, minor: 0 }
        ));
        assert!(matches!(entries[2].kind, EntryKind::Fifo));
        assert!(matches!(entries[3].kind, EntryKind::Socket));
    }

    #[test]
    fn xattr_attaches_to_the_most_recent_entry() {
        let entries = TreeBuilder::new()
            .file(b"/bin/ping".to_vec(), b"elf".to_vec(), meta())
            .xattr(b"security.capability".to_vec(), vec![1, 2, 3, 4])
            .xattr(b"user.note".to_vec(), b"hi".to_vec())
            .file(b"/plain".to_vec(), b"x".to_vec(), meta())
            .into_entries();
        assert_eq!(entries[0].xattrs.len(), 2);
        assert_eq!(entries[0].xattrs[0].name, b"security.capability");
        assert!(entries[1].xattrs.is_empty());
    }

    #[test]
    fn xattr_without_a_preceding_entry_is_a_no_op() {
        let entries = TreeBuilder::new()
            .xattr(b"user.orphan".to_vec(), b"v".to_vec())
            .into_entries();
        assert!(entries.is_empty());
    }

    #[test]
    fn every_borrowed_form_of_a_files_bytes_converts() {
        // A caller writing a small file writes it as a literal. Each of these is a shape a
        // literal takes, and every one must reach the same owned entry — an argument that
        // has to be spelled `.to_vec()` is a bound that lost a caller nothing but noise.
        let want = EntryKind::File(FileContent::Owned(b"hi".to_vec()));
        let entries = TreeBuilder::new()
            .file(b"/vec".to_vec(), b"hi".to_vec(), meta())
            .file(b"/array".to_vec(), b"hi", meta())
            .file(b"/slice".to_vec(), &b"hi"[..], meta())
            .file(b"/str".to_vec(), "hi", meta())
            .file(b"/string".to_vec(), String::from("hi"), meta())
            .into_entries();
        assert_eq!(entries.len(), 5);
        for entry in &entries {
            assert_eq!(
                entry.kind,
                want,
                "{} converted to something else",
                String::from_utf8_lossy(&entry.path)
            );
        }
    }

    #[test]
    fn reading_owned_contents_borrows_rather_than_copies() {
        // The whole point of holding contents by value is that a format pays for them
        // once. A read that cloned would double the largest file's cost at exactly the
        // moment its blocks are being chunked, which is the peak the type exists to
        // lower. Pointer identity is what proves no copy happened.
        let content = FileContent::Owned(vec![9u8; 64]);
        let FileContent::Owned(held) = &content else {
            unreachable!("the content is owned")
        };
        let read = content.read().expect("an owned read cannot fail");
        assert!(matches!(read, std::borrow::Cow::Borrowed(_)));
        assert!(std::ptr::eq(read.as_ptr(), held.as_ptr()));
    }

    #[test]
    fn a_short_backing_file_names_itself_and_the_range() {
        // A file replaced in place between building the source and formatting is what
        // this error means, and the message is all a caller gets: `FormatError::Io` is
        // transparent, so a bare "failed to fill whole buffer" would name neither the
        // file that changed nor the bytes that went missing.
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("shrunk.tar");
        std::fs::write(&path, b"only eight").expect("write the backing file");
        let file = Arc::new(File::open(&path).expect("open the backing file"));

        let range = FileRange::new(Arc::clone(&file), &path, 4, 4096);
        let err = range
            .read()
            .expect_err("a range past the end cannot be read");
        let text = err.to_string();
        assert!(text.contains("shrunk.tar"), "{text}");
        assert!(text.contains("4096"), "{text}");
        assert!(text.contains("offset 4"), "{text}");
        // The kind survives the added context, so a caller can still tell a truncation
        // from a permission failure without matching on the message.
        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);

        // A range the file does hold reads its bytes, and reading allocates.
        let content = FileContent::Range(FileRange::new(file, &path, 5, 5));
        let read = content.read().expect("read the range");
        assert!(matches!(read, std::borrow::Cow::Owned(_)));
        assert_eq!(read.as_ref(), b"eight");
    }

    #[test]
    fn a_positional_read_counts_from_the_start_of_the_range_and_stops_at_its_end() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("archive");
        std::fs::write(&path, b"leadXYZABCtrail").expect("write the backing file");
        let range = FileContent::Range(FileRange::at_path(&path, 4, 6));
        let owned = FileContent::Owned(b"XYZABC".to_vec());

        for content in [&range, &owned] {
            let mut buf = [0u8; 3];
            content.read_at(2, &mut buf).expect("inside the contents");
            assert_eq!(&buf, b"ZAB", "{content:?}");
            content
                .read_at(3, &mut buf)
                .expect("ending at the last byte");
            assert_eq!(&buf, b"ABC", "{content:?}");

            // One byte past the end is refused rather than read from what follows the range
            // in its file, or answered short.
            let err = content.read_at(4, &mut buf).expect_err("past the end");
            assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput, "{content:?}");
            let err = content
                .read_at(u64::MAX, &mut buf)
                .expect_err("an offset that wraps");
            assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput, "{content:?}");
        }
    }

    #[test]
    fn a_declared_file_has_a_length_and_no_bytes_to_read() {
        let content = FileContent::Declared { len: 300, key: 42 };
        assert_eq!(content.len(), 300);
        // Every way of reading it says there is nothing here to read, and names the key the
        // caller will recognize, rather than handing back zeros as though they were the file.
        let err = content.read().expect_err("no bytes");
        assert_eq!(err.kind(), std::io::ErrorKind::Unsupported);
        assert!(err.to_string().contains("42"), "{err}");
        let err = content.read_at(0, &mut [0u8; 4]).expect_err("no bytes");
        assert_eq!(err.kind(), std::io::ErrorKind::Unsupported);
    }

    #[cfg(any(feature = "ext", feature = "fat"))]
    #[test]
    fn contents_come_in_windows_that_tile_the_file_in_order() {
        let len = 2 * CONTENT_WINDOW + 5;
        let bytes: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("big");
        std::fs::write(&path, &bytes).expect("write the backing file");

        let owned = FileContent::Owned(bytes.clone());
        let range = FileContent::Range(FileRange::at_path(&path, 0, len as u64));
        for content in [&owned, &range] {
            let mut seen: Vec<(u64, usize)> = Vec::new();
            let mut joined = Vec::new();
            content
                .for_each_window(|at, window| {
                    seen.push((at, window.len()));
                    joined.extend_from_slice(window);
                    Ok::<(), std::io::Error>(())
                })
                .expect("the contents read");
            let window = CONTENT_WINDOW as u64;
            assert_eq!(
                seen,
                [
                    (0, CONTENT_WINDOW),
                    (window, CONTENT_WINDOW),
                    (2 * window, 5)
                ]
            );
            assert!(joined == bytes, "the windows did not rejoin as the file");
        }

        // An empty file has no window at all, rather than one empty one.
        let mut calls = 0;
        FileContent::Owned(Vec::new())
            .for_each_window(|_, _| {
                calls += 1;
                Ok::<(), std::io::Error>(())
            })
            .expect("nothing to read");
        assert_eq!(calls, 0);
    }

    #[test]
    fn ranges_sharing_one_descriptor_read_their_own_bytes_concurrently() {
        // Every range into one archive shares one open file. A cursor belongs to the open
        // file, not to a handle, so a seek and a read through any handle to it are two steps
        // another range's read can land between — and both then return another member's
        // bytes, successfully. Each range here holds a byte value of its own, so any read
        // that came back with another's is the failure.
        const REGION: usize = 256 * 1024;
        const RANGES: usize = 8;
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("archive");
        let bytes: Vec<u8> = (0..RANGES)
            .flat_map(|i| std::iter::repeat_n(i as u8 + 1, REGION))
            .collect();
        std::fs::write(&path, &bytes).expect("write the backing file");
        let file = Arc::new(File::open(&path).expect("open the backing file"));

        let start = Arc::new(std::sync::Barrier::new(RANGES));
        let readers: Vec<_> = (0..RANGES)
            .map(|i| {
                let range =
                    FileRange::new(Arc::clone(&file), &path, (i * REGION) as u64, REGION as u64);
                let start = Arc::clone(&start);
                // Every thread reaches every barrier whatever its reads return, so a wrong
                // read is counted rather than panicked on: a panic here would leave the
                // others waiting for a thread that is gone.
                std::thread::spawn(move || {
                    let mut wrong = 0;
                    for _ in 0..20 {
                        start.wait();
                        match range.read() {
                            Ok(read) if read.iter().all(|&b| b == i as u8 + 1) => {}
                            _ => wrong += 1,
                        }
                    }
                    wrong
                })
            })
            .collect();
        let wrong: usize = readers
            .into_iter()
            .map(|reader| reader.join().expect("the reader thread runs to its end"))
            .sum();
        assert_eq!(wrong, 0, "reads that failed or held another range's bytes");
    }

    #[cfg(unix)]
    #[test]
    fn a_link_is_refused_by_the_flag_this_target_defines() {
        // `O_NOFOLLOW` is one number per architecture, and the number that is wrong for the
        // one being built is not a failure the kernel reports: on arm and aarch64 the value
        // Linux's generic headers give is `O_LARGEFILE`, which every open already implies,
        // so the flag is accepted, ignored, and the link followed. Nothing above this reads
        // as broken — the bytes of whatever the link points at simply arrive as the file's.
        //
        // So the flag is exercised rather than trusted: a range named by a path that is a
        // link must fail to read, on whatever target the suite is running on.
        let dir = tempfile::tempdir().expect("temp dir");
        let target = dir.path().join("target");
        std::fs::write(&target, b"pointed at\n").expect("write the target");
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&target, &link).expect("symlink");

        let err = FileRange::at_path(&link, 0, 11)
            .read()
            .expect_err("a range naming a link reads nothing");
        // That it failed is the whole claim: a flag the kernel ignored is a read that
        // *succeeds*, holding the target's bytes. Which errno says so is the kernel's to
        // choose — Linux reports `ELOOP` and the BSDs `EMLINK` — so the refusal is checked
        // by the path it names rather than by a number that varies with the platform.
        let text = err.to_string();
        assert!(text.contains("link"), "{text}");

        // The same range on the name the link points at reads it, so what the refusal
        // refuses is the link and not the read.
        assert_eq!(
            FileRange::at_path(&target, 0, 11).read().expect("read"),
            b"pointed at\n"
        );
    }

    #[test]
    fn distinct_times_are_preserved() {
        let m = Metadata::new(0o644, Timestamp::from_secs(100)).with_times(
            Timestamp::from_secs(1),
            Timestamp::from_secs(2),
            Timestamp::from_secs(3),
        );
        assert_eq!(m.atime, Timestamp::from_secs(1));
        assert_eq!(m.ctime, Timestamp::from_secs(2));
        assert_eq!(m.mtime, Timestamp::from_secs(3));
    }
}