use alloc::string::{String, ToString};
use core::fmt;
pub type CalcResult<T = crate::Value> = Result<T, CalcError>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CalcErrorKind {
Null,
DivZero,
Value,
Ref,
Name,
Num,
NotAvailable,
Limit,
Unsupported,
}
impl CalcErrorKind {
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::Null => "#NULL!",
Self::DivZero => "#DIV/0!",
Self::Value => "#VALUE!",
Self::Ref => "#REF!",
Self::Name => "#NAME?",
Self::Num => "#NUM!",
Self::NotAvailable => "#N/A",
Self::Limit => "#LIMIT!",
Self::Unsupported => "#UNSUPPORTED!",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CalcError {
kind: CalcErrorKind,
message: String,
}
impl CalcError {
#[must_use]
pub fn new(kind: CalcErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
#[must_use]
pub const fn kind(&self) -> CalcErrorKind {
self.kind
}
#[must_use]
pub const fn code(&self) -> &'static str {
self.kind.code()
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
pub(crate) fn value(message: impl Into<String>) -> Self {
Self::new(CalcErrorKind::Value, message)
}
pub(crate) fn num(message: impl Into<String>) -> Self {
Self::new(CalcErrorKind::Num, message)
}
pub(crate) fn name(message: impl Into<String>) -> Self {
Self::new(CalcErrorKind::Name, message)
}
}
impl fmt::Display for CalcError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{} {}", self.code(), self.message)
}
}
#[cfg(feature = "std")]
impl std::error::Error for CalcError {}
impl From<CalcErrorKind> for CalcError {
fn from(kind: CalcErrorKind) -> Self {
Self::new(kind, kind.code().to_string())
}
}