use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use serde::Serialize;
use crate::error::Error;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub enum Level {
Emergency,
Alert,
Critical,
Error,
Warning,
Notice,
Info,
Debug
}
impl Level {
pub fn above(&self, other: &Self) -> bool {
self.severity() < other.severity()
}
pub fn below(&self, other: &Self) -> bool {
self.severity() > other.severity()
}
pub fn name(&self) -> &'static str {
match self {
Level::Emergency => "emergency",
Level::Alert => "alert",
Level::Critical => "critical",
Level::Error => "error",
Level::Warning => "warning",
Level::Notice => "notice",
Level::Info => "info",
Level::Debug => "debug",
}
}
pub fn severity(&self) -> i8 {
match self {
Level::Debug => 7,
Level::Info => 6,
Level::Notice => 5,
Level::Warning => 4,
Level::Error => 3,
Level::Critical => 2,
Level::Alert => 1,
Level::Emergency => 0,
}
}
pub fn from_name(name: &str) -> Result<Self, Error> {
match name.as_bytes() {
b"debug" => Ok(Self::Debug),
b"info" => Ok(Self::Info),
b"notice" => Ok(Self::Notice),
b"warning" => Ok(Self::Warning),
b"error" => Ok(Self::Error),
b"critical" => Ok(Self::Critical),
b"alert" => Ok(Self::Alert),
b"emergency" => Ok(Self::Emergency),
_ => Err(Error::InvalidLevel(name.to_string())),
}
}
pub fn from_severity(severity: i8) -> Result<Self, Error> {
match severity {
0 => Ok(Self::Emergency),
1 => Ok(Self::Alert),
2 => Ok(Self::Critical),
3 => Ok(Self::Error),
4 => Ok(Self::Warning),
5 => Ok(Self::Notice),
6 => Ok(Self::Info),
7 => Ok(Self::Debug),
_ => Err(Error::InvalidSeverity(severity)),
}
}
}
impl Display for Level {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
impl FromStr for Level {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_name(s)
}
}
impl PartialOrd for Level {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Level {
fn cmp(&self, other: &Self) -> Ordering {
self.severity().cmp(&other.severity()).reverse()
}
}