use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
Parse,
Type,
Invalid,
Unsupported,
}
impl ErrorKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Parse => "parse",
Self::Type => "type",
Self::Invalid => "invalid",
Self::Unsupported => "unsupported",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Error {
kind: ErrorKind,
message: &'static str,
}
impl Error {
#[must_use]
pub const fn new(kind: ErrorKind, message: &'static str) -> Self {
Self { kind, message }
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub const fn message(&self) -> &'static str {
self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.kind.as_str(), self.message)
}
}
impl core::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_error_says_the_kind_and_the_rule() {
let error = Error::new(ErrorKind::Invalid, "low_ms must be below high_ms");
assert_eq!(error.kind(), ErrorKind::Invalid);
assert_eq!(error.message(), "low_ms must be below high_ms");
}
#[test]
fn it_is_copy_so_it_can_go_in_a_status_register() {
let error = Error::new(ErrorKind::Parse, "bad");
let copied = error;
assert_eq!(error, copied);
}
}