use core::fmt;
use crate::device::Request;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Error<E> {
Port(E),
Protocol(crate::Error),
Timeout(Request),
Elapsed,
}
impl<E> Error<E> {
#[must_use]
pub const fn port(&self) -> Option<&E> {
match self {
Self::Port(error) => Some(error),
_ => None,
}
}
#[must_use]
pub fn into_port(self) -> Option<E> {
match self {
Self::Port(error) => Some(error),
_ => None,
}
}
#[must_use]
pub const fn protocol(&self) -> Option<crate::Error> {
match self {
Self::Protocol(error) => Some(*error),
_ => None,
}
}
#[must_use]
pub const fn request(&self) -> Option<Request> {
match self {
Self::Timeout(request) => Some(*request),
_ => None,
}
}
}
impl<E> From<crate::Error> for Error<E> {
fn from(error: crate::Error) -> Self {
Self::Protocol(error)
}
}
impl<E: fmt::Display> fmt::Display for Error<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Port(error) => write!(f, "MIDI port: {error}"),
Self::Protocol(error) => error.fmt(f),
Self::Timeout(request) => write!(f, "no answer to the {request}"),
Self::Elapsed => f.write_str("waited longer than the caller allowed"),
}
}
}
impl<E: core::error::Error + 'static> core::error::Error for Error<E> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Port(error) => Some(error),
Self::Protocol(error) => Some(error),
_ => None,
}
}
}