Skip to main content

libarchive_oxide_core/
protocol.rs

1// SPDX-FileCopyrightText: 2026 libarchive_oxide contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Unified sans-I/O codec and archive protocols.
6
7use core::fmt;
8
9use crate::metadata::{ArchiveMetadata, EntryMetadata};
10use crate::{ArchiveError, ErrorKind};
11
12/// Whether the supplied input is the final input.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum EndOfInput {
15    /// Additional input may arrive.
16    More,
17    /// No additional input will arrive.
18    End,
19}
20
21/// Three-way incremental detection result.
22#[derive(Debug, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum ProbeResult<T> {
25    /// A format/filter matched.
26    Match(T),
27    /// At least `minimum` prefix bytes are required.
28    NeedMore {
29        /// Minimum prefix size needed for the next decision.
30        minimum: usize,
31    },
32    /// The candidate did not match.
33    NoMatch,
34}
35
36/// What a byte codec needs after one call.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum CodecStatus {
40    /// Supply additional input.
41    NeedInput,
42    /// Supply additional output capacity.
43    NeedOutput,
44    /// One complete codec stream ended.
45    Done,
46}
47
48/// Progress made by a byte codec.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct CodecStep {
51    /// Input bytes consumed.
52    pub consumed: usize,
53    /// Output bytes produced.
54    pub produced: usize,
55    /// Required next action.
56    pub status: CodecStatus,
57}
58
59impl CodecStep {
60    /// Validates counts and progress against the provided buffers.
61    pub fn validate(self, input_len: usize, output_len: usize) -> Result<Self, ArchiveError> {
62        if self.consumed > input_len || self.produced > output_len {
63            return Err(ArchiveError::new(ErrorKind::Protocol)
64                .with_context("codec reported out-of-range progress"));
65        }
66        if self.consumed == 0 && self.produced == 0 {
67            let valid_wait = matches!(self.status, CodecStatus::NeedInput) && input_len == 0;
68            let valid_backpressure =
69                matches!(self.status, CodecStatus::NeedOutput) && output_len == 0;
70            if !valid_wait && !valid_backpressure && !matches!(self.status, CodecStatus::Done) {
71                return Err(
72                    ArchiveError::new(ErrorKind::Protocol).with_context("codec made no progress")
73                );
74            }
75        }
76        Ok(self)
77    }
78}
79
80/// Incremental byte-to-byte codec.
81pub trait Codec {
82    /// Processes input, including finalization when `end` is [`EndOfInput::End`].
83    fn process(
84        &mut self,
85        input: &[u8],
86        output: &mut [u8],
87        end: EndOfInput,
88    ) -> Result<CodecStep, ArchiveError>;
89}
90
91/// A borrowed entry-data window.
92#[derive(Clone, Copy)]
93pub struct Chunk<'a> {
94    bytes: &'a [u8],
95}
96
97impl<'a> Chunk<'a> {
98    /// Wraps a borrowed data window.
99    #[must_use]
100    pub const fn new(bytes: &'a [u8]) -> Self {
101        Self { bytes }
102    }
103
104    /// Window bytes.
105    #[must_use]
106    pub const fn as_bytes(self) -> &'a [u8] {
107        self.bytes
108    }
109}
110
111impl fmt::Debug for Chunk<'_> {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.debug_struct("Chunk")
114            .field("len", &self.bytes.len())
115            .finish()
116    }
117}
118
119/// Structural event produced by an archive decoder.
120#[derive(Debug)]
121#[non_exhaustive]
122#[allow(clippy::large_enum_variant)]
123pub enum DecodeEvent<'a> {
124    /// Supply more archive bytes.
125    NeedInput,
126    /// Supply a non-empty scratch/output buffer.
127    NeedOutput,
128    /// Archive-level metadata was discovered or updated.
129    ArchiveMetadata(ArchiveMetadata),
130    /// A new entry begins.
131    Entry(EntryMetadata),
132    /// Entry body bytes.
133    Data(Chunk<'a>),
134    /// Current entry body ended.
135    EndEntry,
136    /// Archive ended.
137    Done,
138}
139
140/// Progress and event from one archive decoder call.
141#[derive(Debug)]
142pub struct DecodeStep<'a> {
143    /// Input bytes consumed.
144    pub consumed: usize,
145    /// Scratch-buffer bytes produced.
146    pub produced: usize,
147    /// Structural event.
148    pub event: DecodeEvent<'a>,
149}
150
151impl DecodeStep<'_> {
152    /// Validates progress against the supplied buffers.
153    pub fn validate(self, input_len: usize, output_len: usize) -> Result<Self, ArchiveError> {
154        if self.consumed > input_len || self.produced > output_len {
155            return Err(ArchiveError::new(ErrorKind::Protocol)
156                .with_context("archive decoder reported out-of-range progress"));
157        }
158        if self.consumed == 0 && self.produced == 0 {
159            let semantic_progress = match &self.event {
160                DecodeEvent::NeedInput
161                | DecodeEvent::NeedOutput
162                | DecodeEvent::ArchiveMetadata(_)
163                | DecodeEvent::Entry(_)
164                | DecodeEvent::EndEntry
165                | DecodeEvent::Done => true,
166                DecodeEvent::Data(chunk) => !chunk.bytes.is_empty(),
167            };
168            if !semantic_progress {
169                return Err(ArchiveError::new(ErrorKind::Protocol)
170                    .with_context("archive decoder made no progress"));
171            }
172        }
173        Ok(self)
174    }
175}
176
177/// Incremental archive decoder.
178pub trait ArchiveDecoder {
179    /// Consumes archive bytes and produces at most one structural event.
180    fn step<'a>(
181        &'a mut self,
182        input: &'a [u8],
183        output: &'a mut [u8],
184        end: EndOfInput,
185    ) -> Result<DecodeStep<'a>, ArchiveError>;
186}
187
188/// Input command for an archive encoder.
189#[derive(Debug)]
190#[non_exhaustive]
191pub enum EncodeCommand<'a> {
192    /// Begins an entry.
193    BeginEntry(&'a EntryMetadata),
194    /// Supplies entry body bytes.
195    Data(&'a [u8]),
196    /// Ends the current entry.
197    EndEntry,
198    /// Finalizes the archive.
199    Finish,
200}
201
202/// Encoder state after one call.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204#[non_exhaustive]
205pub enum EncodeStatus {
206    /// The caller may submit another command.
207    NeedCommand,
208    /// The caller must provide more output capacity while retaining the command.
209    NeedOutput,
210    /// The archive is finalized.
211    Done,
212}
213
214/// Progress from one archive encoder call.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct EncodeStep {
217    /// Data-command bytes consumed. Non-data commands use 0 or 1.
218    pub consumed: usize,
219    /// Output bytes produced.
220    pub produced: usize,
221    /// Encoder state.
222    pub status: EncodeStatus,
223}
224
225impl EncodeStep {
226    /// Validates encoder progress for one command.
227    pub fn validate(
228        self,
229        data_input_len: Option<usize>,
230        output_len: usize,
231    ) -> Result<Self, ArchiveError> {
232        let maximum = data_input_len.unwrap_or(1);
233        if self.consumed > maximum || self.produced > output_len {
234            return Err(ArchiveError::new(ErrorKind::Protocol)
235                .with_context("archive encoder reported out-of-range progress"));
236        }
237        if data_input_len.is_some()
238            && self.consumed == 0
239            && self.produced == 0
240            && (!matches!(self.status, EncodeStatus::NeedOutput) || output_len != 0)
241        {
242            return Err(ArchiveError::new(ErrorKind::Protocol)
243                .with_context("archive encoder made no data progress"));
244        }
245        Ok(self)
246    }
247}
248
249/// Incremental sequential archive encoder.
250pub trait ArchiveEncoder {
251    /// Processes one command into caller-owned output.
252    fn step(
253        &mut self,
254        command: EncodeCommand<'_>,
255        output: &mut [u8],
256    ) -> Result<EncodeStep, ArchiveError>;
257}