ferrosys 0.2.0

Pure-Rust, general-purpose ext2/3/4 filesystem implementation (formatter, reader, resize-safe geometry)
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
//! 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::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::ondisk::{Timestamp, Xattr};

/// A regular file's contents: either bytes in memory, or a range of a file on the host
/// read at the moment it is placed.
///
/// The 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, so the peak becomes the largest single file rather than the
/// total.
///
/// 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)]
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),
}

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(),
        }
    }

    /// 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) allocates, and only for as long
    /// as the caller keeps what it returned.
    ///
    /// # 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()?)),
        }
    }
}

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)
    }
}

// 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.
///
/// # Two 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 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.
///
/// 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.
#[derive(Clone)]
pub struct FileRange {
    /// The open file, when the range was built from one. Shared so a handle is owned
    /// rather than borrowed. `None` for a range named by path alone, which opens `path`
    /// when it is read.
    file: Option<Arc<File>>,
    /// The path the bytes come from: what a range built from a descriptor names for
    /// diagnostics and identity, and what one built by path opens.
    path: Arc<PathBuf>,
    offset: u64,
    len: u64,
}

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 {
            file: Some(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.
    #[must_use]
    pub fn at_path(path: impl Into<PathBuf>, offset: u64, len: u64) -> Self {
        Self {
            file: None,
            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.
    ///
    /// 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 transparent
    /// [`FormatError::Io`](crate::materialize::FormatError::Io), 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.
    ///
    /// # Errors
    ///
    /// [`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.
    pub fn read(&self) -> std::io::Result<Vec<u8>> {
        let context = |e: std::io::Error| {
            std::io::Error::new(
                e.kind(),
                format!(
                    "{}: reading {} bytes at offset {}: {e}",
                    self.path.display(),
                    self.len,
                    self.offset
                ),
            )
        };
        let len = usize::try_from(self.len).map_err(|_| {
            std::io::Error::other(format!(
                "{}: {} bytes at offset {} is more than this platform addresses",
                self.path.display(),
                self.len,
                self.offset
            ))
        })?;
        // An independent descriptor, so the read carries its own cursor: a shared one
        // would make two handles into the same file interfere. A range named by path
        // alone opens it here, which is the whole of what it defers.
        let mut handle = match &self.file {
            Some(file) => file.try_clone().map_err(context)?,
            None => File::open(self.path.as_path()).map_err(context)?,
        };
        handle.seek(SeekFrom::Start(self.offset)).map_err(context)?;
        let mut buf = vec![0u8; len];
        handle.read_exact(&mut buf).map_err(context)?;
        Ok(buf)
    }
}

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; the creation time is derived from the modification time by the model,
/// since no archive format records a birth time.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
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`); also the source of the derived creation time.
    pub mtime: Timestamp,
}

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,
        }
    }

    /// 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
    }
}

/// 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)]
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.
#[derive(Clone, PartialEq, Eq, Debug)]
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. Empty for an entry with none.
    pub xattrs: Vec<Xattr>,
}

/// 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>;
}

/// 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 {
            path: path.into(),
            kind,
            meta,
            xattrs: Vec::new(),
        });
    }
}

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

#[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 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 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));
    }
}