openformula_kernel/
number.rs1use core::cmp::Ordering;
2use core::fmt;
3
4use crate::{CalcError, CalcResult};
5
6#[derive(Clone, Copy, Debug)]
7enum Repr {
8 Integer(i64),
9 Real(f64),
10}
11
12#[derive(Clone, Copy, Debug)]
14pub struct Number(Repr);
15
16impl Number {
17 #[must_use]
19 pub const fn from_i64(value: i64) -> Self {
20 Self(Repr::Integer(value))
21 }
22
23 pub fn try_from_f64(value: f64) -> CalcResult<Self> {
28 if !value.is_finite() {
29 return Err(CalcError::num("number must be finite"));
30 }
31 Ok(Self(Repr::Real(normalize_zero(value))))
32 }
33
34 #[must_use]
36 pub const fn as_f64(self) -> f64 {
37 match self.0 {
38 Repr::Integer(value) => value as f64,
39 Repr::Real(value) => value,
40 }
41 }
42
43 #[must_use]
45 pub const fn as_i64(self) -> Option<i64> {
46 match self.0 {
47 Repr::Integer(value) => Some(value),
48 Repr::Real(_) => None,
49 }
50 }
51
52 #[must_use]
55 pub fn as_i64_exact(self) -> Option<i64> {
56 match self.0 {
57 Repr::Integer(value) => Some(value),
58 Repr::Real(value)
59 if value >= i64::MIN as f64
60 && value < -(i64::MIN as f64)
61 && libm::trunc(value) == value =>
62 {
63 Some(value as i64)
64 }
65 Repr::Real(_) => None,
66 }
67 }
68
69 #[must_use]
71 pub fn is_zero(self) -> bool {
72 self.as_f64() == 0.0
73 }
74
75 #[must_use]
77 pub fn is_integral(self) -> bool {
78 match self.0 {
79 Repr::Integer(_) => true,
80 Repr::Real(value) => libm::trunc(value) == value,
81 }
82 }
83
84 pub(crate) fn checked_add(self, other: Self) -> CalcResult<Self> {
85 match (self.0, other.0) {
86 (Repr::Integer(left), Repr::Integer(right)) => left
87 .checked_add(right)
88 .map(Self::from_i64)
89 .ok_or_else(|| CalcError::num("integer addition overflow")),
90 _ => Self::try_from_f64(self.as_f64() + other.as_f64()),
91 }
92 }
93
94 pub(crate) fn checked_abs(self) -> CalcResult<Self> {
95 match self.0 {
96 Repr::Integer(value) => value
97 .checked_abs()
98 .map(Self::from_i64)
99 .ok_or_else(|| CalcError::num("integer absolute-value overflow")),
100 Repr::Real(value) => Self::try_from_f64(libm::fabs(value)),
101 }
102 }
103}
104
105impl From<i64> for Number {
106 fn from(value: i64) -> Self {
107 Self::from_i64(value)
108 }
109}
110
111impl PartialEq for Number {
112 fn eq(&self, other: &Self) -> bool {
113 self.as_f64() == other.as_f64()
114 }
115}
116
117impl PartialOrd for Number {
118 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
119 self.as_f64().partial_cmp(&other.as_f64())
120 }
121}
122
123impl fmt::Display for Number {
124 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self.0 {
126 Repr::Integer(value) => value.fmt(formatter),
127 Repr::Real(value) => value.fmt(formatter),
128 }
129 }
130}
131
132pub(crate) fn normalize_zero(value: f64) -> f64 {
133 if value == 0.0 {
134 0.0
135 } else {
136 value
137 }
138}