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    /// The value truncated toward zero at `scale`, or `None` on overflow or an out-of-range
311    /// scale.
312    ///
313    /// What a register does: it shows a unit only once the unit is complete, so a figure that
314    /// may be billed never runs ahead of what was delivered.
315    ///
316    /// ```
317    /// use ocpp_kit::types::Decimal;
318    /// let wh: Decimal = "1234.7".parse().unwrap();
319    /// assert_eq!(wh.trunc_to(0), Some(Decimal::from(1234)));
320    /// assert_eq!("-1.9".parse::<Decimal>().unwrap().trunc_to(0), Some(Decimal::from(-1)));
321    /// ```
322    #[must_use]
323    pub const fn trunc_to(self, scale: u8) -> Option<Self> {
324        if scale >= self.scale {
325            return self.rescale(scale);
326        }
327        let drop = (self.scale - scale) as u32;
328        if drop > 38 {
329            return Some(Self { mantissa: 0, scale });
330        }
331        // `i64 / 10^drop` truncates toward zero already; the divisor only overflows i64 past 18.
332        let divisor = pow10_i128(drop);
333        Some(Self {
334            mantissa: (self.mantissa as i128 / divisor) as i64,
335            scale,
336        })
337    }
338
339    // -- arithmetic ---------------------------------------------------------
340
341    /// The sum, at the larger of the two scales, or `None` on overflow.
342    #[must_use]
343    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
344        let scale = if self.scale > rhs.scale {
345            self.scale
346        } else {
347            rhs.scale
348        };
349        let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
350            return None;
351        };
352        narrow(a + b, scale)
353    }
354
355    /// The difference, at the larger of the two scales, or `None` on overflow.
356    ///
357    /// This is the operation OCPP defines a session's energy as, and the reason this type
358    /// exists: `20.2 - 10.1` is `10.1`, not `10.100000000000001`.
359    #[must_use]
360    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
361        let scale = if self.scale > rhs.scale {
362            self.scale
363        } else {
364            rhs.scale
365        };
366        let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
367            return None;
368        };
369        narrow(a - b, scale)
370    }
371
372    /// The product, at the sum of the two scales, or `None` when that does not fit.
373    #[must_use]
374    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
375        let scale = self.scale as u32 + rhs.scale as u32;
376        let product = self.mantissa as i128 * rhs.mantissa as i128;
377        if scale <= Self::MAX_SCALE as u32 {
378            return narrow(product, scale as u8);
379        }
380        // The exact product needs more scale than the type carries; round the surplus away.
381        let drop = scale - Self::MAX_SCALE as u32;
382        let negative = product < 0;
383        let rounded = round_off(product.unsigned_abs(), drop, false);
384        if rounded > i64::MAX as u128 {
385            return None;
386        }
387        let mantissa = rounded as i64;
388        Some(Self {
389            mantissa: if negative { -mantissa } else { mantissa },
390            scale: Self::MAX_SCALE,
391        })
392    }
393
394    /// The quotient at `scale`, rounded half to even, or `None` when `rhs` is zero or the
395    /// result does not fit.
396    ///
397    /// Division is the one operation that has no exact answer in base ten — `1 / 3` does not
398    /// terminate — so the scale to round at is a parameter rather than a guess.
399    #[must_use]
400    pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self> {
401        if rhs.mantissa == 0 || scale > Self::MAX_SCALE {
402            return None;
403        }
404        // (a / 10^sa) / (b / 10^sb) at `scale` == a * 10^(scale + sb - sa) / b.
405        let shift = scale as i32 + rhs.scale as i32 - self.scale as i32;
406        let negative = (self.mantissa < 0) != (rhs.mantissa < 0);
407        let mut numerator = self.mantissa.unsigned_abs() as u128;
408        let denominator = rhs.mantissa.unsigned_abs() as u128;
409        // One extra digit, so the quotient can be rounded half to even.
410        let shift = shift + 1;
411        let mut extra_drop = 0u32;
412        if shift >= 0 {
413            let up = shift as u32;
414            if up > 38 {
415                return None;
416            }
417            let factor = pow10_i128(up) as u128;
418            let Some(scaled) = numerator.checked_mul(factor) else {
419                return None;
420            };
421            numerator = scaled;
422        } else {
423            // Shrinking the numerator instead would throw away the digits the rounding needs,
424            // so the denominator grows.
425            let down = (-shift) as u32;
426            if down > 38 {
427                return None;
428            }
429            extra_drop = down;
430        }
431        let quotient = if extra_drop > 0 {
432            let factor = pow10_i128(extra_drop) as u128;
433            let Some(scaled) = denominator.checked_mul(factor) else {
434                return None;
435            };
436            numerator / scaled
437        } else {
438            numerator / denominator
439        };
440        let remainder_is_zero = if extra_drop > 0 {
441            let factor = pow10_i128(extra_drop) as u128;
442            match denominator.checked_mul(factor) {
443                Some(scaled) => numerator.is_multiple_of(scaled),
444                None => return None,
445            }
446        } else {
447            numerator.is_multiple_of(denominator)
448        };
449        let rounded = round_off(quotient, 1, !remainder_is_zero);
450        if rounded > i64::MAX as u128 {
451            return None;
452        }
453        let mantissa = rounded as i64;
454        Some(Self {
455            mantissa: if negative { -mantissa } else { mantissa },
456            scale,
457        })
458    }
459
460    /// The value multiplied by `10^exp`, exactly, or `None` when it does not fit.
461    ///
462    /// A shift of the decimal point, which is all a change of unit prefix is: kWh to Wh is
463    /// `pow10(3)`, and the 2.x `unitOfMeasure.multiplier` is exactly this operation. Unlike a
464    /// multiplication by a literal `1000.0` it cannot introduce a rounding error, because it
465    /// only moves the point.
466    #[must_use]
467    pub const fn checked_pow10(self, exp: i32) -> Option<Self> {
468        if exp == 0 {
469            return Some(self);
470        }
471        // Nothing outside this range has an answer, and `exp` comes off the wire — the 2.x
472        // `unitOfMeasure.multiplier` is whatever the station put there, `i32::MIN` included,
473        // and negating that is an overflow rather than a large number.
474        if exp > 40 || exp < -40 {
475            return if self.mantissa == 0 {
476                Some(Self::ZERO)
477            } else {
478                None
479            };
480        }
481        if exp < 0 {
482            // Dividing by a power of ten: add scale, which is exact until the cap is reached.
483            let want = self.scale as i32 - exp;
484            if want <= Self::MAX_SCALE as i32 {
485                return Some(Self {
486                    mantissa: self.mantissa,
487                    scale: want as u8,
488                });
489            }
490            // Past the cap the mantissa has to shrink instead, which needs trailing zeros.
491            let surplus = want - Self::MAX_SCALE as i32;
492            let surplus = surplus as u32;
493            if surplus > 18 {
494                return None;
495            }
496            let factor = POW10_U64[surplus as usize] as i64;
497            if self.mantissa % factor != 0 {
498                return None;
499            }
500            return Some(Self {
501                mantissa: self.mantissa / factor,
502                scale: Self::MAX_SCALE,
503            });
504        }
505        // Multiplying by a power of ten: spend the scale first, then grow the mantissa.
506        let mut left = exp as u32;
507        let mut mantissa = self.mantissa;
508        let mut scale = self.scale;
509        while left > 0 && scale > 0 {
510            scale -= 1;
511            left -= 1;
512        }
513        while left > 0 {
514            let step = if left > 18 { 18 } else { left };
515            let Some(next) = mantissa.checked_mul(POW10_U64[step as usize] as i64) else {
516                return None;
517            };
518            mantissa = next;
519            left -= step;
520        }
521        Some(Self { mantissa, scale })
522    }
523
524    /// The absolute value, or `None` for a mantissa of `i64::MIN`.
525    #[must_use]
526    pub const fn checked_abs(self) -> Option<Self> {
527        let Some(mantissa) = self.mantissa.checked_abs() else {
528            return None;
529        };
530        Some(Self {
531            mantissa,
532            scale: self.scale,
533        })
534    }
535
536    /// The negation, or `None` for a mantissa of `i64::MIN`.
537    #[must_use]
538    pub const fn checked_neg(self) -> Option<Self> {
539        let Some(mantissa) = self.mantissa.checked_neg() else {
540            return None;
541        };
542        Some(Self {
543            mantissa,
544            scale: self.scale,
545        })
546    }
547
548    /// The smaller of two values.
549    #[must_use]
550    pub const fn min(self, other: Self) -> Self {
551        match self.compare(other) {
552            Ordering::Greater => other,
553            _ => self,
554        }
555    }
556
557    /// The larger of two values.
558    #[must_use]
559    pub const fn max(self, other: Self) -> Self {
560        match self.compare(other) {
561            Ordering::Less => other,
562            _ => self,
563        }
564    }
565
566    /// Numeric comparison, in a `const` context.
567    #[must_use]
568    pub const fn compare(self, other: Self) -> Ordering {
569        let scale = if self.scale > other.scale {
570            self.scale
571        } else {
572            other.scale
573        };
574        match (self.to_i128_at(scale), other.to_i128_at(scale)) {
575            (Some(a), Some(b)) => {
576                if a < b {
577                    Ordering::Less
578                } else if a > b {
579                    Ordering::Greater
580                } else {
581                    Ordering::Equal
582                }
583            }
584            // Unreachable: 19 digits shifted by at most 18 places fits an i128 with room to
585            // spare. Falling back on the sign keeps the function total anyway.
586            _ => {
587                if self.mantissa < other.mantissa {
588                    Ordering::Less
589                } else if self.mantissa > other.mantissa {
590                    Ordering::Greater
591                } else {
592                    Ordering::Equal
593                }
594            }
595        }
596    }
597
598    /// The mantissa this value would have at `scale`, as an `i128`.
599    const fn to_i128_at(self, scale: u8) -> Option<i128> {
600        if scale < self.scale {
601            return None;
602        }
603        let factor = pow10_i128((scale - self.scale) as u32);
604        Some(self.mantissa as i128 * factor)
605    }
606
607    // -- text ---------------------------------------------------------------
608
609    /// Parses a decimal from ASCII, exactly.
610    ///
611    /// Accepts everything JSON's `number` production allows — an optional sign, digits, an
612    /// optional fraction, an optional `e`/`E` exponent — plus a leading `+`, leading zeros
613    /// and surrounding whitespace, none of which JSON permits but stations send anyway. The
614    /// scale of the result is the number of fraction digits written, so `2935.600` parses to
615    /// scale 3 and prints back identically.
616    ///
617    /// # Errors
618    ///
619    /// [`ParseDecimalError::Invalid`] when the text is not a number at all, and
620    /// [`ParseDecimalError::Overflow`] when its integer part needs more than 19 digits.
621    /// Excess *fraction* digits are rounded half to even rather than refused, because
622    /// refusing a value the schema calls valid is worse than rounding at the nineteenth
623    /// significant digit.
624    // One parser, in one place: splitting it would hand the pieces a half-parsed state to
625    // agree about, which is how parsers grow disagreements.
626    #[allow(clippy::too_many_lines)]
627    pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
628        let n = bytes.len();
629        let mut i = 0usize;
630        while i < n && is_space(bytes[i]) {
631            i += 1;
632        }
633        let mut negative = false;
634        if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
635            negative = bytes[i] == b'-';
636            i += 1;
637        }
638
639        let mut magnitude: u128 = 0;
640        let mut fraction_digits: i64 = 0;
641        let mut skipped_integer_digits: i64 = 0;
642        let mut round_digit: u8 = 0;
643        let mut sticky = false;
644        let mut dropped_any = false;
645        let mut seen_digit = false;
646        let mut seen_point = false;
647
648        while i < n {
649            let byte = bytes[i];
650            if byte == b'.' {
651                if seen_point {
652                    return Err(ParseDecimalError::Invalid);
653                }
654                seen_point = true;
655                i += 1;
656                continue;
657            }
658            if byte < b'0' || byte > b'9' {
659                break;
660            }
661            seen_digit = true;
662            let digit = byte - b'0';
663            if magnitude < ACCUMULATE_LIMIT {
664                magnitude = magnitude * 10 + digit as u128;
665                if seen_point {
666                    fraction_digits += 1;
667                }
668            } else {
669                // No room left in the accumulator: the digit only decides the rounding.
670                if !seen_point {
671                    skipped_integer_digits += 1;
672                }
673                if dropped_any {
674                    if digit != 0 {
675                        sticky = true;
676                    }
677                } else {
678                    round_digit = digit;
679                    dropped_any = true;
680                }
681            }
682            i += 1;
683        }
684        if !seen_digit {
685            return Err(ParseDecimalError::Invalid);
686        }
687        let mut rounded_off = false;
688        if dropped_any {
689            if round_digit > 5 || (round_digit == 5 && (sticky || magnitude % 2 == 1)) {
690                magnitude += 1;
691            }
692            rounded_off = true;
693        }
694
695        let mut exponent: i64 = 0;
696        if i < n && (bytes[i] == b'e' || bytes[i] == b'E') {
697            i += 1;
698            let mut exponent_negative = false;
699            if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
700                exponent_negative = bytes[i] == b'-';
701                i += 1;
702            }
703            let mut seen_exponent_digit = false;
704            while i < n && bytes[i] >= b'0' && bytes[i] <= b'9' {
705                seen_exponent_digit = true;
706                // Clamped: anything past a few hundred is out of range either way.
707                if exponent < 1_000_000 {
708                    exponent = exponent * 10 + (bytes[i] - b'0') as i64;
709                }
710                i += 1;
711            }
712            if !seen_exponent_digit {
713                return Err(ParseDecimalError::Invalid);
714            }
715            if exponent_negative {
716                exponent = -exponent;
717            }
718        }
719        while i < n && is_space(bytes[i]) {
720            i += 1;
721        }
722        if i != n {
723            return Err(ParseDecimalError::Invalid);
724        }
725
726        // value == magnitude × 10^(skipped_integer_digits + exponent - fraction_digits)
727        let mut scale = fraction_digits - skipped_integer_digits - exponent;
728        if magnitude == 0 {
729            // Zero has no significant digits to place; keep the written fraction width when
730            // it is representable, so `0.00` stays `0.00`.
731            if scale < 0 || scale > Self::MAX_SCALE as i64 {
732                scale = 0;
733            }
734            return Ok(Self {
735                mantissa: 0,
736                scale: scale as u8,
737            });
738        }
739
740        if scale < 0 {
741            let shift = -scale;
742            if shift > 38 {
743                return Err(ParseDecimalError::Overflow);
744            }
745            let factor = pow10_i128(shift as u32) as u128;
746            let Some(scaled) = magnitude.checked_mul(factor) else {
747                return Err(ParseDecimalError::Overflow);
748            };
749            magnitude = scaled;
750            scale = 0;
751        } else if scale > Self::MAX_SCALE as i64 {
752            let drop = scale - Self::MAX_SCALE as i64;
753            if drop > 39 {
754                magnitude = 0;
755            } else {
756                let dropped = drop as u32;
757                magnitude = round_off(magnitude, dropped, false);
758            }
759            scale = Self::MAX_SCALE as i64;
760            rounded_off = true;
761        }
762
763        // Whatever is left has to fit an i64, which may cost further fraction digits.
764        while magnitude > i64::MAX as u128 {
765            if scale == 0 {
766                return Err(ParseDecimalError::Overflow);
767            }
768            magnitude = round_off(magnitude, 1, false);
769            scale -= 1;
770            rounded_off = true;
771        }
772        let _ = rounded_off;
773        let mantissa = magnitude as i64;
774        Ok(Self {
775            mantissa: if negative { -mantissa } else { mantissa },
776            scale: scale as u8,
777        })
778    }
779
780    /// Parses a Rust numeric literal, panicking instead of returning an error.
781    ///
782    /// This is what [`decimal!`](crate::decimal) expands to, so the panic is a compile error
783    /// rather than a runtime one. It differs from [`from_ascii`](Self::from_ascii) in
784    /// accepting Rust's `_` digit separators — `decimal!(11_000)` is how the number would be
785    /// written anywhere else in the source, and JSON never contains one, so the leniency
786    /// costs the wire path nothing.
787    ///
788    /// # Panics
789    ///
790    /// If the text is not a decimal number.
791    #[must_use]
792    pub const fn from_literal(text: &str) -> Self {
793        let bytes = text.as_bytes();
794        // A stack copy with the separators removed; `const` rules out allocating one.
795        let mut digits = [0u8; 64];
796        let mut len = 0usize;
797        let mut i = 0usize;
798        while i < bytes.len() {
799            if bytes[i] != b'_' {
800                assert!(len < 64, "decimal literal is too long");
801                digits[len] = bytes[i];
802                len += 1;
803            }
804            i += 1;
805        }
806        let (kept, _) = digits.split_at(len);
807        match Self::from_ascii(kept) {
808            Ok(value) => value,
809            Err(ParseDecimalError::Invalid) => panic!("not a decimal number"),
810            Err(ParseDecimalError::Overflow) => panic!("decimal number out of range"),
811        }
812    }
813
814    // -- floating point -----------------------------------------------------
815
816    /// The value as an `f64`, correctly rounded.
817    ///
818    /// Named for what it costs: past 15 significant digits the result is not the number this
819    /// `Decimal` holds, and no arithmetic done on it afterwards is exact. Nothing in this
820    /// crate calls it.
821    #[must_use]
822    #[allow(clippy::cast_precision_loss)] // The whole point of the name.
823    pub fn to_f64_lossy(self) -> f64 {
824        const POW10_F64: [f64; 19] = [
825            1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
826            1e16, 1e17, 1e18,
827        ];
828        let mantissa = self.mantissa as f64;
829        mantissa / POW10_F64[self.scale as usize]
830    }
831
832    /// The decimal an `f64` is nearest to, or `None` for an infinity, a NaN, or a magnitude
833    /// out of range.
834    ///
835    /// Named for what it costs: the `f64` `0.1` is not one tenth, and this returns the
836    /// shortest decimal that reads back as the same `f64` — `0.1` — rather than the value it
837    /// actually holds. That is the friendly answer, and it is still a guess about what the
838    /// number was before it became a float. Parse the text instead when there is text.
839    #[must_use]
840    pub fn from_f64_lossy(value: f64) -> Option<Self> {
841        if !value.is_finite() {
842            return None;
843        }
844        let mut buffer = TextBuffer::new();
845        // The exponent form is the shortest round-tripping spelling and is bounded in length;
846        // `{}` would spell 1e300 out in full.
847        if fmt::Write::write_fmt(&mut buffer, format_args!("{value:e}")).is_err() {
848            return None;
849        }
850        Self::from_ascii(buffer.as_bytes()).ok()
851    }
852}
853
854/// Drops `digits` decimal digits from `magnitude`, rounding half to even.
855///
856/// `sticky` says whether anything non-zero was already discarded below those digits, which is
857/// what turns an exact half into a value above it.
858const fn round_off(magnitude: u128, digits: u32, sticky: bool) -> u128 {
859    if digits == 0 {
860        return magnitude;
861    }
862    if digits > 38 {
863        return 0;
864    }
865    let divisor = pow10_i128(digits) as u128;
866    let quotient = magnitude / divisor;
867    let remainder = magnitude % divisor;
868    let half = divisor / 2;
869    if remainder > half || (remainder == half && (sticky || quotient % 2 == 1)) {
870        quotient + 1
871    } else {
872        quotient
873    }
874}
875
876/// Narrows an `i128` mantissa back to a `Decimal`, or `None` when it does not fit.
877const fn narrow(mantissa: i128, scale: u8) -> Option<Decimal> {
878    if mantissa > i64::MAX as i128 || mantissa < i64::MIN as i128 {
879        return None;
880    }
881    Some(Decimal {
882        mantissa: mantissa as i64,
883        scale,
884    })
885}
886
887const fn is_space(byte: u8) -> bool {
888    matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
889}
890
891/// Why a decimal could not be parsed.
892#[derive(Clone, Copy, Debug, PartialEq, Eq)]
893#[non_exhaustive]
894pub enum ParseDecimalError {
895    /// The text is not a number.
896    Invalid,
897    /// The number needs more than 19 digits before the decimal point.
898    Overflow,
899}
900
901impl fmt::Display for ParseDecimalError {
902    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903        f.write_str(match self {
904            ParseDecimalError::Invalid => "not a decimal number",
905            ParseDecimalError::Overflow => "decimal number out of range",
906        })
907    }
908}
909
910#[cfg(feature = "std")]
911impl std::error::Error for ParseDecimalError {}
912
913impl FromStr for Decimal {
914    type Err = ParseDecimalError;
915
916    fn from_str(text: &str) -> Result<Self, Self::Err> {
917        Self::from_ascii(text.as_bytes())
918    }
919}
920
921impl fmt::Debug for Decimal {
922    /// The number, not its representation: `Decimal(2935.600)`. A `{mantissa, scale}` dump is
923    /// what a reader has to decode by hand every time one of these appears in a log line.
924    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
925        write!(f, "Decimal({self})")
926    }
927}
928
929impl fmt::Display for Decimal {
930    /// Writes the value at its own scale, so `2935.600` prints as `2935.600`.
931    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932        if self.scale == 0 {
933            return write!(f, "{}", self.mantissa);
934        }
935        let magnitude = self.mantissa.unsigned_abs();
936        let divisor = POW10_U64[self.scale as usize];
937        let sign = if self.mantissa < 0 { "-" } else { "" };
938        write!(
939            f,
940            "{sign}{}.{:0width$}",
941            magnitude / divisor,
942            magnitude % divisor,
943            width = self.scale as usize
944        )
945    }
946}
947
948// ---------------------------------------------------------------------------
949// Comparison
950// ---------------------------------------------------------------------------
951
952impl PartialEq for Decimal {
953    fn eq(&self, other: &Self) -> bool {
954        self.compare(*other) == Ordering::Equal
955    }
956}
957
958impl Eq for Decimal {}
959
960impl PartialOrd for Decimal {
961    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
962        Some(self.cmp(other))
963    }
964}
965
966impl Ord for Decimal {
967    fn cmp(&self, other: &Self) -> Ordering {
968        self.compare(*other)
969    }
970}
971
972impl Hash for Decimal {
973    /// Hashes the normalized value, so `2.50` and `2.5` — which compare equal — hash equal.
974    fn hash<H: Hasher>(&self, state: &mut H) {
975        let normalized = self.normalized();
976        normalized.mantissa.hash(state);
977        normalized.scale.hash(state);
978    }
979}
980
981// ---------------------------------------------------------------------------
982// Operators
983// ---------------------------------------------------------------------------
984
985macro_rules! binary_op {
986    ($trait:ident, $method:ident, $checked:ident, $what:literal) => {
987        impl $trait for Decimal {
988            type Output = Decimal;
989            /// # Panics
990            ///
991            /// On overflow, like the integer operators. Use the `checked_` form to handle it.
992            fn $method(self, rhs: Decimal) -> Decimal {
993                self.$checked(rhs)
994                    .expect(concat!("Decimal ", $what, " overflowed"))
995            }
996        }
997    };
998}
999
1000binary_op!(Add, add, checked_add, "addition");
1001binary_op!(Sub, sub, checked_sub, "subtraction");
1002binary_op!(Mul, mul, checked_mul, "multiplication");
1003
1004impl Div for Decimal {
1005    type Output = Decimal;
1006
1007    /// Division at [`Decimal::MAX_SCALE`], rounded half to even.
1008    ///
1009    /// # Panics
1010    ///
1011    /// On division by zero or overflow. [`Decimal::checked_div`] takes the scale to round at
1012    /// and returns `None` instead, which is what production code should use.
1013    fn div(self, rhs: Decimal) -> Decimal {
1014        self.checked_div(rhs, Decimal::MAX_SCALE)
1015            .expect("Decimal division by zero or overflow")
1016    }
1017}
1018
1019impl Neg for Decimal {
1020    type Output = Decimal;
1021
1022    /// # Panics
1023    ///
1024    /// Only for a mantissa of `i64::MIN`, which no parsed value has.
1025    fn neg(self) -> Decimal {
1026        self.checked_neg().expect("Decimal negation overflowed")
1027    }
1028}
1029
1030impl AddAssign for Decimal {
1031    fn add_assign(&mut self, rhs: Decimal) {
1032        *self = *self + rhs;
1033    }
1034}
1035
1036impl SubAssign for Decimal {
1037    fn sub_assign(&mut self, rhs: Decimal) {
1038        *self = *self - rhs;
1039    }
1040}
1041
1042impl core::iter::Sum for Decimal {
1043    fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
1044        iter.fold(Decimal::ZERO, |total, value| total + value)
1045    }
1046}
1047
1048// ---------------------------------------------------------------------------
1049// Conversions
1050// ---------------------------------------------------------------------------
1051
1052macro_rules! from_integer {
1053    ($($ty:ty),*) => {
1054        $(
1055            impl From<$ty> for Decimal {
1056                fn from(value: $ty) -> Self {
1057                    Self { mantissa: i64::from(value), scale: 0 }
1058                }
1059            }
1060        )*
1061    };
1062}
1063
1064from_integer!(i8, i16, i32, i64, u8, u16, u32);
1065
1066impl TryFrom<u64> for Decimal {
1067    type Error = ParseDecimalError;
1068
1069    fn try_from(value: u64) -> Result<Self, Self::Error> {
1070        i64::try_from(value)
1071            .map(Self::from_i64)
1072            .map_err(|_| ParseDecimalError::Overflow)
1073    }
1074}
1075
1076impl TryFrom<Decimal> for i64 {
1077    type Error = ParseDecimalError;
1078
1079    /// Succeeds only when the value is a whole number.
1080    fn try_from(value: Decimal) -> Result<Self, Self::Error> {
1081        value
1082            .rescale(0)
1083            .map(Decimal::mantissa)
1084            .ok_or(ParseDecimalError::Invalid)
1085    }
1086}
1087
1088// ---------------------------------------------------------------------------
1089// A stack buffer, so formatting a Decimal never allocates
1090// ---------------------------------------------------------------------------
1091
1092/// Enough for a sign, 19 digits, a point and an exponent.
1093const TEXT_CAPACITY: usize = 40;
1094
1095struct TextBuffer {
1096    bytes: [u8; TEXT_CAPACITY],
1097    len: usize,
1098}
1099
1100impl TextBuffer {
1101    const fn new() -> Self {
1102        Self {
1103            bytes: [0; TEXT_CAPACITY],
1104            len: 0,
1105        }
1106    }
1107
1108    fn as_bytes(&self) -> &[u8] {
1109        &self.bytes[..self.len]
1110    }
1111
1112    fn as_str(&self) -> &str {
1113        // Only `core::fmt` writes here, and it only writes UTF-8; the slice ends on a
1114        // character boundary because a write either fits whole or fails.
1115        core::str::from_utf8(self.as_bytes()).unwrap_or("0")
1116    }
1117}
1118
1119impl fmt::Write for TextBuffer {
1120    fn write_str(&mut self, text: &str) -> fmt::Result {
1121        let end = self.len + text.len();
1122        if end > TEXT_CAPACITY {
1123            return Err(fmt::Error);
1124        }
1125        self.bytes[self.len..end].copy_from_slice(text.as_bytes());
1126        self.len = end;
1127        Ok(())
1128    }
1129}
1130
1131// ---------------------------------------------------------------------------
1132// serde
1133// ---------------------------------------------------------------------------
1134
1135/// `serde_json`'s private marker for a value carried as raw JSON text.
1136///
1137/// Asking for it is how a `Deserialize` impl sees the number *as the peer wrote it* rather
1138/// than as whatever `f64` the parser would round it to — which is the entire point of this
1139/// type. `serde_json` answers with the source token; any other data format falls through to
1140/// `deserialize_any` below and gets the ordinary numeric path.
1141const RAW_TOKEN: &str = "$serde_json::private::RawValue";
1142
1143impl Serialize for Decimal {
1144    /// Writes the number as the peer would have written it: the mantissa at its own scale, so
1145    /// `2935.600` goes back out as `2935.600` and not as `2935.6`.
1146    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1147        use serde::ser::SerializeStruct as _;
1148        let mut buffer = TextBuffer::new();
1149        if fmt::Write::write_fmt(&mut buffer, format_args!("{self}")).is_err() {
1150            return Err(serde::ser::Error::custom("decimal is too long to render"));
1151        }
1152        let mut raw = serializer.serialize_struct(RAW_TOKEN, 1)?;
1153        raw.serialize_field(RAW_TOKEN, buffer.as_str())?;
1154        raw.end()
1155    }
1156}
1157
1158impl<'de> Deserialize<'de> for Decimal {
1159    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1160        deserializer.deserialize_newtype_struct(RAW_TOKEN, DecimalVisitor)
1161    }
1162}
1163
1164struct DecimalVisitor;
1165
1166impl<'de> serde::de::Visitor<'de> for DecimalVisitor {
1167    type Value = Decimal;
1168
1169    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1170        f.write_str("a JSON number")
1171    }
1172
1173    fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Decimal, E> {
1174        Ok(Decimal::from_i64(value))
1175    }
1176
1177    fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Decimal, E> {
1178        Decimal::try_from(value).map_err(|_| E::custom("number out of range for a decimal"))
1179    }
1180
1181    fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Decimal, E> {
1182        Decimal::from_f64_lossy(value)
1183            .ok_or_else(|| E::custom("number is not a finite decimal in range"))
1184    }
1185
1186    /// The data format handed back a newtype rather than raw text — it is not `serde_json`.
1187    /// Take the ordinary numeric path.
1188    fn visit_newtype_struct<D: serde::Deserializer<'de>>(
1189        self,
1190        deserializer: D,
1191    ) -> Result<Decimal, D::Error> {
1192        deserializer.deserialize_any(DecimalVisitor)
1193    }
1194
1195    /// `serde_json` answers the raw-value request with a one-entry map holding the source
1196    /// token. Parsing that token is what keeps `2935.600` from becoming `2935.6`.
1197    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Decimal, A::Error> {
1198        use serde::de::Error as _;
1199        let Some(RawKey) = map.next_key::<RawKey>()? else {
1200            return Err(A::Error::custom("expected a JSON number"));
1201        };
1202        let RawToken(value) = map.next_value::<RawToken>()?;
1203        Ok(value)
1204    }
1205}
1206
1207/// The key of `serde_json`'s raw-value map, which is a fixed marker and carries no meaning.
1208struct RawKey;
1209
1210impl<'de> Deserialize<'de> for RawKey {
1211    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1212        struct KeyVisitor;
1213        impl serde::de::Visitor<'_> for KeyVisitor {
1214            type Value = RawKey;
1215            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216                f.write_str("a raw value marker")
1217            }
1218            fn visit_str<E: serde::de::Error>(self, _value: &str) -> Result<RawKey, E> {
1219                Ok(RawKey)
1220            }
1221        }
1222        deserializer.deserialize_identifier(KeyVisitor)
1223    }
1224}
1225
1226/// One raw JSON token, parsed as a decimal.
1227struct RawToken(Decimal);
1228
1229impl<'de> Deserialize<'de> for RawToken {
1230    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1231        struct TokenVisitor;
1232        impl serde::de::Visitor<'_> for TokenVisitor {
1233            type Value = RawToken;
1234
1235            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236                f.write_str("a JSON number")
1237            }
1238
1239            fn visit_str<E: serde::de::Error>(self, token: &str) -> Result<RawToken, E> {
1240                use serde::de::Unexpected;
1241                // The token is whatever stood where a number belongs. Reporting the *JSON
1242                // type* of what actually arrived is what keeps `invalid type: …` — and with
1243                // it the TypeConstraintViolation classification, and the numeric-string
1244                // repair — working exactly as it does for every other field.
1245                let trimmed = token.trim();
1246                let unexpected = match trimmed.as_bytes().first() {
1247                    Some(b'"') => Some(Unexpected::Str(trimmed.trim_matches('"'))),
1248                    Some(b'{') => Some(Unexpected::Map),
1249                    Some(b'[') => Some(Unexpected::Seq),
1250                    Some(b't') => Some(Unexpected::Bool(true)),
1251                    Some(b'f') => Some(Unexpected::Bool(false)),
1252                    Some(b'n') => Some(Unexpected::Unit),
1253                    _ => None,
1254                };
1255                if let Some(unexpected) = unexpected {
1256                    return Err(E::invalid_type(unexpected, &"a JSON number"));
1257                }
1258                Decimal::from_ascii(trimmed.as_bytes())
1259                    .map(RawToken)
1260                    .map_err(|error| {
1261                        let expected: &str = match error {
1262                            ParseDecimalError::Overflow => "a decimal number in range",
1263                            ParseDecimalError::Invalid => "a decimal number",
1264                        };
1265                        E::invalid_value(Unexpected::Other(trimmed), &expected)
1266                    })
1267            }
1268        }
1269        deserializer.deserialize_str(TokenVisitor)
1270    }
1271}
1272
1273impl Validate for Decimal {
1274    /// Nothing to check: unlike an `f64`, a `Decimal` cannot hold a value JSON has no
1275    /// spelling for. Range constraints are emitted per field by the code generator.
1276    fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
1277}
1278
1279// ---------------------------------------------------------------------------
1280// Literals
1281// ---------------------------------------------------------------------------
1282
1283/// An exact [`Decimal`] literal, parsed at compile time.
1284///
1285/// ```
1286/// use ocpp_kit::decimal;
1287///
1288/// let limit = decimal!(32.5);
1289/// assert_eq!(limit.scale(), 1);
1290/// assert_eq!(limit.mantissa(), 325);
1291/// ```
1292///
1293/// The digits are read from the source text, so the value is the one written rather than the
1294/// nearest `f64` to it, and a malformed literal is a compile error.
1295#[macro_export]
1296macro_rules! decimal {
1297    ($($token:tt)+) => {
1298        const {
1299            $crate::types::Decimal::from_literal(::core::stringify!($($token)+))
1300        }
1301    };
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306    use super::*;
1307
1308    #[test]
1309    fn trunc_to_drops_toward_zero_and_never_rounds_up() {
1310        let d = |s: &str| s.parse::<Decimal>().unwrap();
1311        assert_eq!(d("1234.7").trunc_to(0), Some(d("1234")));
1312        assert_eq!(d("1234.5").trunc_to(0), Some(d("1234")));
1313        assert_eq!(d("1234.99999").trunc_to(2), Some(d("1234.99")));
1314        assert_eq!(d("-1.9").trunc_to(0), Some(d("-1")));
1315        assert_eq!(d("-0.5").trunc_to(0), Some(d("0")));
1316        assert_eq!(d("12").trunc_to(2).map(Decimal::scale), Some(2));
1317        assert!(d("12").trunc_to(2).unwrap().eq_exact(d("12.00")));
1318        assert_eq!(
1319            Decimal::new(i64::MAX, 18).trunc_to(0),
1320            Some(Decimal::from(9))
1321        );
1322        assert_eq!(
1323            Decimal::new(i64::MIN, 0).trunc_to(0),
1324            Some(Decimal::new(i64::MIN, 0))
1325        );
1326    }
1327    use alloc::string::ToString;
1328
1329    #[test]
1330    fn the_scale_the_station_sent_survives_the_round_trip() {
1331        // The whole point: `2935.600` states three decimals of resolution, and an f64 cannot
1332        // hold that claim — `2935.600` and `2935.6` are the same f64.
1333        let value: Decimal = serde_json::from_str("2935.600").unwrap();
1334        assert_eq!(value.scale(), 3);
1335        assert_eq!(value.mantissa(), 2_935_600);
1336        assert_eq!(serde_json::to_string(&value).unwrap(), "2935.600");
1337        assert_eq!(value.to_string(), "2935.600");
1338
1339        // Equal in value, different in what they claim about the meter.
1340        let short: Decimal = serde_json::from_str("2935.6").unwrap();
1341        assert_eq!(value, short);
1342        assert!(!value.eq_exact(short));
1343    }
1344
1345    #[test]
1346    fn a_difference_of_two_registers_is_exact() {
1347        // The f64 answer to this is 10.000000000000002.
1348        let start: Decimal = "0.1".parse().unwrap();
1349        let stop: Decimal = "10.2".parse().unwrap();
1350        assert_eq!((stop - start).to_string(), "10.1");
1351    }
1352
1353    #[test]
1354    fn every_json_number_spelling_parses() {
1355        for (text, expected) in [
1356            ("0", "0"),
1357            ("-0", "0"),
1358            ("42", "42"),
1359            ("-17.25", "-17.25"),
1360            ("0.00", "0.00"),
1361            ("1e3", "1000"),
1362            ("1.5E+3", "1500"),
1363            ("15e-1", "1.5"),
1364            ("2E-4", "0.0002"),
1365            ("0.000000000000000001", "0.000000000000000001"),
1366            ("9223372036854775807", "9223372036854775807"),
1367        ] {
1368            let value: Decimal = text.parse().unwrap_or_else(|_| panic!("{text}"));
1369            assert_eq!(value.to_string(), expected, "{text}");
1370        }
1371        for text in ["", "-", "abc", "1.2.3", "1e", "NaN", "1 2", "--1"] {
1372            assert!(text.parse::<Decimal>().is_err(), "{text} should not parse");
1373        }
1374    }
1375
1376    #[test]
1377    fn excess_precision_rounds_half_to_even_rather_than_failing() {
1378        // 20 fraction digits: the last two are past what 19 significant digits can hold.
1379        let value: Decimal = "0.12345678901234567895".parse().unwrap();
1380        assert_eq!(value.scale(), Decimal::MAX_SCALE);
1381        assert_eq!(value.to_string(), "0.123456789012345679");
1382        // An integer that cannot be rounded into range is refused rather than mangled.
1383        assert_eq!("1e30".parse::<Decimal>(), Err(ParseDecimalError::Overflow));
1384    }
1385
1386    #[test]
1387    fn arithmetic_is_exact_and_checked() {
1388        let a = decimal!(1.05);
1389        let b = decimal!(2.1);
1390        assert_eq!((a + b).to_string(), "3.15");
1391        assert_eq!((b - a).to_string(), "1.05");
1392        assert_eq!((a * b).to_string(), "2.205");
1393        assert_eq!(a.checked_div(b, 4).unwrap().to_string(), "0.5000");
1394        // Half to even, at the requested scale.
1395        assert_eq!(
1396            decimal!(1).checked_div(decimal!(3), 5).unwrap().to_string(),
1397            "0.33333"
1398        );
1399        assert_eq!(
1400            decimal!(2).checked_div(decimal!(3), 5).unwrap().to_string(),
1401            "0.66667"
1402        );
1403        assert_eq!(decimal!(0.125).round_to(2).unwrap().to_string(), "0.12");
1404        assert_eq!(decimal!(0.135).round_to(2).unwrap().to_string(), "0.14");
1405        assert_eq!(Decimal::new(i64::MAX, 0).checked_add(Decimal::ONE), None);
1406        assert_eq!(decimal!(1).checked_div(Decimal::ZERO, 2), None);
1407    }
1408
1409    /// The 2.x `unitOfMeasure.multiplier` is an `i32` straight off the wire, so every value
1410    /// an `i32` can hold has to have an answer — including the one whose negation overflows.
1411    #[test]
1412    fn an_absurd_exponent_is_refused_rather_than_overflowing() {
1413        assert_eq!(decimal!(1.5).checked_pow10(i32::MIN), None);
1414        assert_eq!(decimal!(1.5).checked_pow10(i32::MAX), None);
1415        assert_eq!(Decimal::ZERO.checked_pow10(i32::MIN), Some(Decimal::ZERO));
1416        assert_eq!(decimal!(1).checked_pow10(19), None);
1417        assert_eq!(
1418            decimal!(1).checked_pow10(18).unwrap().mantissa(),
1419            10i64.pow(18)
1420        );
1421    }
1422
1423    #[test]
1424    fn a_change_of_unit_prefix_only_moves_the_point() {
1425        // kWh to Wh, the conversion that is a routine factor-1000 bug.
1426        let kwh = decimal!(2935.600);
1427        assert_eq!(kwh.checked_pow10(3).unwrap().to_string(), "2935600");
1428        assert_eq!(kwh.checked_pow10(-3).unwrap().to_string(), "2.935600");
1429        assert_eq!(decimal!(1.5).checked_pow10(1).unwrap().to_string(), "15");
1430    }
1431
1432    #[test]
1433    fn comparison_is_numeric_and_ordering_is_total() {
1434        assert_eq!(decimal!(2.50), decimal!(2.5));
1435        assert!(decimal!(2.5) < decimal!(10));
1436        assert!(decimal!(-1) < Decimal::ZERO);
1437        assert_eq!(decimal!(1.10).min(decimal!(1.2)), decimal!(1.1));
1438        assert_eq!(decimal!(1.10).max(decimal!(1.2)), decimal!(1.2));
1439        assert_eq!(decimal!(2.500).normalized().to_string(), "2.5");
1440    }
1441
1442    /// Decoding goes through `serde_json::Deserializer`, the leniency repair loop goes
1443    /// through `serde_json::Value`, and unknown-field detection goes through
1444    /// `serde_json::to_value`. All three have to see the same number.
1445    #[test]
1446    fn every_serde_json_entry_point_agrees() {
1447        let value: Decimal = serde_json::from_str("1.230").unwrap();
1448        assert_eq!(serde_json::to_value(value).unwrap().to_string(), "1.23");
1449        let from_value: Decimal = serde_json::from_value(serde_json::json!(1.23)).unwrap();
1450        assert_eq!(from_value, decimal!(1.23));
1451        let from_int: Decimal = serde_json::from_value(serde_json::json!(7)).unwrap();
1452        assert_eq!(from_int, decimal!(7));
1453
1454        // And through `serde_path_to_error`, which is what the decoder actually uses.
1455        let mut de = serde_json::Deserializer::from_str("2935.600");
1456        let traced: Decimal = serde_path_to_error::deserialize(&mut de).unwrap();
1457        assert!(traced.eq_exact(decimal!(2935.600)));
1458    }
1459
1460    /// The classification the decoder builds on: a string where a number belongs has to read
1461    /// as a *type* error, or `NumericStrings::Coerce` never fires and the OCPP error code is
1462    /// wrong.
1463    #[test]
1464    fn a_wrong_json_type_still_reads_as_a_type_error() {
1465        let error = serde_json::from_str::<Decimal>("\"42\"").unwrap_err();
1466        assert!(
1467            error.to_string().starts_with("invalid type: string"),
1468            "{error}"
1469        );
1470        assert_eq!(error.classify(), serde_json::error::Category::Data);
1471        for (text, expected) in [
1472            ("true", "invalid type: boolean"),
1473            ("null", "invalid type: null"),
1474            ("[]", "invalid type: sequence"),
1475            ("{}", "invalid type: map"),
1476        ] {
1477            let error = serde_json::from_str::<Decimal>(text).unwrap_err();
1478            assert!(error.to_string().starts_with(expected), "{text}: {error}");
1479        }
1480    }
1481
1482    #[test]
1483    fn floating_point_conversion_is_available_but_has_to_be_asked_for() {
1484        assert_eq!(Decimal::from_f64_lossy(0.1).unwrap(), decimal!(0.1));
1485        assert_eq!(
1486            Decimal::from_f64_lossy(1e18).unwrap().to_string(),
1487            "1000000000000000000"
1488        );
1489        assert_eq!(Decimal::from_f64_lossy(f64::NAN), None);
1490        // Past 19 digits there is no mantissa to hold it, and saying so beats guessing.
1491        assert_eq!(Decimal::from_f64_lossy(1e300), None);
1492        assert!((decimal!(2935.600).to_f64_lossy() - 2935.6).abs() < 1e-9);
1493    }
1494
1495    #[test]
1496    fn equal_values_hash_equally_whatever_their_scale() {
1497        use core::hash::BuildHasher;
1498        // One hasher state, or the two hashes would be incomparable whatever the values.
1499        let state = std::collections::hash_map::RandomState::new();
1500        assert_eq!(
1501            state.hash_one(decimal!(2.50)),
1502            state.hash_one(decimal!(2.5))
1503        );
1504        assert_eq!(
1505            state.hash_one(Decimal::ZERO),
1506            state.hash_one(decimal!(0.000))
1507        );
1508    }
1509}