use core::fmt::{self, Debug, Display};
#[derive(Clone, Debug)]
pub struct Error<E: Debug> {
kind: ErrorKind,
cause: Option<E>,
}
impl<E> Error<E>
where
E: Debug,
{
pub fn new(kind: ErrorKind) -> Self {
Self { kind, cause: None }
}
pub fn new_with_cause(kind: ErrorKind, cause: E) -> Self {
Self {
kind,
cause: Some(cause),
}
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn cause(&self) -> Option<&E> {
self.cause.as_ref()
}
pub fn into_cause(self) -> E {
self.cause
.expect("into_cause called on an error with no cause")
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
Bus,
Device,
Mode,
Param,
}
impl ErrorKind {
pub fn err<E: Debug>(self) -> Result<(), Error<E>> {
Err(Error::new(self))
}
}
impl ErrorKind {
pub fn description(self) -> &'static str {
match self {
ErrorKind::Device => "device error",
ErrorKind::Bus => "bus error",
ErrorKind::Mode => "invalid mode",
ErrorKind::Param => "invalid parameter",
}
}
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl<E> From<E> for Error<E>
where
E: Debug,
{
fn from(cause: E) -> Error<E> {
Self::new_with_cause(ErrorKind::Bus, cause)
}
}