Skip to main content

mbus_kit/
value.rs

1use core::fmt;
2
3use crate::time::{Date, DateTime, Time};
4
5/// A record's value.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Value<'a> {
8    /// No data.
9    None,
10    /// A binary integer (data type B, two's complement).
11    Int(i64),
12    /// An unsigned binary integer (data type C, announced by the combinable extension
13    /// VIFE `FC 11`).
14    UInt(u64),
15    /// A BCD number.
16    Bcd(i64),
17    /// A BCD field with digits outside 0–9 (meters use this to signal errors). The raw
18    /// bytes, as transmitted.
19    InvalidBcd(&'a [u8]),
20    /// A 32-bit IEEE 754 real, as raw bits. [`Value::as_decimal`] and
21    /// [`Record::quantity`](crate::Record::quantity) give its exact decimal value; no
22    /// float is involved (D-012).
23    Real32(u32),
24    /// A date (type G).
25    Date(Date),
26    /// A time of day (type J).
27    Time(Time),
28    /// A date and time (type F or I).
29    DateTime(DateTime),
30    /// A text (variable length, LVAR `00`–`BF`), as transmitted (M-Bus sends it reversed).
31    Text(&'a [u8]),
32    /// Binary data longer than 8 bytes (LVAR `E9`–`EF`, `F0`–`F6`).
33    Bytes(&'a [u8]),
34    /// A duration in seconds, exact: data type M in its relative form (EN 13757-3:2018
35    /// Table A.12, e.g. "offset 3 s" in OMS Annex N N.13).
36    Duration(Quantity),
37}
38
39impl fmt::Display for Value<'_> {
40    /// Integers in decimal, dates ISO-8601-like, text in reading order. Bytes from the
41    /// meter are never written raw: anything but printable ASCII is escaped as `\xNN`,
42    /// so a crafted telegram cannot put control sequences into a terminal or log
43    /// (001-describe-every-record/SR-003).
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        match *self {
46            Self::None => f.write_str("—"),
47            Self::Int(v) | Self::Bcd(v) => write!(f, "{v}"),
48            Self::UInt(v) => write!(f, "{v}"),
49            Self::InvalidBcd(b) => {
50                f.write_str("invalid BCD ")?;
51                hex(f, b.iter().rev())
52            }
53            Self::Real32(bits) => match real32_exact(bits) {
54                Some((mantissa, exponent)) => write!(f, "{}", Quantity { mantissa, exponent, unit: None }),
55                None => write!(f, "IEEE 754 0x{bits:08X}"),
56            },
57            Self::Date(d) => write!(f, "{d}"),
58            Self::Time(t) => write!(f, "{t}"),
59            Self::DateTime(t) => write!(f, "{t}"),
60            Self::Text(t) => escaped(f, t.iter().rev()),
61            Self::Bytes(b) => hex(f, b.iter()),
62            Self::Duration(q) => write!(f, "{q}"),
63        }
64    }
65}
66
67/// Printable ASCII as is, everything else as `\xNN`.
68pub(crate) fn escaped<'b>(f: &mut fmt::Formatter<'_>, bytes: impl Iterator<Item = &'b u8>) -> fmt::Result {
69    for &b in bytes {
70        if b == b' ' || b.is_ascii_graphic() && b != b'\\' {
71            write!(f, "{}", char::from(b))?;
72        } else {
73            write!(f, "\\x{b:02x}")?;
74        }
75    }
76    Ok(())
77}
78
79fn hex<'b>(f: &mut fmt::Formatter<'_>, bytes: impl Iterator<Item = &'b u8>) -> fmt::Result {
80    for &b in bytes {
81        write!(f, "{b:02X}")?;
82    }
83    Ok(())
84}
85
86impl Value<'_> {
87    /// The value as an exact decimal `mantissa × 10^exponent`: integers and valid BCD
88    /// with exponent 0, and 32-bit reals converted exactly (every finite IEEE 754
89    /// single is a finite decimal; D-012). `None` for NaN, infinities, reals too large
90    /// or too small for an `i128` mantissa, and non-numeric values.
91    pub fn as_decimal(&self) -> Option<(i128, i8)> {
92        match *self {
93            Self::Real32(bits) => real32_exact(bits),
94            _ => self.as_integer().map(|m| (m, 0)),
95        }
96    }
97
98    /// The value as an integer, for binary integers and valid BCD.
99    pub const fn as_integer(&self) -> Option<i128> {
100        match *self {
101            Self::Int(v) | Self::Bcd(v) => Some(v as i128),
102            Self::UInt(v) => Some(v as i128),
103            _ => None,
104        }
105    }
106
107    pub(crate) const fn negate(self) -> Self {
108        match self {
109            Self::Bcd(v) => Self::Bcd(-v),
110            other => other,
111        }
112    }
113}
114
115/// The exact decimal value of an IEEE 754 single: `m × 2^e` is `m × 5^-e × 10^e`.
116fn real32_exact(bits: u32) -> Option<(i128, i8)> {
117    let negative = bits >> 31 != 0;
118    let biased = (bits >> 23) & 0xFF;
119    let fraction = bits & 0x007F_FFFF;
120    if biased == 0xFF {
121        return None; // infinity or NaN
122    }
123    let (mut m, mut e) = if biased == 0 {
124        (i128::from(fraction), -149i32)
125    } else {
126        (i128::from(fraction | 0x0080_0000), i32::try_from(biased).ok()? - 150)
127    };
128    if m == 0 {
129        return Some((0, 0));
130    }
131    while m % 2 == 0 {
132        m /= 2;
133        e += 1;
134    }
135    let (mantissa, exponent) = if e >= 0 {
136        (m.checked_mul(2i128.checked_pow(e.unsigned_abs())?)?, 0)
137    } else {
138        let k = e.unsigned_abs();
139        (m.checked_mul(5i128.checked_pow(k)?)?, i8::try_from(e).ok()?)
140    };
141    Some((if negative { -mantissa } else { mantissa }, exponent))
142}
143
144/// Little-endian two's complement of 1 to 8 bytes.
145pub(crate) fn le_signed(bytes: &[u8]) -> i64 {
146    let negative = bytes.last().is_some_and(|b| b & 0x80 != 0);
147    let start: u64 = if negative { u64::MAX } else { 0 };
148    let raw = bytes.iter().rev().fold(start, |acc, &b| (acc << 8) | u64::from(b));
149    i64::from_le_bytes(raw.to_le_bytes())
150}
151
152/// Data type M (LVAR, 2–10 bytes): a two's-complement count, then a header byte with
153/// the resolution (bits 6–5: 2 s, 1 s, 1/256 s, 1/32768 s) and the time offset (bits 4–0).
154/// Only the relative form (offset `10000b`) is decoded; the absolute form's epoch is not
155/// public, so it stays raw. The most negative count means invalid.
156pub(crate) fn type_m(bytes: &[u8]) -> Option<Quantity> {
157    let (&header, count) = bytes.split_last()?;
158    if header & 0x1F != 0x10 || count.is_empty() || count.len() > 8 {
159        return None;
160    }
161    let c = i128::from(le_signed(count));
162    let min = -(1i128 << (8 * count.len() - 1));
163    if c == min {
164        return None;
165    }
166    // 2 s, 1 s, 1/256 s = 390625 × 10^-8 s, 1/32768 s = 30517578125 × 10^-15 s: exact.
167    let (factor, exponent) = match (header >> 5) & 0x03 {
168        0 => (2, 0),
169        1 => (1, 0),
170        2 => (390_625, -8),
171        _ => (30_517_578_125, -15),
172    };
173    // A duration has no register resolution to keep: drop trailing zeros (still exact).
174    let (mut mantissa, mut exponent) = (c.checked_mul(factor)?, exponent);
175    while exponent < 0 && mantissa % 10 == 0 {
176        mantissa /= 10;
177        exponent += 1;
178    }
179    Some(Quantity { mantissa, exponent, unit: Some(Unit::Seconds) })
180}
181
182/// Little-endian unsigned integer of 1 to 8 bytes.
183pub(crate) fn le_unsigned(bytes: &[u8]) -> u64 {
184    bytes.iter().rev().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
185}
186
187/// Decode little-endian BCD. A most significant nibble of `F` marks a negative number
188/// (EN 13757-3); any other nibble above 9 makes the field invalid.
189pub(crate) fn bcd(bytes: &[u8]) -> Value<'_> {
190    let mut v: i64 = 0;
191    let mut negative = false;
192    for (i, &b) in bytes.iter().enumerate().rev() {
193        for (j, digit) in [b >> 4, b & 0x0F].into_iter().enumerate() {
194            let most_significant = i + 1 == bytes.len() && j == 0;
195            if digit > 9 {
196                if most_significant && digit == 0xF {
197                    negative = true;
198                    continue;
199                }
200                return Value::InvalidBcd(bytes);
201            }
202            v = v * 10 + i64::from(digit);
203        }
204    }
205    Value::Bcd(if negative { -v } else { v })
206}
207
208/// Four BCD bytes (LSB first) as a decimal number, e.g. an identification number.
209pub(crate) fn bcd_u32(bytes: [u8; 4]) -> Option<u32> {
210    match bcd(&bytes) {
211        Value::Bcd(v) => u32::try_from(v).ok(),
212        _ => None,
213    }
214}
215
216/// A unit of a quantity.
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
218#[non_exhaustive]
219pub enum Unit {
220    /// Watt-hour.
221    Wh,
222    /// Joule.
223    J,
224    /// Cubic metre.
225    M3,
226    /// Kilogram.
227    Kg,
228    /// Watt.
229    W,
230    /// Joule per hour.
231    JPerH,
232    /// Cubic metre per hour.
233    M3PerH,
234    /// Cubic metre per minute.
235    M3PerMin,
236    /// Cubic metre per second.
237    M3PerS,
238    /// Kilogram per hour.
239    KgPerH,
240    /// Degree Celsius.
241    Celsius,
242    /// Kelvin.
243    Kelvin,
244    /// Bar.
245    Bar,
246    /// Second.
247    Seconds,
248    /// Minute.
249    Minutes,
250    /// Hour.
251    Hours,
252    /// Day.
253    Days,
254    /// Month (calendar).
255    Months,
256    /// Year (calendar).
257    Years,
258    /// Volt.
259    Volt,
260    /// Ampere.
261    Ampere,
262    /// Hertz.
263    Hertz,
264    /// Percent (relative humidity).
265    Percent,
266    /// Degree Fahrenheit.
267    Fahrenheit,
268    /// Calorie.
269    Calorie,
270    /// Cubic foot.
271    CubicFeet,
272    /// US gallon.
273    UsGallon,
274    /// US gallon per minute.
275    UsGallonPerMin,
276    /// US gallon per hour.
277    UsGallonPerH,
278    /// Volt-ampere (apparent power).
279    VoltAmpere,
280    /// Volt-ampere reactive (reactive power).
281    Var,
282    /// Volt-ampere hour (apparent energy).
283    VaH,
284    /// Volt-ampere reactive hour (reactive energy).
285    VarH,
286    /// Degree of angle (phase).
287    Degree,
288    /// Decibel-milliwatt (signal level).
289    Dbm,
290    /// Units of the local legal currency.
291    Currency,
292    /// Baud.
293    Baud,
294    /// Bit times (response delay).
295    BitTimes,
296    /// Parts per million.
297    Ppm,
298    /// Parts per billion.
299    Ppb,
300    /// Microgram per cubic metre.
301    MicrogramPerM3,
302    /// Count per cubic metre.
303    PerM3,
304    /// Lux.
305    Lux,
306    /// Candela.
307    Candela,
308    /// Watt per square metre.
309    WattPerM2,
310    /// Metre per second.
311    MetrePerS,
312    /// A-weighted decibel.
313    Dba,
314    /// Formazin nephelometric unit (turbidity).
315    Fnu,
316    /// pH.
317    Ph,
318    /// Millimetre.
319    Millimetre,
320}
321
322impl Unit {
323    /// Seconds, minutes, hours or days from the low two bits of a code.
324    pub(crate) const fn duration(nn: u8) -> Self {
325        match nn & 0x03 {
326            0 => Self::Seconds,
327            1 => Self::Minutes,
328            2 => Self::Hours,
329            _ => Self::Days,
330        }
331    }
332
333    /// Hours, days, months or years from the low two bits (`FD 68`–`6F`).
334    pub(crate) const fn long_duration(pp: u8) -> Self {
335        match pp & 0x03 {
336            0 => Self::Hours,
337            1 => Self::Days,
338            2 => Self::Months,
339            _ => Self::Years,
340        }
341    }
342
343    /// The unit's symbol.
344    pub const fn symbol(self) -> &'static str {
345        match self {
346            Self::Wh => "Wh",
347            Self::J => "J",
348            Self::M3 => "m³",
349            Self::Kg => "kg",
350            Self::W => "W",
351            Self::JPerH => "J/h",
352            Self::M3PerH => "m³/h",
353            Self::M3PerMin => "m³/min",
354            Self::M3PerS => "m³/s",
355            Self::KgPerH => "kg/h",
356            Self::Celsius => "°C",
357            Self::Kelvin => "K",
358            Self::Bar => "bar",
359            Self::Seconds => "s",
360            Self::Minutes => "min",
361            Self::Hours => "h",
362            Self::Days => "d",
363            Self::Months => "months",
364            Self::Years => "years",
365            Self::Volt => "V",
366            Self::Ampere => "A",
367            Self::Hertz => "Hz",
368            Self::Percent => "%",
369            Self::Fahrenheit => "°F",
370            Self::Calorie => "cal",
371            Self::CubicFeet => "ft³",
372            Self::UsGallon => "US gal",
373            Self::UsGallonPerMin => "US gal/min",
374            Self::UsGallonPerH => "US gal/h",
375            Self::VoltAmpere => "VA",
376            Self::Var => "var",
377            Self::VaH => "VAh",
378            Self::VarH => "varh",
379            Self::Degree => "°",
380            Self::Dbm => "dBm",
381            Self::Currency => "currency units",
382            Self::Baud => "Bd",
383            Self::BitTimes => "bit times",
384            Self::Ppm => "ppm",
385            Self::Ppb => "ppb",
386            Self::MicrogramPerM3 => "µg/m³",
387            Self::PerM3 => "/m³",
388            Self::Lux => "lx",
389            Self::Candela => "cd",
390            Self::WattPerM2 => "W/m²",
391            Self::MetrePerS => "m/s",
392            Self::Dba => "dB(A)",
393            Self::Fnu => "FNU",
394            Self::Ph => "pH",
395            Self::Millimetre => "mm",
396        }
397    }
398}
399
400impl fmt::Display for Unit {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        f.write_str(self.symbol())
403    }
404}
405
406/// An exact measured quantity: `mantissa × 10^exponent` in `unit`. Never a float.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub struct Quantity {
409    /// The raw value from the meter.
410    pub mantissa: i128,
411    /// The decimal exponent from the VIF.
412    pub exponent: i8,
413    /// The unit.
414    pub unit: Option<Unit>,
415}
416
417impl Quantity {
418    /// The value in units of `10^exponent`. `None` if it would need rounding or does
419    /// not fit an `i128`.
420    pub fn to_scale(self, exponent: i8) -> Option<i128> {
421        let diff = i32::from(self.exponent) - i32::from(exponent);
422        let p = 10i128.checked_pow(diff.unsigned_abs())?;
423        if diff >= 0 {
424            self.mantissa.checked_mul(p)
425        } else {
426            // `p` is a power of ten and never zero; the checked forms keep the panic path out.
427            (self.mantissa.checked_rem(p)? == 0).then(|| self.mantissa.checked_div(p)).flatten()
428        }
429    }
430}
431
432impl Quantity {
433    /// Round to units of `10^exponent`, half to even: an explicit, visible rounding for
434    /// display or for a coarser register. Exact (no rounding) when `exponent` is not
435    /// coarser than the quantity's. `None` on overflow.
436    pub fn round(self, exponent: i8) -> Option<Self> {
437        if exponent <= self.exponent {
438            return Some(Self { mantissa: self.to_scale(exponent)?, exponent, unit: self.unit });
439        }
440        let diff = i32::from(exponent) - i32::from(self.exponent);
441        let p = 10i128.checked_pow(diff.unsigned_abs())?;
442        let q = self.mantissa.checked_div(p)?;
443        let r = self.mantissa.checked_rem(p)?;
444        let twice = r.unsigned_abs().checked_mul(2)?;
445        let half = p.unsigned_abs();
446        let away = twice > half || (twice == half && q % 2 != 0);
447        let mantissa = if away { q.checked_add(r.signum())? } else { q };
448        Some(Self { mantissa, exponent, unit: self.unit })
449    }
450
451    /// Rounded to at most `digits` significant digits (never more precise than it is).
452    pub fn significant(self, digits: u32) -> Option<Self> {
453        let len = self.mantissa.unsigned_abs().checked_ilog10().map_or(1, |l| l + 1);
454        if len <= digits {
455            return Some(self);
456        }
457        let shift = i8::try_from(len - digits).ok()?;
458        self.round(self.exponent.checked_add(shift)?)
459    }
460}
461
462impl Unit {
463    /// Units shown with an SI prefix (k, M, G, T) when large: energy and power.
464    const fn prefixable(self) -> bool {
465        matches!(
466            self,
467            Self::Wh
468                | Self::J
469                | Self::W
470                | Self::JPerH
471                | Self::VoltAmpere
472                | Self::Var
473                | Self::VaH
474                | Self::VarH
475                | Self::Calorie
476        )
477    }
478}
479
480impl fmt::Display for Quantity {
481    /// Exact decimal notation: `12.565 m³`. Energy and power of 1000 or more get an SI
482    /// prefix, still exact: `218.370 kWh`, `37.402 MWh`. The alternate form (`{:#}`)
483    /// keeps the base unit: `218370 Wh`.
484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485        if let Some(unit) = self.unit.filter(|u| u.prefixable() && !f.alternate() && self.mantissa != 0) {
486            let len = self.mantissa.unsigned_abs().checked_ilog10().unwrap_or(0);
487            let magnitude = i32::try_from(len).unwrap_or(0) + i32::from(self.exponent);
488            let k = (magnitude / 3).clamp(0, 4);
489            if k > 0 {
490                let prefix =
491                    ["", "k", "M", "G", "T"].get(usize::try_from(k).unwrap_or(0)).copied().unwrap_or("");
492                let shift = i8::try_from(3 * k).unwrap_or(0);
493                let scaled = Self {
494                    mantissa: self.mantissa,
495                    exponent: self.exponent.saturating_sub(shift),
496                    unit: None,
497                };
498                return write!(f, "{scaled} {prefix}{unit}");
499            }
500        }
501        let mut digits = [0u8; 40];
502        let mut n = self.mantissa.unsigned_abs();
503        let mut len = 0usize;
504        loop {
505            if let Some(slot) = digits.get_mut(len) {
506                *slot = b'0' + u8::try_from(n % 10).unwrap_or(0);
507            }
508            len += 1;
509            n /= 10;
510            if n == 0 || len >= digits.len() {
511                break;
512            }
513        }
514        let digits = digits.get(..len).unwrap_or(&[]);
515        if self.mantissa < 0 {
516            f.write_str("-")?;
517        }
518        let exp = i32::from(self.exponent);
519        let put = |f: &mut fmt::Formatter<'_>, d: &u8| write!(f, "{}", char::from(*d));
520        if self.mantissa == 0 && exp >= 0 {
521            f.write_str("0")?;
522        } else if exp >= 0 {
523            for d in digits.iter().rev() {
524                put(f, d)?;
525            }
526            for _ in 0..exp {
527                f.write_str("0")?;
528            }
529        } else {
530            let frac = exp.unsigned_abs() as usize;
531            if len <= frac {
532                f.write_str("0.")?;
533                for _ in len..frac {
534                    f.write_str("0")?;
535                }
536                for d in digits.iter().rev() {
537                    put(f, d)?;
538                }
539            } else {
540                for (i, d) in digits.iter().rev().enumerate() {
541                    if i == len - frac {
542                        f.write_str(".")?;
543                    }
544                    put(f, d)?;
545                }
546            }
547        }
548        if let Some(unit) = self.unit {
549            write!(f, " {unit}")?;
550        }
551        Ok(())
552    }
553}
554
555#[cfg(test)]
556mod tests {
557    extern crate std;
558    use super::*;
559    use std::string::ToString;
560
561    #[test]
562    fn bcd_decoding() {
563        assert_eq!(bcd(&[0x37, 0x18, 0x02]), Value::Bcd(21837));
564        assert_eq!(bcd(&[0x13, 0x01]), Value::Bcd(113));
565        assert_eq!(bcd(&[0x45, 0xF1]), Value::Bcd(-145));
566        assert_eq!(bcd(&[0x4A, 0x01]), Value::InvalidBcd(&[0x4A, 0x01]));
567        assert_eq!(bcd_u32([0x78, 0x56, 0x34, 0x12]), Some(12_345_678));
568    }
569
570    #[test]
571    fn little_endian_integers() {
572        assert_eq!(le_signed(&[0x15, 0x31, 0x00]), 12565);
573        assert_eq!(le_signed(&[0xFF, 0xFF]), -1);
574        assert_eq!(le_signed(&[0x00, 0x80]), -32768);
575    }
576
577    #[test]
578    fn reals_are_exact_decimals() {
579        // baylanheat (wmbusmeters): 0x46529447 = 13477.0693359375 exactly.
580        assert_eq!(real32_exact(0x4652_9447), Some((134_770_693_359_375, -10)));
581        assert_eq!(real32_exact(0x3F80_0000), Some((1, 0)));
582        assert_eq!(real32_exact(0xC000_0000), Some((-2, 0)));
583        assert_eq!(real32_exact(0x0000_0000), Some((0, 0)));
584        assert_eq!(real32_exact(0x7F80_0000), None); // infinity
585        assert_eq!(real32_exact(0x7FC0_0000), None); // NaN
586        assert_eq!(real32_exact(0x0000_0001), None); // 2^-149: mantissa too long
587        assert_eq!(real32_exact(0x7F7F_FFFF), None); // 3.4e38 does not fit i128
588    }
589
590    #[test]
591    fn type_m_relative_durations() {
592        // wmbusmeters test_type_m (EN 13757-3:2018 Table A.12 examples) and OMS N.13.
593        let d = |b: &[u8]| type_m(b).map(|q| q.to_string());
594        assert_eq!(d(&[0x03, 0x30]).as_deref(), Some("3 s"));
595        assert_eq!(d(&[0x80, 0xDD, 0x50]).as_deref(), Some("-34.5 s"));
596        assert_eq!(d(&[0x0A, 0x10]).as_deref(), Some("20 s"));
597        assert_eq!(d(&[0x00, 0x40, 0x70]).as_deref(), Some("0.5 s"));
598        assert_eq!(d(&[0x03, 0xB0]).as_deref(), Some("3 s"));
599        assert_eq!(d(&[0x81, 0x30]).as_deref(), Some("-127 s"));
600        assert_eq!(d(&[0x80, 0x30]), None, "most negative count: invalid");
601        assert_eq!(d(&[0x0B, 0x60, 0x01, 0x00, 0x21]), None, "absolute form stays raw");
602    }
603
604    #[test]
605    fn rounding_is_explicit_and_half_even() {
606        let q = |m, e| Quantity { mantissa: m, exponent: e, unit: None };
607        assert_eq!(q(218_370, 0).round(3), Some(q(218, 3)));
608        assert_eq!(q(2_185, 0).round(1), Some(q(218, 1)));
609        assert_eq!(q(2_175, 0).round(1), Some(q(218, 1)));
610        assert_eq!(q(-2_185, 0).round(1), Some(q(-218, 1)));
611        assert_eq!(q(12, 0).round(-2), Some(q(1200, -2)));
612        assert_eq!(q(134_770_693_359_375, -10).significant(9).unwrap().to_string(), "13477.0693");
613    }
614
615    #[test]
616    fn exact_display() {
617        let q = |m, e| Quantity { mantissa: m, exponent: e, unit: Some(Unit::M3) }.to_string();
618        assert_eq!(q(12565, -3), "12.565 m³");
619        assert_eq!(q(21837, 1), "218370 m³");
620        assert_eq!(q(5, -3), "0.005 m³");
621        assert_eq!(q(0, 3), "0 m³");
622        assert_eq!(q(0, -2), "0.00 m³");
623        let e = |m, e| Quantity { mantissa: m, exponent: e, unit: Some(Unit::Wh) };
624        assert_eq!(e(218_370, 0).to_string(), "218.370 kWh");
625        assert_eq!(std::format!("{:#}", e(218_370, 0)), "218370 Wh");
626        assert_eq!(e(37_402, 3).to_string(), "37.402 MWh");
627        assert_eq!(e(999, 0).to_string(), "999 Wh");
628        assert_eq!(e(-1_364, 0).to_string(), "-1.364 kWh");
629        assert_eq!(e(0, 3).to_string(), "0 Wh");
630    }
631}