#![allow(unknown_lints)] #![allow(non_local_definitions)]
use std::borrow::Cow;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::num::TryFromIntError;
use std::string::FromUtf8Error;
pub type ZipResult<T> = Result<T, ZipError>;
#[derive(Debug)]
#[non_exhaustive]
pub enum ZipError {
Io(io::Error),
InvalidArchive(Cow<'static, str>),
UnsupportedArchive(&'static str),
FileNotFound,
InvalidPassword,
}
impl ZipError {
pub const PASSWORD_REQUIRED: &'static str = "Password required to decrypt file";
}
impl Display for ZipError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Io(_) => f.write_str("i/o error"),
Self::InvalidArchive(e) => write!(f, "invalid Zip archive: {}", e),
Self::UnsupportedArchive(e) => write!(f, "unsupported Zip archive: {}", e),
Self::FileNotFound => f.write_str("specified file not found in archive"),
Self::InvalidPassword => f.write_str("provided password is incorrect"),
}
}
}
impl Error for ZipError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io(e) => Some(e),
Self::InvalidArchive(_)
| Self::UnsupportedArchive(_)
| Self::FileNotFound
| Self::InvalidPassword => None,
}
}
}
impl From<ZipError> for io::Error {
fn from(err: ZipError) -> io::Error {
let kind = match &err {
ZipError::Io(err) => err.kind(),
ZipError::InvalidArchive(_) => io::ErrorKind::InvalidData,
ZipError::UnsupportedArchive(_) => io::ErrorKind::Unsupported,
ZipError::FileNotFound => io::ErrorKind::NotFound,
ZipError::InvalidPassword => io::ErrorKind::InvalidInput,
};
io::Error::new(kind, err)
}
}
impl From<io::Error> for ZipError {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}
impl From<DateTimeRangeError> for ZipError {
fn from(_: DateTimeRangeError) -> Self {
invalid!("Invalid date or time")
}
}
impl From<FromUtf8Error> for ZipError {
fn from(_: FromUtf8Error) -> Self {
invalid!("Invalid UTF-8")
}
}
#[derive(Debug)]
pub struct DateTimeRangeError;
impl From<TryFromIntError> for DateTimeRangeError {
fn from(_value: TryFromIntError) -> Self {
DateTimeRangeError
}
}
impl fmt::Display for DateTimeRangeError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"a date could not be represented within the bounds the MS-DOS date range (1980-2107)"
)
}
}
impl Error for DateTimeRangeError {}
pub(crate) fn invalid_archive<M: Into<Cow<'static, str>>>(message: M) -> ZipError {
ZipError::InvalidArchive(message.into())
}
pub(crate) const fn invalid_archive_const(message: &'static str) -> ZipError {
ZipError::InvalidArchive(Cow::Borrowed(message))
}
macro_rules! invalid {
($message:literal) => {
crate::result::invalid_archive_const($message)
};
($($arg:tt)*) => {
crate::result::invalid_archive(format!($($arg)*))
};
}
pub(crate) use invalid;