haggis-rs/src/error.rs
2023-07-07 19:20:21 -04:00

85 lines
2.2 KiB
Rust

use std::{
array::TryFromSliceError, ffi::NulError, fmt, io, num::TryFromIntError, string::FromUtf8Error,
};
#[derive(Debug)]
pub enum Error {
Int(TryFromIntError),
Io(io::Error),
Utf8(FromUtf8Error),
Slice(TryFromSliceError),
InvalidChecksum,
InvalidAlgorithm,
InvalidMagic,
MissingData,
MutexError,
NulError,
SenderError,
UnexpectedData,
UnknownFileType,
Other(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Int(e) => write!(f, "{e}"),
Self::Utf8(e) => write!(f, "{e}"),
Self::Slice(e) => write!(f, "{e}"),
Self::Io(e) => write!(f, "{e}"),
Self::InvalidAlgorithm => write!(f, "invalid algorithm"),
Self::InvalidChecksum => write!(f, "invalid checksum"),
Self::InvalidMagic => write!(f, "invalid magic"),
Self::MissingData => write!(f, "missing data"),
Self::MutexError => write!(f, "mutex error"),
Self::NulError => write!(f, "nul error"),
Self::SenderError => write!(f, "sender error"),
Self::UnexpectedData => write!(f, "unexpected data"),
Self::UnknownFileType => write!(f, "unknown file type"),
Self::Other(s) => write!(f, "{s}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Int(e) => Some(e),
Self::Io(e) => Some(e),
Self::Utf8(e) => Some(e),
Self::Slice(e) => Some(e),
_ => None,
}
}
}
impl From<TryFromIntError> for Error {
fn from(value: TryFromIntError) -> Self {
Self::Int(value)
}
}
impl From<io::Error> for Error {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}
impl From<FromUtf8Error> for Error {
fn from(value: FromUtf8Error) -> Self {
Self::Utf8(value)
}
}
impl From<TryFromSliceError> for Error {
fn from(value: TryFromSliceError) -> Self {
Self::Slice(value)
}
}
impl From<NulError> for Error {
fn from(_value: NulError) -> Self {
Self::NulError
}
}