use std::fmt;
#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct ErrorCode(&'static str);
impl ErrorCode {
#[doc(hidden)]
pub const fn new(code: &'static str) -> Self {
assert!(
matches!(code.as_bytes(), [b'E', b'0'..=b'9', b'0'..=b'9', b'0'..=b'9', b'0'..=b'9']),
"Error codes must start with a capital `E` followed by 4 decimal digits."
);
Self(code)
}
pub fn display_bracketed(self) -> String {
format!("[{self}]")
}
pub fn as_str(&self) -> &str {
self.0
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.0, f)
}
}
#[macro_export]
macro_rules! error_code {
($code:expr) => {{
use $crate::ErrorCode;
const ENSURE_CONST: ErrorCode = ErrorCode::new(stringify!($code));
ENSURE_CONST
}};
}
pub trait OptionErrorCodeExt {
fn display_bracketed(self) -> String;
}
impl OptionErrorCodeExt for Option<ErrorCode> {
fn display_bracketed(self) -> String {
self.map(ErrorCode::display_bracketed).unwrap_or_default()
}
}