use std::fmt;
macro_rules! format_err {
($kind:path, $msg:expr) => {
crate::error::Error::new(
$kind,
Some($msg.to_string())
)
};
($kind:path, $fmt:expr, $($arg:tt)+) => {
format_err!($kind, format!($fmt, $($arg)+))
};
}
macro_rules! fail {
($kind:path, $msg:expr) => {
Err(format_err!($kind, $msg))?
};
($kind:path, $fmt:expr, $($arg:tt)+) => {
fail!($kind, format!($fmt, $($arg)+))
};
}
#[derive(Clone, Debug)]
pub struct Error {
kind: ErrorKind,
msg: Option<String>,
}
impl Error {
pub fn new(kind: ErrorKind, msg: Option<String>) -> Self {
Error { kind, msg }
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ref msg) = self.msg {
write!(f, "{}: {}", self.kind, msg)
} else {
write!(f, "{}", self.kind)
}
}
}
impl std::error::Error for Error {}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
Parse,
Version,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrorKind::Parse => write!(f, "parse error"),
ErrorKind::Version => write!(f, "unsupported CVSS version"),
}
}
}