use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
Format(String),
Unsupported(String),
Cast(String),
InvalidArgument(String),
Shape {
expected: Vec<usize>,
got: usize,
},
Pickle(String),
Compression(String),
Exhausted,
}
impl Error {
pub(crate) fn format<S: Into<String>>(m: S) -> Self {
Error::Format(m.into())
}
pub(crate) fn unsupported<S: Into<String>>(m: S) -> Self {
Error::Unsupported(m.into())
}
pub(crate) fn cast<S: Into<String>>(m: S) -> Self {
Error::Cast(m.into())
}
pub(crate) fn invalid<S: Into<String>>(m: S) -> Self {
Error::InvalidArgument(m.into())
}
pub(crate) fn pickle<S: Into<String>>(m: S) -> Self {
Error::Pickle(m.into())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io(e) => write!(f, "io error: {e}"),
Error::Format(m) => write!(f, "malformed file: {m}"),
Error::Unsupported(m) => write!(f, "unsupported feature: {m}"),
Error::Cast(m) => write!(f, "conversion error: {m}"),
Error::InvalidArgument(m) => write!(f, "invalid argument: {m}"),
Error::Shape { expected, got } => {
write!(f, "shape {expected:?} does not match {got} elements")
}
Error::Pickle(m) => write!(f, "pickle error: {m}"),
Error::Compression(m) => write!(f, "compression error: {m}"),
Error::Exhausted => write!(f, "stream already exhausted"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::Io(e)
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(e: std::string::FromUtf8Error) -> Self {
Error::Format(format!("invalid utf-8: {e}"))
}
}