1use std::{borrow::Cow, fmt};
6
7use rust_decimal::Decimal;
8
9use crate::{
10 into_caveat, json,
11 warning::{self, IntoCaveat},
12};
13
14pub const SCALE: u32 = 4;
18
19#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
21pub enum WarningKind {
22 ContainsEscapeCodes,
24
25 ExceedsMaximumPossibleValue,
27
28 InvalidType,
30
31 LessThanMinimumPossibleValue,
33
34 Underflow,
36}
37
38impl fmt::Display for WarningKind {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 WarningKind::ContainsEscapeCodes => write!(
42 f,
43 "The value contains escape codes but it does not need them"
44 ),
45 WarningKind::InvalidType => write!(f, "The value should be a number."),
46 WarningKind::ExceedsMaximumPossibleValue => {
47 write!(
48 f,
49 "The value provided exceeds `79,228,162,514,264,337,593,543,950,335`."
50 )
51 }
52 WarningKind::LessThanMinimumPossibleValue => write!(
53 f,
54 "The value provided is less than `-79,228,162,514,264,337,593,543,950,335`."
55 ),
56 WarningKind::Underflow => write!(
57 f,
58 "An underflow is when there are more than 28 fractional digits"
59 ),
60 }
61 }
62}
63
64impl warning::Kind for WarningKind {
65 fn id(&self) -> Cow<'static, str> {
66 match self {
67 WarningKind::ContainsEscapeCodes => "contains_escape_codes".into(),
68 WarningKind::InvalidType => "invalid_type".into(),
69 WarningKind::ExceedsMaximumPossibleValue => "exceeds_maximum_possible_value".into(),
70 WarningKind::LessThanMinimumPossibleValue => "less_than_minimum_possible_value".into(),
71 WarningKind::Underflow => "underflow".into(),
72 }
73 }
74}
75
76into_caveat!(Decimal);
77
78impl json::FromJson<'_, '_> for Decimal {
79 type WarningKind = WarningKind;
80
81 fn from_json(elem: &json::Element<'_>) -> crate::Verdict<Self, Self::WarningKind> {
82 let warnings = warning::Set::new();
83 let value = elem.as_value();
84
85 let Some(s) = value.as_number() else {
86 return warnings.bail(WarningKind::InvalidType, elem);
87 };
88
89 let mut decimal = match Decimal::from_str_exact(s) {
90 Ok(v) => v,
91 Err(err) => {
92 let kind = match err {
93 rust_decimal::Error::ExceedsMaximumPossibleValue => {
94 WarningKind::ExceedsMaximumPossibleValue
95 }
96 rust_decimal::Error::LessThanMinimumPossibleValue => {
97 WarningKind::LessThanMinimumPossibleValue
98 }
99 rust_decimal::Error::Underflow => WarningKind::Underflow,
100 rust_decimal::Error::ConversionTo(_) => unreachable!("This is only triggered when converting to numerical types"),
101 rust_decimal::Error::ErrorString(_) => unreachable!("rust_decimal docs state: This is a legacy/deprecated error type retained for backwards compatibility."),
102 rust_decimal::Error::ScaleExceedsMaximumPrecision(_) => unreachable!("`Decimal::from_str_exact` uses a scale of zero")
103 };
104
105 return warnings.bail(kind, elem);
106 }
107 };
108
109 decimal.rescale(SCALE);
110 Ok(decimal.into_caveat(warnings))
111 }
112}
113
114pub(crate) trait FromDecimal {
115 fn from_decimal(d: Decimal) -> Self;
116}
117
118impl FromDecimal for Decimal {
122 fn from_decimal(mut d: Decimal) -> Self {
123 d.rescale(SCALE);
124 d
125 }
126}
127
128#[doc(hidden)]
135#[macro_export]
136macro_rules! impl_dec_newtype {
137 ($kind:ident, $unit:literal) => {
138 impl $kind {
139 #[must_use]
140 pub fn zero() -> Self {
141 use num_traits::Zero as _;
142
143 Self(Decimal::zero())
144 }
145
146 pub fn is_zero(&self) -> bool {
147 self.0.is_zero()
148 }
149
150 #[must_use]
152 pub fn rescale(mut self) -> Self {
153 self.0.rescale(number::SCALE);
154 Self(self.0)
155 }
156
157 #[must_use]
158 pub fn round_dp(self, digits: u32) -> Self {
159 Self(self.0.round_dp(digits))
160 }
161 }
162
163 impl $crate::number::FromDecimal for $kind {
164 fn from_decimal(mut d: Decimal) -> Self {
165 d.rescale($crate::number::SCALE);
166 Self(d)
167 }
168 }
169
170 impl std::fmt::Display for $kind {
171 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172 if self.0.is_zero() {
174 write!(f, "0{}", $unit)
175 } else {
176 write!(f, "{:.4}{}", self.0, $unit)
177 }
178 }
179 }
180
181 impl From<$kind> for rust_decimal::Decimal {
184 fn from(value: $kind) -> Self {
185 value.0
186 }
187 }
188
189 #[cfg(test)]
190 impl From<u64> for $kind {
191 fn from(value: u64) -> Self {
192 Self(value.into())
193 }
194 }
195
196 #[cfg(test)]
197 impl From<f64> for $kind {
198 fn from(value: f64) -> Self {
199 Self(Decimal::from_f64_retain(value).unwrap())
200 }
201 }
202
203 #[cfg(test)]
204 impl From<rust_decimal::Decimal> for $kind {
205 fn from(value: rust_decimal::Decimal) -> Self {
206 Self(value)
207 }
208 }
209
210 impl $crate::SaturatingAdd for $kind {
211 fn saturating_add(self, other: Self) -> Self {
212 Self(self.0.saturating_add(other.0))
213 }
214 }
215
216 impl $crate::SaturatingSub for $kind {
217 fn saturating_sub(self, other: Self) -> Self {
218 Self(self.0.saturating_sub(other.0))
219 }
220 }
221
222 impl $crate::json::FromJson<'_, '_> for $kind {
223 type WarningKind = $crate::number::WarningKind;
224
225 fn from_json(elem: &json::Element<'_>) -> $crate::Verdict<Self, Self::WarningKind> {
226 rust_decimal::Decimal::from_json(elem).map(|v| v.map(Self))
227 }
228 }
229
230 #[cfg(test)]
231 impl $crate::test::ApproxEq for $kind {
232 fn approx_eq(&self, other: &Self) -> bool {
233 const TOLERANCE: Decimal = rust_decimal_macros::dec!(0.1);
234 const PRECISION: u32 = 2;
235
236 $crate::test::approx_eq_dec(self.0, other.0, TOLERANCE, PRECISION)
237 }
238 }
239 };
240}
241
242#[cfg(test)]
243mod test {
244 use rust_decimal::Decimal;
245 use rust_decimal_macros::dec;
246
247 use crate::test::{approx_eq_dec, ApproxEq};
248
249 impl ApproxEq for Decimal {
250 fn approx_eq(&self, other: &Self) -> bool {
251 const TOLERANCE: Decimal = dec!(0.1);
252 const PRECISION: u32 = 2;
253
254 approx_eq_dec(*self, *other, TOLERANCE, PRECISION)
255 }
256 }
257}