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/release-2.2.1-bugfixes/types.asciidoc#14-number-type>
4
5use std::{borrow::Cow, fmt};
6
7use rust_decimal::Decimal;
8
9use crate::{
10    into_caveat, json,
11    warning::{self, IntoCaveat},
12};
13
14/// The scale for numerical values as defined in the OCPI spec.
15///
16/// See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/types.asciidoc#14-number-type>
17pub const SCALE: u32 = 4;
18
19/// The warnings that can happen when parsing or linting a numerical value.
20#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
21pub enum WarningKind {
22    /// Numerical strings do not need escape codes.
23    ContainsEscapeCodes,
24
25    /// The value provided exceeds `Decimal::MAX`.
26    ExceedsMaximumPossibleValue,
27
28    /// The JSON value given is not a number.
29    InvalidType,
30
31    /// The value provided is less than `Decimal::MIN`.
32    LessThanMinimumPossibleValue,
33
34    /// An underflow is when there are more fractional digits than can be represented within `Decimal`.
35    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 mut warnings = warning::Set::new();
83        let value = elem.as_value();
84
85        let Some(s) = value.as_number() else {
86            warnings.with_elem(WarningKind::InvalidType, elem);
87            return Err(warnings);
88        };
89
90        let mut decimal = match Decimal::from_str_exact(s) {
91            Ok(v) => v,
92            Err(err) => {
93                let kind = match err {
94                    rust_decimal::Error::ExceedsMaximumPossibleValue => {
95                        WarningKind::ExceedsMaximumPossibleValue
96                    }
97                    rust_decimal::Error::LessThanMinimumPossibleValue => {
98                        WarningKind::LessThanMinimumPossibleValue
99                    }
100                    rust_decimal::Error::Underflow => WarningKind::Underflow,
101                    rust_decimal::Error::ConversionTo(_) => unreachable!("This is only triggered when converting to numerical types"),
102                    rust_decimal::Error::ErrorString(_) => unreachable!("rust_decimal docs state: This is a legacy/deprecated error type retained for backwards compatibility."),
103                    rust_decimal::Error::ScaleExceedsMaximumPrecision(_) => unreachable!("`Decimal::from_str_exact` uses a scale of zero")
104                };
105
106                warnings.with_elem(kind, elem);
107                return Err(warnings);
108            }
109        };
110
111        decimal.rescale(SCALE);
112        Ok(decimal.into_caveat(warnings))
113    }
114}
115
116pub(crate) trait FromDecimal {
117    fn from_decimal(d: Decimal) -> Self;
118}
119
120/// All `Decimal`s should be rescaled to scale defined in the OCPI specs.
121///
122/// See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/types.asciidoc#14-number-type>
123impl FromDecimal for Decimal {
124    fn from_decimal(mut d: Decimal) -> Self {
125        d.rescale(SCALE);
126        d
127    }
128}
129
130/// Impl a `Decimal` based newtype.
131///
132/// All `Decimal` newtypes impl and `serde::Deserialize` which apply the precision
133/// defined in the OCPI spec.
134///
135/// <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/types.asciidoc#14-number-type>
136#[doc(hidden)]
137#[macro_export]
138macro_rules! impl_dec_newtype {
139    ($kind:ident, $unit:literal) => {
140        impl $kind {
141            #[must_use]
142            pub fn zero() -> Self {
143                use num_traits::Zero as _;
144
145                Self(Decimal::zero())
146            }
147
148            pub fn is_zero(&self) -> bool {
149                self.0.is_zero()
150            }
151
152            /// Round this number to the OCPI specified amount of decimals.
153            #[must_use]
154            pub fn rescale(mut self) -> Self {
155                self.0.rescale(number::SCALE);
156                Self(self.0)
157            }
158
159            #[must_use]
160            pub fn round_dp(self, digits: u32) -> Self {
161                Self(self.0.round_dp(digits))
162            }
163        }
164
165        impl $crate::number::FromDecimal for $kind {
166            fn from_decimal(mut d: Decimal) -> Self {
167                d.rescale($crate::number::SCALE);
168                Self(d)
169            }
170        }
171
172        impl std::fmt::Display for $kind {
173            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174                // Avoid writing needless "0.000"
175                if self.0.is_zero() {
176                    write!(f, "0{}", $unit)
177                } else {
178                    write!(f, "{:.4}{}", self.0, $unit)
179                }
180            }
181        }
182
183        /// The user can convert a `Decimal` newtype to a `Decimal` But cannot create
184        /// a `Decimal` newtype from a `Decimal`.
185        impl From<$kind> for rust_decimal::Decimal {
186            fn from(value: $kind) -> Self {
187                value.0
188            }
189        }
190
191        #[cfg(test)]
192        impl From<u64> for $kind {
193            fn from(value: u64) -> Self {
194                Self(value.into())
195            }
196        }
197
198        #[cfg(test)]
199        impl From<rust_decimal::Decimal> for $kind {
200            fn from(value: rust_decimal::Decimal) -> Self {
201                Self(value)
202            }
203        }
204
205        impl $crate::SaturatingAdd for $kind {
206            fn saturating_add(self, other: Self) -> Self {
207                Self(self.0.saturating_add(other.0))
208            }
209        }
210
211        impl $crate::SaturatingSub for $kind {
212            fn saturating_sub(self, other: Self) -> Self {
213                Self(self.0.saturating_sub(other.0))
214            }
215        }
216
217        impl $crate::json::FromJson<'_, '_> for $kind {
218            type WarningKind = $crate::number::WarningKind;
219
220            fn from_json(elem: &json::Element<'_>) -> $crate::Verdict<Self, Self::WarningKind> {
221                rust_decimal::Decimal::from_json(elem).map(|v| v.map(Self))
222            }
223        }
224
225        #[cfg(test)]
226        impl $crate::test::ApproxEq for $kind {
227            fn approx_eq(&self, other: &Self) -> bool {
228                const TOLERANCE: Decimal = rust_decimal_macros::dec!(0.1);
229                const PRECISION: u32 = 2;
230
231                $crate::test::approx_eq_dec(self.0, other.0, TOLERANCE, PRECISION)
232            }
233        }
234    };
235}
236
237#[cfg(test)]
238mod test {
239    use rust_decimal::Decimal;
240    use rust_decimal_macros::dec;
241
242    use crate::test::{approx_eq_dec, ApproxEq};
243
244    impl ApproxEq for Decimal {
245        fn approx_eq(&self, other: &Self) -> bool {
246            const TOLERANCE: Decimal = dec!(0.1);
247            const PRECISION: u32 = 2;
248
249            approx_eq_dec(*self, *other, TOLERANCE, PRECISION)
250        }
251    }
252}