Skip to main content

ocpi_tariffs/
number.rs

1//! We represent the OCPI spec Number as a `Decimal` and serialize and deserialize to the precision defined in the OCPI spec.
2//!
3//! <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_number_type>.
4
5#[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
23/// The scale for numerical values as defined in the OCPI spec.
24///
25/// The spec fixes the number of decimals and says nothing about which way a tie goes, so
26/// the choice is ours: [`RoundDecimal::round_to_ocpi_scale`] rounds a tie to the even digit. Over
27/// many prices that does not drift upward the way rounding a tie away from zero does.
28///
29/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_number_type>.
30pub const SCALE: u32 = 4;
31
32/// The strategy for every reduction to a fixed number of decimals, named once so a value
33/// reduced for display and the same value reduced for output cannot land on different digits.
34/// [`SCALE`] states why a tie goes to the even digit.
35pub(crate) const ROUNDING_STRATEGY: rust_decimal::RoundingStrategy =
36    rust_decimal::RoundingStrategy::MidpointNearestEven;
37
38/// The warnings that can happen when parsing or linting a numerical value.
39#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
40pub enum Warning {
41    /// Numerical strings don't need to have escape-codes.
42    ContainsEscapeCodes,
43
44    /// Unable to convert string to a `Decimal`.
45    Decimal(String),
46
47    /// The field at the path could not be decoded.
48    Decode(json::decode::Warning),
49
50    /// The value provided exceeds `Decimal::MAX`.
51    ExceedsMaximumPossibleValue,
52
53    /// The value provided is less than `Decimal::MIN`.
54    LessThanMinimumPossibleValue,
55
56    /// An underflow is when there are more fractional digits than can be represented within `Decimal`.
57    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        // The schema already proved the literal form is a valid JSON number, so its
123        // `digits` are read directly. The string-encoded form carries an unchecked
124        // string, so it must be decoded (and an escaped string is rejected) here.
125        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
171/// Round a `Decimal` or `Decimal`-like value to the scale defined in the OCPI spec.
172///
173/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_number_type>.
174pub trait RoundDecimal {
175    /// Round a `Decimal` or `Decimal`-like value to the scale defined in the OCPI spec.
176    ///
177    /// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_number_type>.
178    #[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
194/// Allow a `Decimal` type to define its own precision when testing for zero.
195///
196/// Note: the `num_traits::Zero` trait is not used as it has extra requirements that
197/// the `ocpi-tariffs` `Decimal` types do not want/need to fulfill.
198pub(crate) trait IsZero {
199    /// Return true if the value is considered zero.
200    fn is_zero(&self) -> bool;
201}
202
203/// Approximately compare two `Decimal` values.
204pub(crate) fn approx_eq_dec(a: &Decimal, b: &Decimal, tolerance: Decimal) -> bool {
205    // If `a` and `b` are potentially equal then `a - b` should be close to zero.
206    // If the subtraction results in an overflow, then the numbers are nowhere near to being equal.
207    let Some(diff) = a.checked_sub(*b) else {
208        return false;
209    };
210    // We don't care about the sign of the difference when checking for equality.
211    diff.abs() <= tolerance
212}
213
214/// Impl a `Decimal` based newtype.
215///
216/// Every `Decimal` newtype rounds to the precision the OCPI spec defines for a number,
217/// both through `RoundDecimal` and when it is displayed.
218///
219/// <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/types.asciidoc#types_number_type>.
220#[doc(hidden)]
221#[macro_export]
222macro_rules! impl_dec_newtype {
223    ($kind:ident, $unit:literal) => {
224        impl $kind {
225            #[must_use]
226            /// Round the value to `digits` decimal places.
227            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                // Avoid writing needless "0.000"
249                //
250                // The zero test reads the value as given. Rounding first would report a
251                // rate too small to survive the scale as a plain "0", which is the one thing a
252                // rate must never be printed as.
253                if self.0.is_zero() {
254                    if f.alternate() {
255                        write!(f, "0")
256                    } else {
257                        write!(f, "0{}", $unit)
258                    }
259                } else {
260                    // `{:.4}` truncates rather than rounds, so it understates any value
261                    // carrying more than `number::SCALE` decimals. Round first, so a value that
262                    // reached the report unrounded prints the same digits as the same value
263                    // rounded on the way out.
264                    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        /// The user can convert a `Decimal` newtype to a `Decimal` But cannot create
276        /// a `Decimal` newtype from a `Decimal`.
277        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}