Skip to main content

stuffr_core/
archive.rs

1//! The two orthogonal traits, and the entry model they share.
2
3use std::io::{Read, Write};
4use std::time::SystemTime;
5
6use crate::error::Result;
7use crate::fidelity::FidelityReport;
8use crate::format::{CodecCaps, ContainerCaps, FormatId};
9use crate::source::Source;
10
11#[derive(Clone, Default)]
12pub struct DecodeOpts {
13    /// Worker hint. The governor has final say; this is only a request.
14    pub threads: Option<usize>,
15    /// The shared worker/memory budget. `None` means single-threaded — a codec
16    /// parallelises only if handed a governor, never from an ambient global.
17    pub governor: Option<std::sync::Arc<crate::Governor>>,
18    /// Cap on memory a decoder may ask the allocator for. `None` means
19    /// unbounded, which is the library default; the CLI always sets a value.
20    ///
21    /// This exists because three pure codecs size a dictionary buffer from a
22    /// value the *file declares in its own header*, before producing any
23    /// output — measured at 69.35 MB peak RSS for a 60-byte `.xz`, and 538 MB
24    /// for a crafted 114-byte `.lz` that decoded correctly, so the cost came
25    /// purely from the declaration. `--max-ratio` cannot see it: that guard
26    /// counts decoded output bytes and the allocation precedes any output.
27    ///
28    /// Exceeding it is [`crate::Error::ResourceLimit`] (exit 6), never
29    /// `Corrupt` (exit 5) — the file is not damaged, this build simply will
30    /// not allocate that much.
31    pub memory_limit: Option<u64>,
32}
33
34impl std::fmt::Debug for DecodeOpts {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("DecodeOpts")
37            .field("threads", &self.threads)
38            .field("governor", &self.governor.as_ref().map(|_| "Governor"))
39            .field("memory_limit", &self.memory_limit)
40            .finish()
41    }
42}
43
44#[derive(Clone, Default)]
45pub struct EncodeOpts {
46    /// Format-relative compression level. `None` means the format's default.
47    pub level: Option<i32>,
48    /// Worker hint. The governor has final say; this is only a request.
49    pub threads: Option<usize>,
50    /// The shared worker/memory budget. `None` means single-threaded — a codec
51    /// parallelises only if handed a governor, never from an ambient global.
52    pub governor: Option<std::sync::Arc<crate::Governor>>,
53}
54
55impl std::fmt::Debug for EncodeOpts {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("EncodeOpts")
58            .field("level", &self.level)
59            .field("threads", &self.threads)
60            .field("governor", &self.governor.as_ref().map(|_| "Governor"))
61            .finish()
62    }
63}
64
65#[derive(Clone, Default)]
66pub struct OpenOpts {
67    pub password: Option<String>,
68    /// The shared worker/memory budget. `None` means single-threaded — a
69    /// container parallelises only if handed a governor, never from an
70    /// ambient global. Needed so a container with `per_entry_codec` can build
71    /// a `DecodeOpts` per entry, carrying the same governor forward.
72    pub governor: Option<std::sync::Arc<crate::Governor>>,
73}
74
75impl std::fmt::Debug for OpenOpts {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.debug_struct("OpenOpts")
78            .field("password", &self.password)
79            .field("governor", &self.governor.as_ref().map(|_| "Governor"))
80            .finish()
81    }
82}
83
84#[derive(Clone, Default)]
85pub struct CreateOpts {
86    pub level: Option<i32>,
87    /// Codec for entry payloads, for containers with `per_entry_codec`.
88    pub entry_codec: Option<FormatId>,
89    /// The shared worker/memory budget. `None` means single-threaded — a
90    /// container parallelises only if handed a governor, never from an
91    /// ambient global. Needed so a container with `per_entry_codec` can build
92    /// an `EncodeOpts` per entry, carrying the same governor forward.
93    pub governor: Option<std::sync::Arc<crate::Governor>>,
94}
95
96impl std::fmt::Debug for CreateOpts {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("CreateOpts")
99            .field("level", &self.level)
100            .field("entry_codec", &self.entry_codec)
101            .field("governor", &self.governor.as_ref().map(|_| "Governor"))
102            .finish()
103    }
104}
105
106/// Phase 2 adds `Hardlink`, `CharDevice`, `BlockDevice`, `Fifo` and `Socket`
107/// for tar and cpio; `#[non_exhaustive]` keeps that from breaking downstream
108/// matches. Struct types deliberately do NOT carry this attribute — see the
109/// `#[non_exhaustive]` section of CONTRIBUTING.md.
110#[non_exhaustive]
111#[derive(Clone, PartialEq, Eq, Debug, Default)]
112pub enum EntryKind {
113    #[default]
114    File,
115    Dir,
116    Symlink {
117        target: String,
118    },
119    Other,
120}
121
122#[derive(Clone, PartialEq, Eq, Debug, Default)]
123pub struct EntryMeta {
124    pub name: String,
125    pub size: Option<u64>,
126    pub compressed_size: Option<u64>,
127    pub mtime: Option<SystemTime>,
128    pub mode: Option<u32>,
129    pub uid: Option<u32>,
130    pub gid: Option<u32>,
131    pub kind: EntryKind,
132    /// Codec of this entry's payload, for `per_entry_codec` containers.
133    pub codec: Option<FormatId>,
134}
135
136impl EntryMeta {
137    pub fn file(name: impl Into<String>) -> Self {
138        Self {
139            name: name.into(),
140            ..Default::default()
141        }
142    }
143}
144
145/// One entry, borrowed from the archive it came from.
146///
147/// The reader is deliberately **not** `Send`. It was until Phase 2's first
148/// real container, and the bound was unsound to require: `tar::Entry` holds
149/// `&Archive<dyn Read>` over a `RefCell`, so it is `!Send` for any reader,
150/// and every container built on the `tar` crate would have had to assert
151/// `unsafe impl Send` for a property that is false — a lie that becomes UB
152/// the day anything actually sends one.
153///
154/// Nothing needs it. An entry borrows the archive it came from
155/// (`ArchiveRead::next_entry(&mut self) -> Entry<'_>`), so sending an entry
156/// to another thread would mean sending the archive with it, and no caller in
157/// this tree does either: entries are read on the thread that asked for
158/// them. Dropping the bound is strictly more permissive, so a container whose
159/// reader IS `Send` is unaffected.
160pub struct Entry<'a> {
161    meta: EntryMeta,
162    reader: Box<dyn Read + 'a>,
163}
164
165impl<'a> Entry<'a> {
166    pub fn new(meta: EntryMeta, reader: Box<dyn Read + 'a>) -> Self {
167        Self { meta, reader }
168    }
169
170    pub fn meta(&self) -> &EntryMeta {
171        &self.meta
172    }
173
174    pub fn reader(&mut self) -> &mut (dyn Read + 'a) {
175        &mut *self.reader
176    }
177
178    /// Takes the payload reader out, leaving the metadata behind — the one
179    /// way to rebuild an `Entry` with different metadata over the SAME,
180    /// still-streaming reader.
181    ///
182    /// `#[cfg(test)]` and `pub(crate)` on purpose: no container needs it,
183    /// and nothing outside this crate should be rewriting an entry's
184    /// metadata between the container that read it and the caller that acts
185    /// on it. It exists for `container_conformance`'s property 11 doubles,
186    /// which have to report a mode the framed mock's wire format does not
187    /// carry while still satisfying property 8 — buffering the payload to
188    /// fake one would trip the incrementality property first and the double
189    /// would then prove the wrong thing. Not `pub`: widening the visibility
190    /// to silence the dead-code lint would ship a metadata-rewriting hook to
191    /// every caller for a test's convenience.
192    #[cfg(test)]
193    pub(crate) fn into_reader(self) -> Box<dyn Read + 'a> {
194        self.reader
195    }
196}
197
198/// Manual impl: `reader` is `Box<dyn Read>`, which cannot derive `Debug`.
199/// Needed so `Result<Entry<'_>, Error>::unwrap_err()` type-checks in tests
200/// (`unwrap_err` requires the `Ok` side to be `Debug`).
201impl std::fmt::Debug for Entry<'_> {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        f.debug_struct("Entry")
204            .field("meta", &self.meta)
205            .finish_non_exhaustive()
206    }
207}
208
209/// A writer that needs an explicit, fallible completion step (trailers, CRCs).
210///
211/// `finish` must flush the underlying writer before returning, once every
212/// trailer byte has been written to it. `Codec::encoder` takes the
213/// destination `Box<dyn Write + Send>` by value, so once a caller has handed
214/// it over, `finish` is the only code left holding it — the caller has no
215/// remaining handle to flush afterwards. Skipping this is silent on an
216/// unbuffered destination (a plain `File`) but loses the tail of the stream
217/// on a buffered one: notably stdout's `LineWriter`, which only auto-flushes
218/// on `\n` and may see none in a long run of binary output.
219///
220/// `#[must_use]` on the trait, so a `Box<dyn Sink>` that is produced and then
221/// dropped without `finish` is a warning rather than a silent truncation.
222/// `ArchiveWrite::finish` returns one precisely so the layer beneath can be
223/// finished next; `archive.finish()?;` on its own compiles perfectly well and
224/// loses every trailer below the container — the exact defect Phase 2c
225/// exists to fix, reintroduced by a line that looks finished.
226#[must_use = "a Sink must be completed with `finish`; dropping it skips the \
227              trailer and the flush, truncating the output"]
228pub trait Sink: Write + Send {
229    fn finish(self: Box<Self>) -> Result<()>;
230}
231
232/// A [`Sink`] over a destination that needs no trailer — an uncompressed file.
233///
234/// Exists so `Container::create` can take a `Box<dyn Sink>` uniformly. A
235/// composed write never constructs one: there the codec's own `Sink` IS the
236/// container's destination. `finish` flushes, which is exactly what all four
237/// containers used to do by hand at the end of their own `finish`.
238pub struct PlainSink(Box<dyn Write + Send>);
239
240impl PlainSink {
241    /// Returns the boxed trait object rather than `Self` on purpose: every
242    /// call site wants a `Box<dyn Sink>`, and handing back `Self` would make
243    /// each of them re-box it.
244    #[allow(clippy::new_ret_no_self)]
245    pub fn new(w: Box<dyn Write + Send>) -> Box<dyn Sink> {
246        Box::new(Self(w))
247    }
248}
249
250impl Write for PlainSink {
251    fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
252        self.0.write(b)
253    }
254    fn flush(&mut self) -> std::io::Result<()> {
255        self.0.flush()
256    }
257}
258
259impl Sink for PlainSink {
260    fn finish(mut self: Box<Self>) -> Result<()> {
261        self.0.flush()?;
262        Ok(())
263    }
264}
265
266/// A byte-stream transform. Knows nothing about files, names, or entries.
267pub trait Codec: Send + Sync {
268    fn id(&self) -> FormatId;
269    fn caps(&self) -> CodecCaps;
270    /// Validates encode options without touching the filesystem.
271    ///
272    /// `ops` calls this before opening any destination, so a rejected option
273    /// costs nothing — no temp file created, no existing file disturbed. The
274    /// default accepts everything, for codecs with no options to reject.
275    ///
276    /// With one codec this looks like ceremony. With nine, each carrying its
277    /// own level range, "validate before touching the filesystem" has to be a
278    /// contract rather than a habit: in Phase 1b an invalid level created and
279    /// then deleted a file for nothing.
280    fn check_encode_opts(&self, _o: &EncodeOpts) -> Result<()> {
281        Ok(())
282    }
283    /// Decodes `src`. Returns a [`Source`] rather than a bare reader so a codec
284    /// carrying a frame index can advertise seekability to the layer above;
285    /// forward-only codecs wrap their reader in [`crate::StreamOnly`].
286    fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> Result<Box<dyn Source>>;
287    fn encoder(&self, dst: Box<dyn Write + Send>, o: &EncodeOpts) -> Result<Box<dyn Sink>>;
288}
289
290/// A structure of entries. May invoke codecs internally.
291pub trait Container: Send + Sync {
292    fn id(&self) -> FormatId;
293    fn caps(&self) -> ContainerCaps;
294    /// Opens an archive from a ladder-resolved source.
295    ///
296    /// Takes the whole [`crate::Resolved`] rather than just its source so the
297    /// container knows which rung it was given — which is what makes
298    /// `Rung::Degraded` implementable — and so it can seed its fidelity report
299    /// from the ladder's rather than re-deriving the same facts.
300    fn open(&self, resolved: crate::ladder::Resolved, o: &OpenOpts)
301    -> Result<Box<dyn ArchiveRead>>;
302    /// Creates an archive writing into `dst`.
303    ///
304    /// Takes a [`Sink`] rather than a bare `Write` so a container over a codec
305    /// composes: the codec's own `Sink` is handed straight in, and
306    /// [`ArchiveWrite::finish`] gives it back so the caller can finish it.
307    /// Passing a bare file means wrapping it in [`PlainSink`].
308    fn create(&self, dst: Box<dyn Sink>, o: &CreateOpts) -> Result<Box<dyn ArchiveWrite>>;
309}
310
311pub trait ArchiveRead {
312    /// Forward iteration. Available for every container on every input — this
313    /// is the streaming path, and the reason `Entry` borrows.
314    fn next_entry(&mut self) -> Result<Option<Entry<'_>>>;
315
316    /// Random access. `Err(NotSeekable)` when the ladder could not supply seek.
317    fn by_index(&mut self, index: usize) -> Result<Entry<'_>>;
318
319    fn fidelity(&self) -> &FidelityReport;
320}
321
322pub trait ArchiveWrite {
323    fn add(&mut self, meta: &EntryMeta, data: &mut dyn Read) -> Result<()>;
324    /// Writes the container's trailer and returns the destination.
325    ///
326    /// Returning it is what makes container-over-codec possible: the caller
327    /// still holds a `Sink` afterwards and can finish the codec layer, which
328    /// writes ITS trailer. Dropping the destination here — what this used to
329    /// do — silently truncated every composed archive.
330    ///
331    /// Implementors must NOT call `finish` on the returned sink. Finishing is
332    /// the caller's, once, at the outermost layer.
333    fn finish(self: Box<Self>) -> Result<Box<dyn Sink>>;
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    #[test]
341    fn a_plain_sink_flushes_its_destination_on_finish() {
342        use std::sync::{Arc, Mutex};
343
344        #[derive(Default)]
345        struct Rec {
346            flushed: bool,
347            bytes: Vec<u8>,
348        }
349        struct W(Arc<Mutex<Rec>>);
350        impl Write for W {
351            fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
352                self.0.lock().unwrap().bytes.extend_from_slice(b);
353                Ok(b.len())
354            }
355            fn flush(&mut self) -> std::io::Result<()> {
356                self.0.lock().unwrap().flushed = true;
357                Ok(())
358            }
359        }
360
361        let rec = Arc::new(Mutex::new(Rec::default()));
362        let mut sink = PlainSink::new(Box::new(W(Arc::clone(&rec))));
363        sink.write_all(b"payload").unwrap();
364        assert!(
365            !rec.lock().unwrap().flushed,
366            "finish has not been called yet"
367        );
368        sink.finish().unwrap();
369
370        let r = rec.lock().unwrap();
371        assert!(
372            r.flushed,
373            "PlainSink::finish must flush — a buffered destination loses its tail otherwise"
374        );
375        assert_eq!(r.bytes, b"payload");
376    }
377}