use std::{fmt, str::FromStr};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Level {
Error = 0,
Warn = 1,
#[default]
Info = 2,
Debug = 3,
Trace = 4,
}
impl Level {
pub const ALL: [Self; 5] = [
Self::Error,
Self::Warn,
Self::Info,
Self::Debug,
Self::Trace,
];
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::Error => "ERROR",
Self::Warn => "WARN",
Self::Info => "INFO",
Self::Debug => "DEBUG",
Self::Trace => "TRACE",
}
}
#[must_use]
pub const fn is_at_least(&self, other: Self) -> bool {
(*self as u8) <= (other as u8)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseLevelError;
impl fmt::Display for ParseLevelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown log level")
}
}
impl std::error::Error for ParseLevelError {}
impl FromStr for Level {
type Err = ParseLevelError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"error" | "err" => Ok(Self::Error),
"warn" | "warning" => Ok(Self::Warn),
"info" => Ok(Self::Info),
"debug" => Ok(Self::Debug),
"trace" => Ok(Self::Trace),
_ => Err(ParseLevelError),
}
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}