Skip to main content

libarchive_oxide_core/
error.rs

1// SPDX-FileCopyrightText: 2026 libarchive_oxide contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! `no_std`-friendly error type. Does not depend on `std::io::Error`.
6
7use alloc::string::String;
8use alloc::vec::Vec;
9use core::fmt;
10
11/// Crate-wide result type.
12pub(crate) type Result<T> = core::result::Result<T, Error>;
13
14/// `libarchive_oxide-core`'s error. Represents, in the type system, the semantic failures that can occur in the sans-IO layer.
15///
16/// I/O-originated failures are not expressed in the base layer (since it is sans-IO, the bytes are carried by the caller).
17/// The std-side adapters are responsible for interconversion with `std::io::Error`.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[non_exhaustive]
20pub(crate) enum Error {
21    /// The input byte sequence violates the format specification (corrupt header, invalid magic, etc.).
22    Malformed(&'static str),
23    /// Valid per the specification, but a feature this implementation does not yet handle.
24    Unsupported(&'static str),
25    /// A header-declared size or similar exceeded the configured safety limit (guards against decompression bombs and huge lengths).
26    LimitExceeded(&'static str),
27    /// A protocol violation, such as attempting to proceed to the next operation before fully reading an entry's data.
28    InvalidState(&'static str),
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self {
34            Self::Malformed(m) => write!(f, "malformed archive: {m}"),
35            Self::Unsupported(m) => write!(f, "unsupported feature: {m}"),
36            Self::LimitExceeded(m) => write!(f, "safety limit exceeded: {m}"),
37            Self::InvalidState(m) => write!(f, "invalid state: {m}"),
38        }
39    }
40}
41
42impl core::error::Error for Error {}
43
44/// Stable classification of v0.2 archive failures.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum ErrorKind {
48    /// Malformed bytes or contradictory headers.
49    Malformed,
50    /// Valid but unsupported format capability.
51    Unsupported,
52    /// Configured resource budget was exceeded.
53    Limit,
54    /// A checksum, authentication tag, or other integrity check failed.
55    Integrity,
56    /// The current input/output lacks a required capability.
57    Capability,
58    /// A writer requires a declared entry size.
59    SizeRequired,
60    /// Caller or implementation violated the state-machine contract.
61    Protocol,
62    /// Filesystem extraction policy rejected an operation.
63    Policy,
64}
65
66/// Context-rich, `no_std + alloc` archive failure.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct ArchiveError {
69    kind: ErrorKind,
70    format: Option<&'static str>,
71    offset: Option<u64>,
72    entry_index: Option<u64>,
73    entry_path: Option<Vec<u8>>,
74    context: Vec<String>,
75}
76
77impl ArchiveError {
78    /// Creates an error with a stable kind.
79    #[must_use]
80    pub const fn new(kind: ErrorKind) -> Self {
81        Self {
82            kind,
83            format: None,
84            offset: None,
85            entry_index: None,
86            entry_path: None,
87            context: Vec::new(),
88        }
89    }
90
91    /// Adds a diagnostic context frame.
92    #[must_use]
93    pub fn with_context(mut self, context: impl Into<String>) -> Self {
94        self.context.push(context.into());
95        self
96    }
97
98    /// Adds format context.
99    #[must_use]
100    pub const fn with_format(mut self, format: &'static str) -> Self {
101        self.format = Some(format);
102        self
103    }
104
105    /// Adds byte offset context.
106    #[must_use]
107    pub const fn with_offset(mut self, offset: u64) -> Self {
108        self.offset = Some(offset);
109        self
110    }
111
112    /// Adds entry context.
113    #[must_use]
114    pub fn with_entry(mut self, index: u64, path: impl Into<Vec<u8>>) -> Self {
115        self.entry_index = Some(index);
116        self.entry_path = Some(path.into());
117        self
118    }
119
120    /// Stable classification.
121    #[must_use]
122    pub const fn kind(&self) -> ErrorKind {
123        self.kind
124    }
125
126    /// Format context.
127    #[must_use]
128    pub const fn format(&self) -> Option<&'static str> {
129        self.format
130    }
131
132    /// Byte offset.
133    #[must_use]
134    pub const fn offset(&self) -> Option<u64> {
135        self.offset
136    }
137
138    /// Entry index and raw path.
139    #[must_use]
140    pub fn entry(&self) -> Option<(u64, &[u8])> {
141        Some((self.entry_index?, self.entry_path.as_deref()?))
142    }
143
144    /// Diagnostic context frames, outermost last.
145    #[must_use]
146    pub fn context(&self) -> &[String] {
147        &self.context
148    }
149}
150
151impl fmt::Display for ArchiveError {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(f, "{:?} archive error", self.kind)?;
154        if let Some(format) = self.format {
155            write!(f, " in {format}")?;
156        }
157        if let Some(offset) = self.offset {
158            write!(f, " at byte {offset}")?;
159        }
160        for context in &self.context {
161            write!(f, ": {context}")?;
162        }
163        Ok(())
164    }
165}
166
167impl core::error::Error for ArchiveError {}
168
169impl From<Error> for ArchiveError {
170    fn from(value: Error) -> Self {
171        match value {
172            Error::Malformed(message) => Self::new(ErrorKind::Malformed).with_context(message),
173            Error::Unsupported(message) => Self::new(ErrorKind::Unsupported).with_context(message),
174            Error::LimitExceeded(message) => Self::new(ErrorKind::Limit).with_context(message),
175            Error::InvalidState(message) => Self::new(ErrorKind::Protocol).with_context(message),
176        }
177    }
178}