use std::fmt;
use std::str::FromStr;
use super::ErrorKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum ErrorCode {
InvalidOperator,
InvalidArguments,
VariableNotFound,
InvalidContextLevel,
TypeError,
ArithmeticError,
Custom,
ParseError,
Thrown,
FormatError,
IndexOutOfBounds,
ConfigurationError,
BudgetExceeded,
}
impl ErrorCode {
pub const ALL: &'static [ErrorCode] = &[
ErrorCode::InvalidOperator,
ErrorCode::InvalidArguments,
ErrorCode::VariableNotFound,
ErrorCode::InvalidContextLevel,
ErrorCode::TypeError,
ErrorCode::ArithmeticError,
ErrorCode::Custom,
ErrorCode::ParseError,
ErrorCode::Thrown,
ErrorCode::FormatError,
ErrorCode::IndexOutOfBounds,
ErrorCode::ConfigurationError,
ErrorCode::BudgetExceeded,
];
pub const fn as_str(self) -> &'static str {
match self {
ErrorCode::InvalidOperator => "InvalidOperator",
ErrorCode::InvalidArguments => "InvalidArguments",
ErrorCode::VariableNotFound => "VariableNotFound",
ErrorCode::InvalidContextLevel => "InvalidContextLevel",
ErrorCode::TypeError => "TypeError",
ErrorCode::ArithmeticError => "ArithmeticError",
ErrorCode::Custom => "Custom",
ErrorCode::ParseError => "ParseError",
ErrorCode::Thrown => "Thrown",
ErrorCode::FormatError => "FormatError",
ErrorCode::IndexOutOfBounds => "IndexOutOfBounds",
ErrorCode::ConfigurationError => "ConfigurationError",
ErrorCode::BudgetExceeded => "BudgetExceeded",
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownErrorCode;
impl fmt::Display for UnknownErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("unknown error code")
}
}
impl std::error::Error for UnknownErrorCode {}
impl FromStr for ErrorCode {
type Err = UnknownErrorCode;
fn from_str(s: &str) -> Result<Self, Self::Err> {
ErrorCode::ALL
.iter()
.copied()
.find(|code| code.as_str() == s)
.ok_or(UnknownErrorCode)
}
}
impl ErrorKind {
pub const fn code(&self) -> ErrorCode {
match self {
ErrorKind::InvalidOperator(_) => ErrorCode::InvalidOperator,
ErrorKind::InvalidArguments(_) => ErrorCode::InvalidArguments,
ErrorKind::VariableNotFound(_) => ErrorCode::VariableNotFound,
ErrorKind::InvalidContextLevel(_) => ErrorCode::InvalidContextLevel,
ErrorKind::TypeError(_) => ErrorCode::TypeError,
ErrorKind::ArithmeticError(_) => ErrorCode::ArithmeticError,
ErrorKind::Custom(_) => ErrorCode::Custom,
ErrorKind::ParseError(_) => ErrorCode::ParseError,
ErrorKind::Thrown(_) => ErrorCode::Thrown,
ErrorKind::FormatError(_) => ErrorCode::FormatError,
ErrorKind::IndexOutOfBounds { .. } => ErrorCode::IndexOutOfBounds,
ErrorKind::ConfigurationError(_) => ErrorCode::ConfigurationError,
ErrorKind::BudgetExceeded { .. } => ErrorCode::BudgetExceeded,
}
}
}