openformula_kernel/
error.rs1use alloc::string::{String, ToString};
2use core::fmt;
3
4pub type CalcResult<T = crate::Value> = Result<T, CalcError>;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum CalcErrorKind {
10 Null,
12 DivZero,
14 Value,
16 Ref,
18 Name,
20 Num,
22 NotAvailable,
24 Limit,
26 Unsupported,
28}
29
30impl CalcErrorKind {
31 #[must_use]
33 pub const fn code(self) -> &'static str {
34 match self {
35 Self::Null => "#NULL!",
36 Self::DivZero => "#DIV/0!",
37 Self::Value => "#VALUE!",
38 Self::Ref => "#REF!",
39 Self::Name => "#NAME?",
40 Self::Num => "#NUM!",
41 Self::NotAvailable => "#N/A",
42 Self::Limit => "#LIMIT!",
43 Self::Unsupported => "#UNSUPPORTED!",
44 }
45 }
46}
47
48#[derive(Clone, Debug, PartialEq, Eq, Hash)]
50pub struct CalcError {
51 kind: CalcErrorKind,
52 message: String,
53}
54
55impl CalcError {
56 #[must_use]
58 pub fn new(kind: CalcErrorKind, message: impl Into<String>) -> Self {
59 Self {
60 kind,
61 message: message.into(),
62 }
63 }
64
65 #[must_use]
67 pub const fn kind(&self) -> CalcErrorKind {
68 self.kind
69 }
70
71 #[must_use]
73 pub const fn code(&self) -> &'static str {
74 self.kind.code()
75 }
76
77 #[must_use]
79 pub fn message(&self) -> &str {
80 &self.message
81 }
82
83 pub(crate) fn value(message: impl Into<String>) -> Self {
84 Self::new(CalcErrorKind::Value, message)
85 }
86
87 pub(crate) fn num(message: impl Into<String>) -> Self {
88 Self::new(CalcErrorKind::Num, message)
89 }
90
91 pub(crate) fn name(message: impl Into<String>) -> Self {
92 Self::new(CalcErrorKind::Name, message)
93 }
94}
95
96impl fmt::Display for CalcError {
97 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98 write!(formatter, "{} {}", self.code(), self.message)
99 }
100}
101
102#[cfg(feature = "std")]
103impl std::error::Error for CalcError {}
104
105impl From<CalcErrorKind> for CalcError {
106 fn from(kind: CalcErrorKind) -> Self {
107 Self::new(kind, kind.code().to_string())
108 }
109}