Skip to main content

ocpp_kit/
decimal.rs

1//! [`Decimal`], the exact base-10 number every OCPP quantity is carried in.
2//!
3//! Re-exported as [`crate::types::Decimal`]; see that type for what it is and why it is not
4//! an `f64`.
5
6// Fixed-point arithmetic is width juggling on purpose: a mantissa moves between `i64`,
7// `i128` and `u128` so that an intermediate cannot overflow, and every one of those moves is
8// bounded by the check on the line above it. Spelling that out as one `#[allow]` per cast
9// buries the checks in attributes without making any of them safer.
10#![allow(
11    clippy::cast_possible_truncation,
12    clippy::cast_possible_wrap,
13    clippy::cast_sign_loss
14)]
15
16use core::cmp::Ordering;
17use core::fmt;
18use core::hash::{Hash, Hasher};
19use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
20use core::str::FromStr;
21
22use serde::{Deserialize, Serialize};
23
24use crate::validate::{Validate, ValidationPath, Violations};
25
26/// An exact base-10 decimal: `mantissa × 10⁻ˢᶜᵃˡᵉ`.
27///
28/// This is what every OCPP `number` is carried in. The schemas say `"type": "number"` and the
29/// obvious reading of that is `f64`; it is the wrong one, for three reasons that all cost
30/// money:
31///
32/// * **Resolution is a claim.** A meter reporting `2935.600` kWh is stating three decimals of
33///   accuracy. As an `f64`, `2935.600` and `2935.6` are the same value and the claim is gone.
34///   A `Decimal` keeps the scale the station sent, so the value decodes, prints and
35///   re-encodes as `2935.600`. OCMF says the same of its own readings: the representation
36///   "must not be transformed … thus potentially the number of valid digits" (Tab. 7, `RV`).
37/// * **Energy is a subtraction.** OCPP *defines* a session's energy as the difference of two
38///   register readings, and in `f64` `10.1 - 0.1` is `10.000000000000002`.
39/// * **The 2.1 Tariff and Cost block is money.**
40///
41/// ```
42/// use ocpp_kit::decimal;
43/// use ocpp_kit::types::Decimal;
44///
45/// let register: Decimal = "2935.600".parse().unwrap();
46/// assert_eq!(register.scale(), 3);
47/// assert_eq!(register.to_string(), "2935.600");
48///
49/// // The difference OCPP defines a session's energy as, exactly.
50/// assert_eq!(decimal!(20.2) - decimal!(10.1), decimal!(10.1));
51/// ```
52///
53/// Literals are written with [`decimal!`](crate::decimal), which parses the source text at
54/// compile time; integers convert with `From`. There is deliberately no `From<f64>` — a
55/// number that has been through a float has already lost what this type exists to keep — and
56/// the conversions that do exist are named [`to_f64_lossy`](Self::to_f64_lossy) and
57/// [`from_f64_lossy`](Self::from_f64_lossy) so a signature says what it costs. Nothing else
58/// in this crate calls either, and `cargo xtask no-floats` fails the build if an `f32` or
59/// `f64` reaches any public signature.
60///
61/// # What exactly is preserved
62///
63/// The **fraction digits** — the resolution claim — and therefore the positional spelling:
64/// `2935.600` in, `2935.600` out; `5` in, `5` out, not `5.0`. What is *not* preserved is a
65/// spelling that carries no information a decimal number has: exponent notation is
66/// normalized (`1.5e3` re-encodes as `1500`), as are a leading `+` and leading zeros. Where
67/// the exact bytes are load-bearing — a signed OCMF or EDL record — they are not a JSON
68/// number at all, and [`metering`](crate::metering) carries those untouched.
69///
70/// # Range
71///
72/// The mantissa is an `i64` and the scale is at most [`MAX_SCALE`](Self::MAX_SCALE) (18), so
73/// a value carries up to 19 significant digits — a register in Wh with three decimals up to
74/// 10¹⁵ Wh. Text with more precision than that is rounded half to even by
75/// [`from_ascii`](Self::from_ascii); text whose *integer* part does not fit is refused.
76///
77/// # Equality
78///
79/// `PartialEq` and `Ord` compare *numerically*, so `2.50 == 2.5` — that is what a comparison
80/// between two readings should answer, and `Hash` agrees with it. The scale is still there
81/// and still round-trips; [`eq_exact`](Self::eq_exact) compares it too when the spelling is
82/// what matters.
83///
84/// # Arithmetic
85///
86/// Addition, subtraction and multiplication are exact, at the scale the operands imply, and
87/// the operators panic on overflow exactly as the integer ones do; the `checked_` forms
88/// return `None` instead. Division has no exact answer in base ten, so
89/// [`checked_div`](Self::checked_div) takes the scale to round at rather than guessing one.
90/// A change of unit prefix is [`checked_pow10`](Self::checked_pow10), which moves the point
91/// and so cannot round at all.
92///
93/// # Wire format
94///
95/// `Serialize` and `Deserialize` speak `serde_json`'s raw-value protocol, which is how the
96/// source token reaches this type instead of the `f64` a JSON parser would otherwise round it
97/// to. Any other data format falls back to the ordinary numeric path and is lossy in the way
98/// that format is lossy. OCPP-J is JSON, so this is the format that matters.
99///
100/// # Handing the value to another decimal type
101///
102/// A billing platform generally has a decimal type of its own. The conversion is exact in
103/// either direction, so this crate depends on none of them:
104///
105/// ```ignore
106/// let exact = rust_decimal::Decimal::new(reading.mantissa(), u32::from(reading.scale()));
107/// let back = ocpp_kit::types::Decimal::new(
108///     i64::try_from(exact.mantissa()).unwrap(),
109///     u8::try_from(exact.scale()).unwrap(),
110/// );
111/// ```
112///
113/// Anything that parses decimal text — `bigdecimal`, a database `NUMERIC` — takes
114/// `to_string()`, which is the value at its own scale and never in exponent form.
115#[derive(Clone, Copy, Default)]
116pub struct Decimal {
117    mantissa: i64,
118    scale: u8,
119}
120
121/// Powers of ten that fit a `u64`, for rendering and rescaling.
122const POW10_U64: [u64; 19] = [
123    1,
124    10,
125    100,
126    1_000,
127    10_000,
128    100_000,
129    1_000_000,
130    10_000_000,
131    100_000_000,
132    1_000_000_000,
133    10_000_000_000,
134    100_000_000_000,
135    1_000_000_000_000,
136    10_000_000_000_000,
137    100_000_000_000_000,
138    1_000_000_000_000_000,
139    10_000_000_000_000_000,
140    100_000_000_000_000_000,
141    1_000_000_000_000_000_000,
142];
143
144/// `10ⁿ` as an `i128`, for comparison and arithmetic across scales.
145const fn pow10_i128(exp: u32) -> i128 {
146    let mut result: i128 = 1;
147    let mut left = exp;
148    while left > 0 {
149        result *= 10;
150        left -= 1;
151    }
152    result
153}
154
155/// Room to take one more digit without overflowing a `u128`.
156const ACCUMULATE_LIMIT: u128 = u128::MAX / 16;
157
158impl Decimal {
159    /// Zero, at scale 0.
160    pub const ZERO: Self = Self {
161        mantissa: 0,
162        scale: 0,
163    };
164
165    /// One, at scale 0.
166    pub const ONE: Self = Self {
167        mantissa: 1,
168        scale: 0,
169    };
170
171    /// The largest [`scale`](Self::scale) a `Decimal` can carry.
172    pub const MAX_SCALE: u8 = 18;
173
174    /// `mantissa × 10⁻ˢᶜᵃˡᵉ`.
175    ///
176    /// # Panics
177    ///
178    /// If `scale` exceeds [`MAX_SCALE`](Self::MAX_SCALE). Use [`try_new`](Self::try_new) when
179    /// the scale is not known at compile time.
180    #[must_use]
181    pub const fn new(mantissa: i64, scale: u8) -> Self {
182        assert!(
183            scale <= Self::MAX_SCALE,
184            "a Decimal scale may not exceed Decimal::MAX_SCALE"
185        );
186        Self { mantissa, scale }
187    }
188
189    /// `mantissa × 10⁻ˢᶜᵃˡᵉ`, or `None` when `scale` exceeds [`MAX_SCALE`](Self::MAX_SCALE).
190    #[must_use]
191    pub const fn try_new(mantissa: i64, scale: u8) -> Option<Self> {
192        if scale > Self::MAX_SCALE {
193            return None;
194        }
195        Some(Self { mantissa, scale })
196    }
197
198    /// A whole number.
199    #[must_use]
200    pub const fn from_i64(value: i64) -> Self {
201        Self {
202            mantissa: value,
203            scale: 0,
204        }
205    }
206
207    /// The mantissa: the value with the decimal point removed.
208    #[must_use]
209    pub const fn mantissa(self) -> i64 {
210        self.mantissa
211    }
212
213    /// How many digits follow the decimal point.
214    ///
215    /// This is the resolution the value was written with, and it is preserved: a station that
216    /// sent `2935.600` gets `3` here, and `2935.600` back on the wire.
217    #[must_use]
218    pub const fn scale(self) -> u8 {
219        self.scale
220    }
221
222    /// Whether the value is zero, whatever its scale.
223    #[must_use]
224    pub const fn is_zero(self) -> bool {
225        self.mantissa == 0
226    }
227
228    /// `-1`, `0` or `1`.
229    #[must_use]
230    pub const fn signum(self) -> i32 {
231        if self.mantissa < 0 {
232            -1
233        } else if self.mantissa > 0 {
234            1
235        } else {
236            0
237        }
238    }
239
240    /// Whether two values have both the same number *and* the same scale — `2.50` and `2.5`
241    /// are equal but not identical.
242    #[must_use]
243    pub const fn eq_exact(self, other: Self) -> bool {
244        self.mantissa == other.mantissa && self.scale == other.scale
245    }
246
247    /// The same number with every trailing zero removed: `2.500` becomes `2.5`.
248    #[must_use]
249    pub const fn normalized(mut self) -> Self {
250        while self.scale > 0 && self.mantissa % 10 == 0 {
251            self.mantissa /= 10;
252            self.scale -= 1;
253        }
254        if self.mantissa == 0 {
255            self.scale = 0;
256        }
257        self
258    }
259
260    /// The same number written at `scale`, or `None` when that would lose a digit or
261    /// overflow.
262    ///
263    /// Exact by construction: it never rounds. Use [`round_to`](Self::round_to) to round.
264    #[must_use]
265    pub const fn rescale(self, scale: u8) -> Option<Self> {
266        if scale > Self::MAX_SCALE {
267            return None;
268        }
269        if scale == self.scale {
270            return Some(self);
271        }
272        if scale > self.scale {
273            let factor = POW10_U64[(scale - self.scale) as usize];
274            let Some(mantissa) = self.mantissa.checked_mul(factor as i64) else {
275                return None;
276            };
277            return Some(Self { mantissa, scale });
278        }
279        let factor = POW10_U64[(self.scale - scale) as usize] as i64;
280        if self.mantissa % factor != 0 {
281            return None;
282        }
283        Some(Self {
284            mantissa: self.mantissa / factor,
285            scale,
286        })
287    }
288
289    /// The value rounded to `scale`, half to even, or `None` on overflow or an out-of-range
290    /// scale.
291    #[must_use]
292    pub const fn round_to(self, scale: u8) -> Option<Self> {
293        if scale >= self.scale {
294            return self.rescale(scale);
295        }
296        let drop = (self.scale - scale) as u32;
297        let negative = self.mantissa < 0;
298        let magnitude = self.mantissa.unsigned_abs() as u128;
299        let rounded = round_off(magnitude, drop, false);
300        if rounded > i64::MAX as u128 {
301            return None;
302        }
303        let mantissa = rounded as i64;
304        Some(Self {
305            mantissa: if negative { -mantissa } else { mantissa },
306            scale,
307        })
308    }
309
310    // -- arithmetic ---------------------------------------------------------
311
312    /// The sum, at the larger of the two scales, or `None` on overflow.
313    #[must_use]
314    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
315        let scale = if self.scale > rhs.scale {
316            self.scale
317        } else {
318            rhs.scale
319        };
320        let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
321            return None;
322        };
323        narrow(a + b, scale)
324    }
325
326    /// The difference, at the larger of the two scales, or `None` on overflow.
327    ///
328    /// This is the operation OCPP defines a session's energy as, and the reason this type
329    /// exists: `20.2 - 10.1` is `10.1`, not `10.100000000000001`.
330    #[must_use]
331    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
332        let scale = if self.scale > rhs.scale {
333            self.scale
334        } else {
335            rhs.scale
336        };
337        let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
338            return None;
339        };
340        narrow(a - b, scale)
341    }
342
343    /// The product, at the sum of the two scales, or `None` when that does not fit.
344    #[must_use]
345    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
346        let scale = self.scale as u32 + rhs.scale as u32;
347        let product = self.mantissa as i128 * rhs.mantissa as i128;
348        if scale <= Self::MAX_SCALE as u32 {
349            return narrow(product, scale as u8);
350        }
351        // The exact product needs more scale than the type carries; round the surplus away.
352        let drop = scale - Self::MAX_SCALE as u32;
353        let negative = product < 0;
354        let rounded = round_off(product.unsigned_abs(), drop, false);
355        if rounded > i64::MAX as u128 {
356            return None;
357        }
358        let mantissa = rounded as i64;
359        Some(Self {
360            mantissa: if negative { -mantissa } else { mantissa },
361            scale: Self::MAX_SCALE,
362        })
363    }
364
365    /// The quotient at `scale`, rounded half to even, or `None` when `rhs` is zero or the
366    /// result does not fit.
367    ///
368    /// Division is the one operation that has no exact answer in base ten — `1 / 3` does not
369    /// terminate — so the scale to round at is a parameter rather than a guess.
370    #[must_use]
371    pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self> {
372        if rhs.mantissa == 0 || scale > Self::MAX_SCALE {
373            return None;
374        }
375        // (a / 10^sa) / (b / 10^sb) at `scale` == a * 10^(scale + sb - sa) / b.
376        let shift = scale as i32 + rhs.scale as i32 - self.scale as i32;
377        let negative = (self.mantissa < 0) != (rhs.mantissa < 0);
378        let mut numerator = self.mantissa.unsigned_abs() as u128;
379        let denominator = rhs.mantissa.unsigned_abs() as u128;
380        // One extra digit, so the quotient can be rounded half to even.
381        let shift = shift + 1;
382        let mut extra_drop = 0u32;
383        if shift >= 0 {
384            let up = shift as u32;
385            if up > 38 {
386                return None;
387            }
388            let factor = pow10_i128(up) as u128;
389            let Some(scaled) = numerator.checked_mul(factor) else {
390                return None;
391            };
392            numerator = scaled;
393        } else {
394            // Shrinking the numerator instead would throw away the digits the rounding needs,
395            // so the denominator grows.
396            let down = (-shift) as u32;
397            if down > 38 {
398                return None;
399            }
400            extra_drop = down;
401        }
402        let quotient = if extra_drop > 0 {
403            let factor = pow10_i128(extra_drop) as u128;
404            let Some(scaled) = denominator.checked_mul(factor) else {
405                return None;
406            };
407            numerator / scaled
408        } else {
409            numerator / denominator
410        };
411        let remainder_is_zero = if extra_drop > 0 {
412            let factor = pow10_i128(extra_drop) as u128;
413            match denominator.checked_mul(factor) {
414                Some(scaled) => numerator % scaled == 0,
415                None => return None,
416            }
417        } else {
418            numerator % denominator == 0
419        };
420        let rounded = round_off(quotient, 1, !remainder_is_zero);
421        if rounded > i64::MAX as u128 {
422            return None;
423        }
424        let mantissa = rounded as i64;
425        Some(Self {
426            mantissa: if negative { -mantissa } else { mantissa },
427            scale,
428        })
429    }
430
431    /// The value multiplied by `10^exp`, exactly, or `None` when it does not fit.
432    ///
433    /// A shift of the decimal point, which is all a change of unit prefix is: kWh to Wh is
434    /// `pow10(3)`, and the 2.x `unitOfMeasure.multiplier` is exactly this operation. Unlike a
435    /// multiplication by a literal `1000.0` it cannot introduce a rounding error, because it
436    /// only moves the point.
437    #[must_use]
438    pub const fn checked_pow10(self, exp: i32) -> Option<Self> {
439        if exp == 0 {
440            return Some(self);
441        }
442        // Nothing outside this range has an answer, and `exp` comes off the wire — the 2.x
443        // `unitOfMeasure.multiplier` is whatever the station put there, `i32::MIN` included,
444        // and negating that is an overflow rather than a large number.
445        if exp > 40 || exp < -40 {
446            return if self.mantissa == 0 {
447                Some(Self::ZERO)
448            } else {
449                None
450            };
451        }
452        if exp < 0 {
453            // Dividing by a power of ten: add scale, which is exact until the cap is reached.
454            let want = self.scale as i32 - exp;
455            if want <= Self::MAX_SCALE as i32 {
456                return Some(Self {
457                    mantissa: self.mantissa,
458                    scale: want as u8,
459                });
460            }
461            // Past the cap the mantissa has to shrink instead, which needs trailing zeros.
462            let surplus = want - Self::MAX_SCALE as i32;
463            let surplus = surplus as u32;
464            if surplus > 18 {
465                return None;
466            }
467            let factor = POW10_U64[surplus as usize] as i64;
468            if self.mantissa % factor != 0 {
469                return None;
470            }
471            return Some(Self {
472                mantissa: self.mantissa / factor,
473                scale: Self::MAX_SCALE,
474            });
475        }
476        // Multiplying by a power of ten: spend the scale first, then grow the mantissa.
477        let mut left = exp as u32;
478        let mut mantissa = self.mantissa;
479        let mut scale = self.scale;
480        while left > 0 && scale > 0 {
481            scale -= 1;
482            left -= 1;
483        }
484        while left > 0 {
485            let step = if left > 18 { 18 } else { left };
486            let Some(next) = mantissa.checked_mul(POW10_U64[step as usize] as i64) else {
487                return None;
488            };
489            mantissa = next;
490            left -= step;
491        }
492        Some(Self { mantissa, scale })
493    }
494
495    /// The absolute value, or `None` for a mantissa of `i64::MIN`.
496    #[must_use]
497    pub const fn checked_abs(self) -> Option<Self> {
498        let Some(mantissa) = self.mantissa.checked_abs() else {
499            return None;
500        };
501        Some(Self {
502            mantissa,
503            scale: self.scale,
504        })
505    }
506
507    /// The negation, or `None` for a mantissa of `i64::MIN`.
508    #[must_use]
509    pub const fn checked_neg(self) -> Option<Self> {
510        let Some(mantissa) = self.mantissa.checked_neg() else {
511            return None;
512        };
513        Some(Self {
514            mantissa,
515            scale: self.scale,
516        })
517    }
518
519    /// The smaller of two values.
520    #[must_use]
521    pub const fn min(self, other: Self) -> Self {
522        match self.compare(other) {
523            Ordering::Greater => other,
524            _ => self,
525        }
526    }
527
528    /// The larger of two values.
529    #[must_use]
530    pub const fn max(self, other: Self) -> Self {
531        match self.compare(other) {
532            Ordering::Less => other,
533            _ => self,
534        }
535    }
536
537    /// Numeric comparison, in a `const` context.
538    #[must_use]
539    pub const fn compare(self, other: Self) -> Ordering {
540        let scale = if self.scale > other.scale {
541            self.scale
542        } else {
543            other.scale
544        };
545        match (self.to_i128_at(scale), other.to_i128_at(scale)) {
546            (Some(a), Some(b)) => {
547                if a < b {
548                    Ordering::Less
549                } else if a > b {
550                    Ordering::Greater
551                } else {
552                    Ordering::Equal
553                }
554            }
555            // Unreachable: 19 digits shifted by at most 18 places fits an i128 with room to
556            // spare. Falling back on the sign keeps the function total anyway.
557            _ => {
558                if self.mantissa < other.mantissa {
559                    Ordering::Less
560                } else if self.mantissa > other.mantissa {
561                    Ordering::Greater
562                } else {
563                    Ordering::Equal
564                }
565            }
566        }
567    }
568
569    /// The mantissa this value would have at `scale`, as an `i128`.
570    const fn to_i128_at(self, scale: u8) -> Option<i128> {
571        if scale < self.scale {
572            return None;
573        }
574        let factor = pow10_i128((scale - self.scale) as u32);
575        Some(self.mantissa as i128 * factor)
576    }
577
578    // -- text ---------------------------------------------------------------
579
580    /// Parses a decimal from ASCII, exactly.
581    ///
582    /// Accepts everything JSON's `number` production allows — an optional sign, digits, an
583    /// optional fraction, an optional `e`/`E` exponent — plus a leading `+`, leading zeros
584    /// and surrounding whitespace, none of which JSON permits but stations send anyway. The
585    /// scale of the result is the number of fraction digits written, so `2935.600` parses to
586    /// scale 3 and prints back identically.
587    ///
588    /// # Errors
589    ///
590    /// [`ParseDecimalError::Invalid`] when the text is not a number at all, and
591    /// [`ParseDecimalError::Overflow`] when its integer part needs more than 19 digits.
592    /// Excess *fraction* digits are rounded half to even rather than refused, because
593    /// refusing a value the schema calls valid is worse than rounding at the nineteenth
594    /// significant digit.
595    // One parser, in one place: splitting it would hand the pieces a half-parsed state to
596    // agree about, which is how parsers grow disagreements.
597    #[allow(clippy::too_many_lines)]
598    pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
599        let n = bytes.len();
600        let mut i = 0usize;
601        while i < n && is_space(bytes[i]) {
602            i += 1;
603        }
604        let mut negative = false;
605        if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
606            negative = bytes[i] == b'-';
607            i += 1;
608        }
609
610        let mut magnitude: u128 = 0;
611        let mut fraction_digits: i64 = 0;
612        let mut skipped_integer_digits: i64 = 0;
613        let mut round_digit: u8 = 0;
614        let mut sticky = false;
615        let mut dropped_any = false;
616        let mut seen_digit = false;
617        let mut seen_point = false;
618
619        while i < n {
620            let byte = bytes[i];
621            if byte == b'.' {
622                if seen_point {
623                    return Err(ParseDecimalError::Invalid);
624                }
625                seen_point = true;
626                i += 1;
627                continue;
628            }
629            if byte < b'0' || byte > b'9' {
630                break;
631            }
632            seen_digit = true;
633            let digit = byte - b'0';
634            if magnitude < ACCUMULATE_LIMIT {
635                magnitude = magnitude * 10 + digit as u128;
636                if seen_point {
637                    fraction_digits += 1;
638                }
639            } else {
640                // No room left in the accumulator: the digit only decides the rounding.
641                if !seen_point {
642                    skipped_integer_digits += 1;
643                }
644                if dropped_any {
645                    if digit != 0 {
646                        sticky = true;
647                    }
648                } else {
649                    round_digit = digit;
650                    dropped_any = true;
651                }
652            }
653            i += 1;
654        }
655        if !seen_digit {
656            return Err(ParseDecimalError::Invalid);
657        }
658        let mut rounded_off = false;
659        if dropped_any {
660            if round_digit > 5 || (round_digit == 5 && (sticky || magnitude % 2 == 1)) {
661                magnitude += 1;
662            }
663            rounded_off = true;
664        }
665
666        let mut exponent: i64 = 0;
667        if i < n && (bytes[i] == b'e' || bytes[i] == b'E') {
668            i += 1;
669            let mut exponent_negative = false;
670            if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
671                exponent_negative = bytes[i] == b'-';
672                i += 1;
673            }
674            let mut seen_exponent_digit = false;
675            while i < n && bytes[i] >= b'0' && bytes[i] <= b'9' {
676                seen_exponent_digit = true;
677                // Clamped: anything past a few hundred is out of range either way.
678                if exponent < 1_000_000 {
679                    exponent = exponent * 10 + (bytes[i] - b'0') as i64;
680                }
681                i += 1;
682            }
683            if !seen_exponent_digit {
684                return Err(ParseDecimalError::Invalid);
685            }
686            if exponent_negative {
687                exponent = -exponent;
688            }
689        }
690        while i < n && is_space(bytes[i]) {
691            i += 1;
692        }
693        if i != n {
694            return Err(ParseDecimalError::Invalid);
695        }
696
697        // value == magnitude × 10^(skipped_integer_digits + exponent - fraction_digits)
698        let mut scale = fraction_digits - skipped_integer_digits - exponent;
699        if magnitude == 0 {
700            // Zero has no significant digits to place; keep the written fraction width when
701            // it is representable, so `0.00` stays `0.00`.
702            if scale < 0 || scale > Self::MAX_SCALE as i64 {
703                scale = 0;
704            }
705            return Ok(Self {
706                mantissa: 0,
707                scale: scale as u8,
708            });
709        }
710
711        if scale < 0 {
712            let shift = -scale;
713            if shift > 38 {
714                return Err(ParseDecimalError::Overflow);
715            }
716            let factor = pow10_i128(shift as u32) as u128;
717            let Some(scaled) = magnitude.checked_mul(factor) else {
718                return Err(ParseDecimalError::Overflow);
719            };
720            magnitude = scaled;
721            scale = 0;
722        } else if scale > Self::MAX_SCALE as i64 {
723            let drop = scale - Self::MAX_SCALE as i64;
724            if drop > 39 {
725                magnitude = 0;
726            } else {
727                let dropped = drop as u32;
728                magnitude = round_off(magnitude, dropped, false);
729            }
730            scale = Self::MAX_SCALE as i64;
731            rounded_off = true;
732        }
733
734        // Whatever is left has to fit an i64, which may cost further fraction digits.
735        while magnitude > i64::MAX as u128 {
736            if scale == 0 {
737                return Err(ParseDecimalError::Overflow);
738            }
739            magnitude = round_off(magnitude, 1, false);
740            scale -= 1;
741            rounded_off = true;
742        }
743        let _ = rounded_off;
744        let mantissa = magnitude as i64;
745        Ok(Self {
746            mantissa: if negative { -mantissa } else { mantissa },
747            scale: scale as u8,
748        })
749    }
750
751    /// Parses a Rust numeric literal, panicking instead of returning an error.
752    ///
753    /// This is what [`decimal!`](crate::decimal) expands to, so the panic is a compile error
754    /// rather than a runtime one. It differs from [`from_ascii`](Self::from_ascii) in
755    /// accepting Rust's `_` digit separators — `decimal!(11_000)` is how the number would be
756    /// written anywhere else in the source, and JSON never contains one, so the leniency
757    /// costs the wire path nothing.
758    ///
759    /// # Panics
760    ///
761    /// If the text is not a decimal number.
762    #[must_use]
763    pub const fn from_literal(text: &str) -> Self {
764        let bytes = text.as_bytes();
765        // A stack copy with the separators removed; `const` rules out allocating one.
766        let mut digits = [0u8; 64];
767        let mut len = 0usize;
768        let mut i = 0usize;
769        while i < bytes.len() {
770            if bytes[i] != b'_' {
771                assert!(len < 64, "decimal literal is too long");
772                digits[len] = bytes[i];
773                len += 1;
774            }
775            i += 1;
776        }
777        let (kept, _) = digits.split_at(len);
778        match Self::from_ascii(kept) {
779            Ok(value) => value,
780            Err(ParseDecimalError::Invalid) => panic!("not a decimal number"),
781            Err(ParseDecimalError::Overflow) => panic!("decimal number out of range"),
782        }
783    }
784
785    // -- floating point -----------------------------------------------------
786
787    /// The value as an `f64`, correctly rounded.
788    ///
789    /// Named for what it costs: past 15 significant digits the result is not the number this
790    /// `Decimal` holds, and no arithmetic done on it afterwards is exact. Nothing in this
791    /// crate calls it.
792    #[must_use]
793    #[allow(clippy::cast_precision_loss)] // The whole point of the name.
794    pub fn to_f64_lossy(self) -> f64 {
795        const POW10_F64: [f64; 19] = [
796            1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
797            1e16, 1e17, 1e18,
798        ];
799        let mantissa = self.mantissa as f64;
800        mantissa / POW10_F64[self.scale as usize]
801    }
802
803    /// The decimal an `f64` is nearest to, or `None` for an infinity, a NaN, or a magnitude
804    /// out of range.
805    ///
806    /// Named for what it costs: the `f64` `0.1` is not one tenth, and this returns the
807    /// shortest decimal that reads back as the same `f64` — `0.1` — rather than the value it
808    /// actually holds. That is the friendly answer, and it is still a guess about what the
809    /// number was before it became a float. Parse the text instead when there is text.
810    #[must_use]
811    pub fn from_f64_lossy(value: f64) -> Option<Self> {
812        if !value.is_finite() {
813            return None;
814        }
815        let mut buffer = TextBuffer::new();
816        // The exponent form is the shortest round-tripping spelling and is bounded in length;
817        // `{}` would spell 1e300 out in full.
818        if fmt::Write::write_fmt(&mut buffer, format_args!("{value:e}")).is_err() {
819            return None;
820        }
821        Self::from_ascii(buffer.as_bytes()).ok()
822    }
823}
824
825/// Drops `digits` decimal digits from `magnitude`, rounding half to even.
826///
827/// `sticky` says whether anything non-zero was already discarded below those digits, which is
828/// what turns an exact half into a value above it.
829const fn round_off(magnitude: u128, digits: u32, sticky: bool) -> u128 {
830    if digits == 0 {
831        return magnitude;
832    }
833    if digits > 38 {
834        return 0;
835    }
836    let divisor = pow10_i128(digits) as u128;
837    let quotient = magnitude / divisor;
838    let remainder = magnitude % divisor;
839    let half = divisor / 2;
840    if remainder > half || (remainder == half && (sticky || quotient % 2 == 1)) {
841        quotient + 1
842    } else {
843        quotient
844    }
845}
846
847/// Narrows an `i128` mantissa back to a `Decimal`, or `None` when it does not fit.
848const fn narrow(mantissa: i128, scale: u8) -> Option<Decimal> {
849    if mantissa > i64::MAX as i128 || mantissa < i64::MIN as i128 {
850        return None;
851    }
852    Some(Decimal {
853        mantissa: mantissa as i64,
854        scale,
855    })
856}
857
858const fn is_space(byte: u8) -> bool {
859    matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
860}
861
862/// Why a decimal could not be parsed.
863#[derive(Clone, Copy, Debug, PartialEq, Eq)]
864#[non_exhaustive]
865pub enum ParseDecimalError {
866    /// The text is not a number.
867    Invalid,
868    /// The number needs more than 19 digits before the decimal point.
869    Overflow,
870}
871
872impl fmt::Display for ParseDecimalError {
873    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
874        f.write_str(match self {
875            ParseDecimalError::Invalid => "not a decimal number",
876            ParseDecimalError::Overflow => "decimal number out of range",
877        })
878    }
879}
880
881#[cfg(feature = "std")]
882impl std::error::Error for ParseDecimalError {}
883
884impl FromStr for Decimal {
885    type Err = ParseDecimalError;
886
887    fn from_str(text: &str) -> Result<Self, Self::Err> {
888        Self::from_ascii(text.as_bytes())
889    }
890}
891
892impl fmt::Debug for Decimal {
893    /// The number, not its representation: `Decimal(2935.600)`. A `{mantissa, scale}` dump is
894    /// what a reader has to decode by hand every time one of these appears in a log line.
895    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896        write!(f, "Decimal({self})")
897    }
898}
899
900impl fmt::Display for Decimal {
901    /// Writes the value at its own scale, so `2935.600` prints as `2935.600`.
902    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903        if self.scale == 0 {
904            return write!(f, "{}", self.mantissa);
905        }
906        let magnitude = self.mantissa.unsigned_abs();
907        let divisor = POW10_U64[self.scale as usize];
908        let sign = if self.mantissa < 0 { "-" } else { "" };
909        write!(
910            f,
911            "{sign}{}.{:0width$}",
912            magnitude / divisor,
913            magnitude % divisor,
914            width = self.scale as usize
915        )
916    }
917}
918
919// ---------------------------------------------------------------------------
920// Comparison
921// ---------------------------------------------------------------------------
922
923impl PartialEq for Decimal {
924    fn eq(&self, other: &Self) -> bool {
925        self.compare(*other) == Ordering::Equal
926    }
927}
928
929impl Eq for Decimal {}
930
931impl PartialOrd for Decimal {
932    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
933        Some(self.cmp(other))
934    }
935}
936
937impl Ord for Decimal {
938    fn cmp(&self, other: &Self) -> Ordering {
939        self.compare(*other)
940    }
941}
942
943impl Hash for Decimal {
944    /// Hashes the normalized value, so `2.50` and `2.5` — which compare equal — hash equal.
945    fn hash<H: Hasher>(&self, state: &mut H) {
946        let normalized = self.normalized();
947        normalized.mantissa.hash(state);
948        normalized.scale.hash(state);
949    }
950}
951
952// ---------------------------------------------------------------------------
953// Operators
954// ---------------------------------------------------------------------------
955
956macro_rules! binary_op {
957    ($trait:ident, $method:ident, $checked:ident, $what:literal) => {
958        impl $trait for Decimal {
959            type Output = Decimal;
960            /// # Panics
961            ///
962            /// On overflow, like the integer operators. Use the `checked_` form to handle it.
963            fn $method(self, rhs: Decimal) -> Decimal {
964                self.$checked(rhs)
965                    .expect(concat!("Decimal ", $what, " overflowed"))
966            }
967        }
968    };
969}
970
971binary_op!(Add, add, checked_add, "addition");
972binary_op!(Sub, sub, checked_sub, "subtraction");
973binary_op!(Mul, mul, checked_mul, "multiplication");
974
975impl Div for Decimal {
976    type Output = Decimal;
977
978    /// Division at [`Decimal::MAX_SCALE`], rounded half to even.
979    ///
980    /// # Panics
981    ///
982    /// On division by zero or overflow. [`Decimal::checked_div`] takes the scale to round at
983    /// and returns `None` instead, which is what production code should use.
984    fn div(self, rhs: Decimal) -> Decimal {
985        self.checked_div(rhs, Decimal::MAX_SCALE)
986            .expect("Decimal division by zero or overflow")
987    }
988}
989
990impl Neg for Decimal {
991    type Output = Decimal;
992
993    /// # Panics
994    ///
995    /// Only for a mantissa of `i64::MIN`, which no parsed value has.
996    fn neg(self) -> Decimal {
997        self.checked_neg().expect("Decimal negation overflowed")
998    }
999}
1000
1001impl AddAssign for Decimal {
1002    fn add_assign(&mut self, rhs: Decimal) {
1003        *self = *self + rhs;
1004    }
1005}
1006
1007impl SubAssign for Decimal {
1008    fn sub_assign(&mut self, rhs: Decimal) {
1009        *self = *self - rhs;
1010    }
1011}
1012
1013impl core::iter::Sum for Decimal {
1014    fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
1015        iter.fold(Decimal::ZERO, |total, value| total + value)
1016    }
1017}
1018
1019// ---------------------------------------------------------------------------
1020// Conversions
1021// ---------------------------------------------------------------------------
1022
1023macro_rules! from_integer {
1024    ($($ty:ty),*) => {
1025        $(
1026            impl From<$ty> for Decimal {
1027                fn from(value: $ty) -> Self {
1028                    Self { mantissa: i64::from(value), scale: 0 }
1029                }
1030            }
1031        )*
1032    };
1033}
1034
1035from_integer!(i8, i16, i32, i64, u8, u16, u32);
1036
1037impl TryFrom<u64> for Decimal {
1038    type Error = ParseDecimalError;
1039
1040    fn try_from(value: u64) -> Result<Self, Self::Error> {
1041        i64::try_from(value)
1042            .map(Self::from_i64)
1043            .map_err(|_| ParseDecimalError::Overflow)
1044    }
1045}
1046
1047impl TryFrom<Decimal> for i64 {
1048    type Error = ParseDecimalError;
1049
1050    /// Succeeds only when the value is a whole number.
1051    fn try_from(value: Decimal) -> Result<Self, Self::Error> {
1052        value
1053            .rescale(0)
1054            .map(Decimal::mantissa)
1055            .ok_or(ParseDecimalError::Invalid)
1056    }
1057}
1058
1059// ---------------------------------------------------------------------------
1060// A stack buffer, so formatting a Decimal never allocates
1061// ---------------------------------------------------------------------------
1062
1063/// Enough for a sign, 19 digits, a point and an exponent.
1064const TEXT_CAPACITY: usize = 40;
1065
1066struct TextBuffer {
1067    bytes: [u8; TEXT_CAPACITY],
1068    len: usize,
1069}
1070
1071impl TextBuffer {
1072    const fn new() -> Self {
1073        Self {
1074            bytes: [0; TEXT_CAPACITY],
1075            len: 0,
1076        }
1077    }
1078
1079    fn as_bytes(&self) -> &[u8] {
1080        &self.bytes[..self.len]
1081    }
1082
1083    fn as_str(&self) -> &str {
1084        // Only `core::fmt` writes here, and it only writes UTF-8; the slice ends on a
1085        // character boundary because a write either fits whole or fails.
1086        core::str::from_utf8(self.as_bytes()).unwrap_or("0")
1087    }
1088}
1089
1090impl fmt::Write for TextBuffer {
1091    fn write_str(&mut self, text: &str) -> fmt::Result {
1092        let end = self.len + text.len();
1093        if end > TEXT_CAPACITY {
1094            return Err(fmt::Error);
1095        }
1096        self.bytes[self.len..end].copy_from_slice(text.as_bytes());
1097        self.len = end;
1098        Ok(())
1099    }
1100}
1101
1102// ---------------------------------------------------------------------------
1103// serde
1104// ---------------------------------------------------------------------------
1105
1106/// `serde_json`'s private marker for a value carried as raw JSON text.
1107///
1108/// Asking for it is how a `Deserialize` impl sees the number *as the peer wrote it* rather
1109/// than as whatever `f64` the parser would round it to — which is the entire point of this
1110/// type. `serde_json` answers with the source token; any other data format falls through to
1111/// `deserialize_any` below and gets the ordinary numeric path.
1112const RAW_TOKEN: &str = "$serde_json::private::RawValue";
1113
1114impl Serialize for Decimal {
1115    /// Writes the number as the peer would have written it: the mantissa at its own scale, so
1116    /// `2935.600` goes back out as `2935.600` and not as `2935.6`.
1117    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1118        use serde::ser::SerializeStruct as _;
1119        let mut buffer = TextBuffer::new();
1120        if fmt::Write::write_fmt(&mut buffer, format_args!("{self}")).is_err() {
1121            return Err(serde::ser::Error::custom("decimal is too long to render"));
1122        }
1123        let mut raw = serializer.serialize_struct(RAW_TOKEN, 1)?;
1124        raw.serialize_field(RAW_TOKEN, buffer.as_str())?;
1125        raw.end()
1126    }
1127}
1128
1129impl<'de> Deserialize<'de> for Decimal {
1130    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1131        deserializer.deserialize_newtype_struct(RAW_TOKEN, DecimalVisitor)
1132    }
1133}
1134
1135struct DecimalVisitor;
1136
1137impl<'de> serde::de::Visitor<'de> for DecimalVisitor {
1138    type Value = Decimal;
1139
1140    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1141        f.write_str("a JSON number")
1142    }
1143
1144    fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Decimal, E> {
1145        Ok(Decimal::from_i64(value))
1146    }
1147
1148    fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Decimal, E> {
1149        Decimal::try_from(value).map_err(|_| E::custom("number out of range for a decimal"))
1150    }
1151
1152    fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Decimal, E> {
1153        Decimal::from_f64_lossy(value)
1154            .ok_or_else(|| E::custom("number is not a finite decimal in range"))
1155    }
1156
1157    /// The data format handed back a newtype rather than raw text — it is not `serde_json`.
1158    /// Take the ordinary numeric path.
1159    fn visit_newtype_struct<D: serde::Deserializer<'de>>(
1160        self,
1161        deserializer: D,
1162    ) -> Result<Decimal, D::Error> {
1163        deserializer.deserialize_any(DecimalVisitor)
1164    }
1165
1166    /// `serde_json` answers the raw-value request with a one-entry map holding the source
1167    /// token. Parsing that token is what keeps `2935.600` from becoming `2935.6`.
1168    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Decimal, A::Error> {
1169        use serde::de::Error as _;
1170        let Some(RawKey) = map.next_key::<RawKey>()? else {
1171            return Err(A::Error::custom("expected a JSON number"));
1172        };
1173        let RawToken(value) = map.next_value::<RawToken>()?;
1174        Ok(value)
1175    }
1176}
1177
1178/// The key of `serde_json`'s raw-value map, which is a fixed marker and carries no meaning.
1179struct RawKey;
1180
1181impl<'de> Deserialize<'de> for RawKey {
1182    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1183        struct KeyVisitor;
1184        impl serde::de::Visitor<'_> for KeyVisitor {
1185            type Value = RawKey;
1186            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187                f.write_str("a raw value marker")
1188            }
1189            fn visit_str<E: serde::de::Error>(self, _value: &str) -> Result<RawKey, E> {
1190                Ok(RawKey)
1191            }
1192        }
1193        deserializer.deserialize_identifier(KeyVisitor)
1194    }
1195}
1196
1197/// One raw JSON token, parsed as a decimal.
1198struct RawToken(Decimal);
1199
1200impl<'de> Deserialize<'de> for RawToken {
1201    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1202        struct TokenVisitor;
1203        impl serde::de::Visitor<'_> for TokenVisitor {
1204            type Value = RawToken;
1205
1206            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1207                f.write_str("a JSON number")
1208            }
1209
1210            fn visit_str<E: serde::de::Error>(self, token: &str) -> Result<RawToken, E> {
1211                use serde::de::Unexpected;
1212                // The token is whatever stood where a number belongs. Reporting the *JSON
1213                // type* of what actually arrived is what keeps `invalid type: …` — and with
1214                // it the TypeConstraintViolation classification, and the numeric-string
1215                // repair — working exactly as it does for every other field.
1216                let trimmed = token.trim();
1217                let unexpected = match trimmed.as_bytes().first() {
1218                    Some(b'"') => Some(Unexpected::Str(trimmed.trim_matches('"'))),
1219                    Some(b'{') => Some(Unexpected::Map),
1220                    Some(b'[') => Some(Unexpected::Seq),
1221                    Some(b't') => Some(Unexpected::Bool(true)),
1222                    Some(b'f') => Some(Unexpected::Bool(false)),
1223                    Some(b'n') => Some(Unexpected::Unit),
1224                    _ => None,
1225                };
1226                if let Some(unexpected) = unexpected {
1227                    return Err(E::invalid_type(unexpected, &"a JSON number"));
1228                }
1229                Decimal::from_ascii(trimmed.as_bytes())
1230                    .map(RawToken)
1231                    .map_err(|error| {
1232                        let expected: &str = match error {
1233                            ParseDecimalError::Overflow => "a decimal number in range",
1234                            ParseDecimalError::Invalid => "a decimal number",
1235                        };
1236                        E::invalid_value(Unexpected::Other(trimmed), &expected)
1237                    })
1238            }
1239        }
1240        deserializer.deserialize_str(TokenVisitor)
1241    }
1242}
1243
1244impl Validate for Decimal {
1245    /// Nothing to check: unlike an `f64`, a `Decimal` cannot hold a value JSON has no
1246    /// spelling for. Range constraints are emitted per field by the code generator.
1247    fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
1248}
1249
1250// ---------------------------------------------------------------------------
1251// Literals
1252// ---------------------------------------------------------------------------
1253
1254/// An exact [`Decimal`] literal, parsed at compile time.
1255///
1256/// ```
1257/// use ocpp_kit::decimal;
1258///
1259/// let limit = decimal!(32.5);
1260/// assert_eq!(limit.scale(), 1);
1261/// assert_eq!(limit.mantissa(), 325);
1262/// ```
1263///
1264/// The digits are read from the source text, so the value is the one written rather than the
1265/// nearest `f64` to it, and a malformed literal is a compile error.
1266#[macro_export]
1267macro_rules! decimal {
1268    ($($token:tt)+) => {
1269        const {
1270            $crate::types::Decimal::from_literal(::core::stringify!($($token)+))
1271        }
1272    };
1273}
1274
1275#[cfg(test)]
1276mod tests {
1277    use super::*;
1278    use alloc::string::ToString;
1279
1280    #[test]
1281    fn the_scale_the_station_sent_survives_the_round_trip() {
1282        // The whole point: `2935.600` states three decimals of resolution, and an f64 cannot
1283        // hold that claim — `2935.600` and `2935.6` are the same f64.
1284        let value: Decimal = serde_json::from_str("2935.600").unwrap();
1285        assert_eq!(value.scale(), 3);
1286        assert_eq!(value.mantissa(), 2_935_600);
1287        assert_eq!(serde_json::to_string(&value).unwrap(), "2935.600");
1288        assert_eq!(value.to_string(), "2935.600");
1289
1290        // Equal in value, different in what they claim about the meter.
1291        let short: Decimal = serde_json::from_str("2935.6").unwrap();
1292        assert_eq!(value, short);
1293        assert!(!value.eq_exact(short));
1294    }
1295
1296    #[test]
1297    fn a_difference_of_two_registers_is_exact() {
1298        // The f64 answer to this is 10.000000000000002.
1299        let start: Decimal = "0.1".parse().unwrap();
1300        let stop: Decimal = "10.2".parse().unwrap();
1301        assert_eq!((stop - start).to_string(), "10.1");
1302    }
1303
1304    #[test]
1305    fn every_json_number_spelling_parses() {
1306        for (text, expected) in [
1307            ("0", "0"),
1308            ("-0", "0"),
1309            ("42", "42"),
1310            ("-17.25", "-17.25"),
1311            ("0.00", "0.00"),
1312            ("1e3", "1000"),
1313            ("1.5E+3", "1500"),
1314            ("15e-1", "1.5"),
1315            ("2E-4", "0.0002"),
1316            ("0.000000000000000001", "0.000000000000000001"),
1317            ("9223372036854775807", "9223372036854775807"),
1318        ] {
1319            let value: Decimal = text.parse().unwrap_or_else(|_| panic!("{text}"));
1320            assert_eq!(value.to_string(), expected, "{text}");
1321        }
1322        for text in ["", "-", "abc", "1.2.3", "1e", "NaN", "1 2", "--1"] {
1323            assert!(text.parse::<Decimal>().is_err(), "{text} should not parse");
1324        }
1325    }
1326
1327    #[test]
1328    fn excess_precision_rounds_half_to_even_rather_than_failing() {
1329        // 20 fraction digits: the last two are past what 19 significant digits can hold.
1330        let value: Decimal = "0.12345678901234567895".parse().unwrap();
1331        assert_eq!(value.scale(), Decimal::MAX_SCALE);
1332        assert_eq!(value.to_string(), "0.123456789012345679");
1333        // An integer that cannot be rounded into range is refused rather than mangled.
1334        assert_eq!("1e30".parse::<Decimal>(), Err(ParseDecimalError::Overflow));
1335    }
1336
1337    #[test]
1338    fn arithmetic_is_exact_and_checked() {
1339        let a = decimal!(1.05);
1340        let b = decimal!(2.1);
1341        assert_eq!((a + b).to_string(), "3.15");
1342        assert_eq!((b - a).to_string(), "1.05");
1343        assert_eq!((a * b).to_string(), "2.205");
1344        assert_eq!(a.checked_div(b, 4).unwrap().to_string(), "0.5000");
1345        // Half to even, at the requested scale.
1346        assert_eq!(
1347            decimal!(1).checked_div(decimal!(3), 5).unwrap().to_string(),
1348            "0.33333"
1349        );
1350        assert_eq!(
1351            decimal!(2).checked_div(decimal!(3), 5).unwrap().to_string(),
1352            "0.66667"
1353        );
1354        assert_eq!(decimal!(0.125).round_to(2).unwrap().to_string(), "0.12");
1355        assert_eq!(decimal!(0.135).round_to(2).unwrap().to_string(), "0.14");
1356        assert_eq!(Decimal::new(i64::MAX, 0).checked_add(Decimal::ONE), None);
1357        assert_eq!(decimal!(1).checked_div(Decimal::ZERO, 2), None);
1358    }
1359
1360    /// The 2.x `unitOfMeasure.multiplier` is an `i32` straight off the wire, so every value
1361    /// an `i32` can hold has to have an answer — including the one whose negation overflows.
1362    #[test]
1363    fn an_absurd_exponent_is_refused_rather_than_overflowing() {
1364        assert_eq!(decimal!(1.5).checked_pow10(i32::MIN), None);
1365        assert_eq!(decimal!(1.5).checked_pow10(i32::MAX), None);
1366        assert_eq!(Decimal::ZERO.checked_pow10(i32::MIN), Some(Decimal::ZERO));
1367        assert_eq!(decimal!(1).checked_pow10(19), None);
1368        assert_eq!(
1369            decimal!(1).checked_pow10(18).unwrap().mantissa(),
1370            10i64.pow(18)
1371        );
1372    }
1373
1374    #[test]
1375    fn a_change_of_unit_prefix_only_moves_the_point() {
1376        // kWh to Wh, the conversion that is a routine factor-1000 bug.
1377        let kwh = decimal!(2935.600);
1378        assert_eq!(kwh.checked_pow10(3).unwrap().to_string(), "2935600");
1379        assert_eq!(kwh.checked_pow10(-3).unwrap().to_string(), "2.935600");
1380        assert_eq!(decimal!(1.5).checked_pow10(1).unwrap().to_string(), "15");
1381    }
1382
1383    #[test]
1384    fn comparison_is_numeric_and_ordering_is_total() {
1385        assert_eq!(decimal!(2.50), decimal!(2.5));
1386        assert!(decimal!(2.5) < decimal!(10));
1387        assert!(decimal!(-1) < Decimal::ZERO);
1388        assert_eq!(decimal!(1.10).min(decimal!(1.2)), decimal!(1.1));
1389        assert_eq!(decimal!(1.10).max(decimal!(1.2)), decimal!(1.2));
1390        assert_eq!(decimal!(2.500).normalized().to_string(), "2.5");
1391    }
1392
1393    /// Decoding goes through `serde_json::Deserializer`, the leniency repair loop goes
1394    /// through `serde_json::Value`, and unknown-field detection goes through
1395    /// `serde_json::to_value`. All three have to see the same number.
1396    #[test]
1397    fn every_serde_json_entry_point_agrees() {
1398        let value: Decimal = serde_json::from_str("1.230").unwrap();
1399        assert_eq!(serde_json::to_value(value).unwrap().to_string(), "1.23");
1400        let from_value: Decimal = serde_json::from_value(serde_json::json!(1.23)).unwrap();
1401        assert_eq!(from_value, decimal!(1.23));
1402        let from_int: Decimal = serde_json::from_value(serde_json::json!(7)).unwrap();
1403        assert_eq!(from_int, decimal!(7));
1404
1405        // And through `serde_path_to_error`, which is what the decoder actually uses.
1406        let mut de = serde_json::Deserializer::from_str("2935.600");
1407        let traced: Decimal = serde_path_to_error::deserialize(&mut de).unwrap();
1408        assert!(traced.eq_exact(decimal!(2935.600)));
1409    }
1410
1411    /// The classification the decoder builds on: a string where a number belongs has to read
1412    /// as a *type* error, or `NumericStrings::Coerce` never fires and the OCPP error code is
1413    /// wrong.
1414    #[test]
1415    fn a_wrong_json_type_still_reads_as_a_type_error() {
1416        let error = serde_json::from_str::<Decimal>("\"42\"").unwrap_err();
1417        assert!(
1418            error.to_string().starts_with("invalid type: string"),
1419            "{error}"
1420        );
1421        assert_eq!(error.classify(), serde_json::error::Category::Data);
1422        for (text, expected) in [
1423            ("true", "invalid type: boolean"),
1424            ("null", "invalid type: null"),
1425            ("[]", "invalid type: sequence"),
1426            ("{}", "invalid type: map"),
1427        ] {
1428            let error = serde_json::from_str::<Decimal>(text).unwrap_err();
1429            assert!(error.to_string().starts_with(expected), "{text}: {error}");
1430        }
1431    }
1432
1433    #[test]
1434    fn floating_point_conversion_is_available_but_has_to_be_asked_for() {
1435        assert_eq!(Decimal::from_f64_lossy(0.1).unwrap(), decimal!(0.1));
1436        assert_eq!(
1437            Decimal::from_f64_lossy(1e18).unwrap().to_string(),
1438            "1000000000000000000"
1439        );
1440        assert_eq!(Decimal::from_f64_lossy(f64::NAN), None);
1441        // Past 19 digits there is no mantissa to hold it, and saying so beats guessing.
1442        assert_eq!(Decimal::from_f64_lossy(1e300), None);
1443        assert!((decimal!(2935.600).to_f64_lossy() - 2935.6).abs() < 1e-9);
1444    }
1445
1446    #[test]
1447    fn equal_values_hash_equally_whatever_their_scale() {
1448        use core::hash::BuildHasher;
1449        // One hasher state, or the two hashes would be incomparable whatever the values.
1450        let state = std::collections::hash_map::RandomState::new();
1451        assert_eq!(
1452            state.hash_one(decimal!(2.50)),
1453            state.hash_one(decimal!(2.5))
1454        );
1455        assert_eq!(
1456            state.hash_one(Decimal::ZERO),
1457            state.hash_one(decimal!(0.000))
1458        );
1459    }
1460}