Skip to main content

oicp_kit/types/
number.rs

1//! `Number` — the OICP decimal number type. Never `f64` in a field, never `f64` in arithmetic.
2
3use core::fmt;
4use core::str::FromStr;
5
6use rust_decimal::Decimal;
7use rust_decimal::prelude::ToPrimitive;
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use super::validate::{Validate, Validator, ViolationCode};
11
12/// An OICP JSON `number`: an exact decimal.
13///
14/// # Why not `f64`
15///
16/// Every `number` in OICP is either energy or money: `ConsumedEnergy`, `MeterValueStart`,
17/// `MeterValueEnd`, `PricePerReferenceUnit`, `PricingDefaultPrice`. All of them end up on an
18/// invoice between two companies, and OICP's own CDR rule — `ConsumedEnergy` is *the difference
19/// between* `MeterValueEnd` *and* `MeterValueStart` — is an exact decimal identity that binary
20/// floating point cannot honour: `10.1 - 0.1 != 10.0` in `f64`.
21///
22/// So every OICP number in this crate is a [`rust_decimal::Decimal`]. No public field of any wire
23/// type is an `f32` or `f64`, the [`sync`](crate::sync) engine has none, and
24/// `cargo run -p xtask -- no-floats` enforces that in CI.
25///
26/// # The JSON boundary
27///
28/// OICP sends these as JSON *numbers*, not strings. `serde_json` represents a fractional JSON
29/// number as an `f64` unless its `arbitrary_precision` feature is enabled — a feature that changes
30/// `serde_json::Value` globally for every crate in the build, so `oicp-kit` does not impose it.
31/// The boundary therefore behaves as follows:
32///
33/// * Integral values pass through exactly, as JSON integers.
34/// * Fractional values with at most 15 significant decimal digits — which covers every price and
35///   energy OICP carries, with room to spare — pass through exactly, because the shortest decimal
36///   that round-trips an `f64` *is* the original decimal.
37/// * Beyond that, a round-trip rounds to the nearest `f64`. [`Number::json_round_trips`] says
38///   whether a given value is affected and [`Validate::validate`] reports it as
39///   [`ViolationCode::Imprecise`], so this can never happen silently.
40///
41/// A peer that sends a number as a JSON *string* (`"0.25"`) is tolerated on input and parsed
42/// exactly; output is always a JSON number.
43///
44/// ```
45/// use oicp_kit::types::Number;
46///
47/// let energy: Number = "10.1".parse().unwrap();
48/// let start: Number = "0.1".parse().unwrap();
49/// // The identity OICP requires of every CDR, exactly.
50/// assert_eq!((energy - start).to_string(), "10.0");
51/// assert_eq!(serde_json::to_string(&energy).unwrap(), "10.1");
52/// ```
53#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct Number(Decimal);
55
56impl Number {
57    /// Zero.
58    pub const ZERO: Self = Self(Decimal::ZERO);
59    /// One.
60    pub const ONE: Self = Self(Decimal::ONE);
61
62    /// Wraps a [`Decimal`].
63    #[must_use]
64    pub const fn new(value: Decimal) -> Self {
65        Self(value)
66    }
67
68    /// The underlying [`Decimal`].
69    #[must_use]
70    pub const fn get(self) -> Decimal {
71        self.0
72    }
73
74    /// The number of digits after the decimal point.
75    #[must_use]
76    pub fn scale(self) -> u32 {
77        self.0.scale()
78    }
79
80    /// Rounds to `dp` decimal places, half away from zero.
81    #[must_use]
82    pub fn round_dp(self, dp: u32) -> Self {
83        Self(self.0.round_dp_with_strategy(dp, rust_decimal::RoundingStrategy::MidpointAwayFromZero))
84    }
85
86    /// Whether this value survives a JSON round-trip unchanged.
87    ///
88    /// See [the type documentation](Self#the-json-boundary). `false` only for values with more
89    /// significant digits than an `f64` can carry.
90    #[must_use]
91    pub fn json_round_trips(self) -> bool {
92        if self.0.is_integer() && self.0.to_i64().is_some() {
93            return true;
94        }
95        self.0.to_f64().and_then(decimal_from_f64).is_some_and(|d| d == self.0.normalize())
96    }
97
98    /// Whether the value is zero.
99    #[must_use]
100    pub fn is_zero(self) -> bool {
101        self.0.is_zero()
102    }
103
104    /// Whether the value is strictly negative.
105    #[must_use]
106    pub fn is_negative(self) -> bool {
107        self.0.is_sign_negative() && !self.0.is_zero()
108    }
109
110    /// Whether the value is a whole number.
111    ///
112    /// OICP's property tables type several fields as `Integer` that the OpenAPI sources widened
113    /// to `number`; this is how the wire types check them without refusing the value.
114    #[must_use]
115    pub fn is_integer(self) -> bool {
116        self.0.is_integer()
117    }
118
119    /// Reports a violation unless the value lies within `min..=max` inclusive.
120    pub(crate) fn validate_range(self, v: &mut Validator, min: i64, max: i64) {
121        let (lo, hi) = (Decimal::from(min), Decimal::from(max));
122        if self.0 < lo || self.0 > hi {
123            v.report(
124                ViolationCode::OutOfRange,
125                format!("{} is outside the allowed range {min}..={max}", self.0),
126            );
127        }
128    }
129
130    /// As [`validate_range`](Self::validate_range), but for a bound the specification states and
131    /// real equipment exceeds.
132    ///
133    /// The message names the [`SpecDefect`](super::SpecDefect), so a partner with a perfectly good
134    /// 500 A charger reads "OICP 2.3 caps this at 99 A, here is the issue" rather than concluding
135    /// that this crate cannot count.
136    pub(crate) fn validate_range_with_defect(self, v: &mut Validator, min: i64, max: i64, defect: &str) {
137        let (lo, hi) = (Decimal::from(min), Decimal::from(max));
138        if self.0 < lo || self.0 > hi {
139            let note = super::SpecDefect::get(defect).map_or_else(String::new, |d| format!("; {}", d.note()));
140            v.report(
141                ViolationCode::OutOfRange,
142                format!("{} is outside the allowed range {min}..={max}{note}", self.0),
143            );
144        }
145    }
146}
147
148/// Reconstructs a decimal from an `f64` the way `serde_json` would print it — via the shortest
149/// representation that round-trips — so `json_round_trips` compares like with like.
150fn decimal_from_f64(f: f64) -> Option<Decimal> {
151    Decimal::from_str(&format!("{f}")).ok().map(|d| d.normalize())
152}
153
154impl Validate for Number {
155    fn validate_in(&self, v: &mut Validator) {
156        if !self.json_round_trips() {
157            v.report(
158                ViolationCode::Imprecise,
159                format!("{} carries more significant digits than a JSON number round-trip preserves", self.0),
160            );
161        }
162    }
163}
164
165impl fmt::Display for Number {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        fmt::Display::fmt(&self.0, f)
168    }
169}
170
171impl fmt::Debug for Number {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        write!(f, "Number({})", self.0)
174    }
175}
176
177impl From<Decimal> for Number {
178    fn from(value: Decimal) -> Self {
179        Self(value)
180    }
181}
182
183impl From<Number> for Decimal {
184    fn from(value: Number) -> Self {
185        value.0
186    }
187}
188
189macro_rules! from_integer {
190    ($($t:ty),*) => {
191        $(impl From<$t> for Number {
192            fn from(value: $t) -> Self { Self(Decimal::from(value)) }
193        })*
194    };
195}
196from_integer!(i8, i16, i32, i64, u8, u16, u32, u64);
197
198impl FromStr for Number {
199    type Err = rust_decimal::Error;
200    fn from_str(s: &str) -> Result<Self, Self::Err> {
201        Decimal::from_str(s).or_else(|_| Decimal::from_scientific(s)).map(Self)
202    }
203}
204
205impl core::ops::Add for Number {
206    type Output = Self;
207    fn add(self, rhs: Self) -> Self {
208        Self(self.0 + rhs.0)
209    }
210}
211
212impl core::ops::Sub for Number {
213    type Output = Self;
214    fn sub(self, rhs: Self) -> Self {
215        Self(self.0 - rhs.0)
216    }
217}
218
219impl core::ops::Mul for Number {
220    type Output = Self;
221    fn mul(self, rhs: Self) -> Self {
222        Self(self.0 * rhs.0)
223    }
224}
225
226impl core::iter::Sum for Number {
227    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
228        Self(iter.map(|n| n.0).sum())
229    }
230}
231
232impl Serialize for Number {
233    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
234        // An integral value is written as a JSON integer, which is exact for anything an i64
235        // holds. A fractional value goes out through f64, which `serde_json` prints with the
236        // shortest round-tripping representation — the original decimal, for every value in
237        // OICP's domain. `json_round_trips` reports the values where that is not true.
238        if self.0.is_integer()
239            && let Some(i) = self.0.to_i64()
240        {
241            return s.serialize_i64(i);
242        }
243        match self.0.to_f64() {
244            Some(f) => s.serialize_f64(f),
245            None => {
246                Err(serde::ser::Error::custom(format!("{} cannot be represented as a JSON number", self.0)))
247            }
248        }
249    }
250}
251
252impl<'de> Deserialize<'de> for Number {
253    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
254        struct V;
255        impl serde::de::Visitor<'_> for V {
256            type Value = Number;
257            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258                f.write_str("a JSON number, or a string holding one")
259            }
260            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Number, E> {
261                Ok(Number(Decimal::from(v)))
262            }
263            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Number, E> {
264                Ok(Number(Decimal::from(v)))
265            }
266            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Number, E> {
267                // Via the shortest round-tripping text rather than `Decimal::from_f64_retain`,
268                // so `0.1` arrives as the decimal `0.1` and not as the binary approximation.
269                decimal_from_f64(v)
270                    .map(Number)
271                    .ok_or_else(|| E::custom(format!("{v} is not a finite JSON number")))
272            }
273            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Number, E> {
274                v.parse().map_err(|_| E::custom(format!("{v:?} is not a number")))
275            }
276        }
277        d.deserialize_any(V)
278    }
279}
280
281#[cfg(feature = "schema")]
282impl schemars::JsonSchema for Number {
283    fn schema_name() -> std::borrow::Cow<'static, str> {
284        "Number".into()
285    }
286    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
287        schemars::json_schema!({ "type": "number" })
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn decimals_survive_the_json_boundary() {
297        for text in ["0.1", "0.25", "10.1", "22", "0", "-3.5", "1234.5678", "99999.99"] {
298            let n: Number = text.parse().unwrap();
299            let json = serde_json::to_string(&n).unwrap();
300            let back: Number = serde_json::from_str(&json).unwrap();
301            assert_eq!(n.get().normalize(), back.get().normalize(), "{text} did not round-trip ({json})");
302        }
303    }
304
305    #[test]
306    fn the_cdr_energy_identity_is_exact() {
307        // The float trap this type exists to avoid: 10.1_f64 - 0.1_f64 == 10.000000000000002.
308        let end: Number = "10.1".parse().unwrap();
309        let start: Number = "0.1".parse().unwrap();
310        let consumed: Number = "10.0".parse().unwrap();
311        assert_eq!(end - start, consumed);
312    }
313
314    #[test]
315    fn integral_values_are_written_as_json_integers() {
316        let n: Number = "22".parse().unwrap();
317        assert_eq!(serde_json::to_string(&n).unwrap(), "22");
318        let n: Number = "22.0".parse().unwrap();
319        assert_eq!(serde_json::to_string(&n).unwrap(), "22");
320    }
321
322    #[test]
323    fn a_number_sent_as_a_string_is_accepted() {
324        let n: Number = serde_json::from_str(r#""0.25""#).unwrap();
325        assert_eq!(n.to_string(), "0.25");
326        assert_eq!(serde_json::to_string(&n).unwrap(), "0.25");
327    }
328
329    #[test]
330    fn imprecise_values_are_reported_not_silently_rounded() {
331        let n: Number = "1.2345678901234567890123".parse().unwrap();
332        assert!(!n.json_round_trips());
333        assert_eq!(n.validate().unwrap_err().as_slice()[0].code, ViolationCode::Imprecise);
334    }
335}