use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
pub(crate) type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub(crate) enum Error {
Malformed(&'static str),
Unsupported(&'static str),
LimitExceeded(&'static str),
InvalidState(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed(m) => write!(f, "malformed archive: {m}"),
Self::Unsupported(m) => write!(f, "unsupported feature: {m}"),
Self::LimitExceeded(m) => write!(f, "safety limit exceeded: {m}"),
Self::InvalidState(m) => write!(f, "invalid state: {m}"),
}
}
}
impl core::error::Error for Error {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
Malformed,
Unsupported,
Limit,
Integrity,
Capability,
SizeRequired,
Protocol,
Policy,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArchiveError {
kind: ErrorKind,
format: Option<&'static str>,
offset: Option<u64>,
entry_index: Option<u64>,
entry_path: Option<Vec<u8>>,
context: Vec<String>,
}
impl ArchiveError {
#[must_use]
pub const fn new(kind: ErrorKind) -> Self {
Self {
kind,
format: None,
offset: None,
entry_index: None,
entry_path: None,
context: Vec::new(),
}
}
#[must_use]
pub fn with_context(mut self, context: impl Into<String>) -> Self {
self.context.push(context.into());
self
}
#[must_use]
pub const fn with_format(mut self, format: &'static str) -> Self {
self.format = Some(format);
self
}
#[must_use]
pub const fn with_offset(mut self, offset: u64) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn with_entry(mut self, index: u64, path: impl Into<Vec<u8>>) -> Self {
self.entry_index = Some(index);
self.entry_path = Some(path.into());
self
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub const fn format(&self) -> Option<&'static str> {
self.format
}
#[must_use]
pub const fn offset(&self) -> Option<u64> {
self.offset
}
#[must_use]
pub fn entry(&self) -> Option<(u64, &[u8])> {
Some((self.entry_index?, self.entry_path.as_deref()?))
}
#[must_use]
pub fn context(&self) -> &[String] {
&self.context
}
}
impl fmt::Display for ArchiveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?} archive error", self.kind)?;
if let Some(format) = self.format {
write!(f, " in {format}")?;
}
if let Some(offset) = self.offset {
write!(f, " at byte {offset}")?;
}
for context in &self.context {
write!(f, ": {context}")?;
}
Ok(())
}
}
impl core::error::Error for ArchiveError {}
impl From<Error> for ArchiveError {
fn from(value: Error) -> Self {
match value {
Error::Malformed(message) => Self::new(ErrorKind::Malformed).with_context(message),
Error::Unsupported(message) => Self::new(ErrorKind::Unsupported).with_context(message),
Error::LimitExceeded(message) => Self::new(ErrorKind::Limit).with_context(message),
Error::InvalidState(message) => Self::new(ErrorKind::Protocol).with_context(message),
}
}
}