1#[cfg(test)]
6mod test_approx_eq;
7
8#[cfg(test)]
9mod test_display;
10
11#[cfg(test)]
12mod test_round_to_ocpi;
13
14#[cfg(test)]
15mod test_from_schema;
16
17use std::{fmt, num::IntErrorKind};
18
19use rust_decimal::Decimal;
20
21use crate::{LowerSchema, json, schema, warning};
22
23pub const SCALE: u32 = 4;
31
32pub(crate) const ROUNDING_STRATEGY: rust_decimal::RoundingStrategy =
36 rust_decimal::RoundingStrategy::MidpointNearestEven;
37
38#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
40pub enum Warning {
41 ContainsEscapeCodes,
43
44 Decimal(String),
46
47 Decode(json::decode::Warning),
49
50 ExceedsMaximumPossibleValue,
52
53 LessThanMinimumPossibleValue,
55
56 Underflow,
58}
59
60impl From<json::decode::Warning> for Warning {
61 fn from(warning: json::decode::Warning) -> Self {
62 Self::Decode(warning)
63 }
64}
65
66impl fmt::Display for Warning {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 match self {
69 Self::ContainsEscapeCodes => {
70 f.write_str("The value contains escape codes but it does not need them")
71 }
72 Self::Decimal(msg) => write!(f, "{msg}"),
73 Self::Decode(warning) => fmt::Display::fmt(warning, f),
74 Self::ExceedsMaximumPossibleValue => {
75 f.write_str("The value provided exceeds `79,228,162,514,264,337,593,543,950,335`.")
76 }
77 Self::LessThanMinimumPossibleValue => f.write_str(
78 "The value provided is less than `-79,228,162,514,264,337,593,543,950,335`.",
79 ),
80 Self::Underflow => {
81 f.write_str("An underflow is when there are more than 28 fractional digits")
82 }
83 }
84 }
85}
86
87impl crate::Warning for Warning {
88 fn id(&self) -> warning::Id {
89 match self {
90 Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
91 Self::Decimal(_) => warning::Id::from_static("decimal"),
92 Self::Decode(warning) => warning.id(),
93 Self::ExceedsMaximumPossibleValue => {
94 warning::Id::from_static("exceeds_maximum_possible_value")
95 }
96 Self::LessThanMinimumPossibleValue => {
97 warning::Id::from_static("less_than_minimum_possible_value")
98 }
99 Self::Underflow => warning::Id::from_static("underflow"),
100 }
101 }
102}
103
104pub(crate) fn int_error_kind_as_str(kind: IntErrorKind) -> &'static str {
105 match kind {
106 IntErrorKind::Empty => "empty",
107 IntErrorKind::InvalidDigit => "invalid digit",
108 IntErrorKind::PosOverflow => "positive overflow",
109 IntErrorKind::NegOverflow => "negative overflow",
110 IntErrorKind::Zero => "zero",
111 _ => "unknown",
112 }
113}
114
115impl<'buf> LowerSchema<'buf, schema::Number<'buf>> for Decimal {
116 type Warning = Warning;
117
118 fn lower_schema(
119 source: &schema::Number<'buf>,
120 warnings: &mut dyn warning::Gather<Warning>,
121 ) -> Result<Self, warning::Error<Warning>> {
122 let (elem, digits) = match source {
126 schema::Number::Number { elem, digits } => (elem, *digits),
127 schema::Number::StringEncoded { elem, value } => {
128 let pending_str = value.has_escapes(elem, &mut warning::Converting::new(warnings));
129
130 match pending_str {
131 json::PendingStr::NoEscapes(s) => (elem, s),
132 json::PendingStr::HasEscapes => {
133 return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
134 }
135 }
136 }
137 };
138
139 let decimal = match Decimal::from_str_exact(digits) {
140 Ok(v) => v,
141 Err(err) => {
142 let kind = match err {
143 rust_decimal::Error::ExceedsMaximumPossibleValue => {
144 Warning::ExceedsMaximumPossibleValue
145 }
146 rust_decimal::Error::LessThanMinimumPossibleValue => {
147 Warning::LessThanMinimumPossibleValue
148 }
149 rust_decimal::Error::Underflow => Warning::Underflow,
150 rust_decimal::Error::ConversionTo(_) => {
151 unreachable!("This is only triggered when converting to numerical types")
152 }
153 rust_decimal::Error::ErrorString(msg) => Warning::Decimal(msg),
154 rust_decimal::Error::ScaleExceedsMaximumPrecision(_) => {
155 unreachable!("`Decimal::from_str_exact` uses a scale of zero")
156 }
157 };
158
159 return Err(warning::Error::new(elem, kind));
160 }
161 };
162
163 Ok(decimal)
164 }
165}
166
167pub(crate) trait FromDecimal {
168 fn from_decimal(d: Decimal) -> Self;
169}
170
171pub trait RoundDecimal {
175 #[must_use]
179 fn round_to_ocpi_scale(self) -> Self;
180}
181
182impl RoundDecimal for Decimal {
183 fn round_to_ocpi_scale(self) -> Self {
184 self.round_dp_with_strategy(SCALE, ROUNDING_STRATEGY)
185 }
186}
187
188impl<T: RoundDecimal> RoundDecimal for Option<T> {
189 fn round_to_ocpi_scale(self) -> Self {
190 self.map(RoundDecimal::round_to_ocpi_scale)
191 }
192}
193
194pub(crate) trait IsZero {
199 fn is_zero(&self) -> bool;
201}
202
203pub(crate) fn approx_eq_dec(a: &Decimal, b: &Decimal, tolerance: Decimal) -> bool {
205 let Some(diff) = a.checked_sub(*b) else {
208 return false;
209 };
210 diff.abs() <= tolerance
212}
213
214#[doc(hidden)]
221#[macro_export]
222macro_rules! impl_dec_newtype {
223 ($kind:ident, $unit:literal) => {
224 impl $kind {
225 #[must_use]
226 pub fn round_dp(self, digits: u32) -> Self {
228 Self(self.0.round_dp(digits))
229 }
230 }
231
232 impl $crate::number::FromDecimal for $kind {
233 fn from_decimal(d: Decimal) -> Self {
234 Self(d)
235 }
236 }
237
238 impl $crate::number::RoundDecimal for $kind {
239 fn round_to_ocpi_scale(self) -> Self {
240 Self(self.0.round_to_ocpi_scale())
241 }
242 }
243
244 impl std::fmt::Display for $kind {
245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 use $crate::number::RoundDecimal as _;
247
248 if self.0.is_zero() {
254 if f.alternate() {
255 write!(f, "0")
256 } else {
257 write!(f, "0{}", $unit)
258 }
259 } else {
260 let value = self.0.round_to_ocpi_scale();
265
266 if f.alternate() {
267 write!(f, "{:.4}", value)
268 } else {
269 write!(f, "{:.4}{}", value, $unit)
270 }
271 }
272 }
273 }
274
275 impl From<$kind> for rust_decimal::Decimal {
278 fn from(value: $kind) -> Self {
279 value.0
280 }
281 }
282
283 #[cfg(test)]
284 impl From<rust_decimal::Decimal> for $kind {
285 fn from(value: rust_decimal::Decimal) -> Self {
286 Self(value)
287 }
288 }
289
290 impl $crate::SaturatingAdd for $kind {
291 fn saturating_add(self, other: Self) -> Self {
292 Self(self.0.saturating_add(other.0))
293 }
294 }
295
296 impl $crate::SaturatingSub for $kind {
297 fn saturating_sub(self, other: Self) -> Self {
298 Self(self.0.saturating_sub(other.0))
299 }
300 }
301
302 impl<'buf> $crate::LowerSchema<'buf, $crate::schema::Number<'buf>> for $kind {
303 type Warning = $crate::number::Warning;
304
305 fn lower_schema(
306 source: &$crate::schema::Number<'buf>,
307 warnings: &mut dyn $crate::warning::Gather<Self::Warning>,
308 ) -> Result<Self, $crate::warning::Error<Self::Warning>> {
309 let decimal: rust_decimal::Decimal =
310 $crate::FromSchema::from_schema(source, warnings)?;
311 Ok(Self(decimal))
312 }
313 }
314
315 #[cfg(test)]
316 impl $crate::test::ApproxEq for $kind {
317 type Tolerance = Decimal;
318
319 fn default_tolerance() -> Self::Tolerance {
320 rust_decimal_macros::dec!(0.1)
321 }
322
323 fn approx_eq_tolerance(&self, other: &Self, tolerance: Decimal) -> bool {
324 $crate::number::approx_eq_dec(&self.0, &other.0, tolerance)
325 }
326 }
327 };
328}