flexibility 0.1.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Exact units with one sign convention: positive is consumption, negative is feed-in.
//!
//! [`Power`] is absolute, [`Deviation`] is relative to a baseline, [`Energy`] is whole
//! watt-seconds. Text in and out is exact: `4.2 kW` is 4 200 W, and a value that is not whole
//! watts is refused, never rounded.

use std::fmt;
use std::str::FromStr;

use crate::{Error, IspDuration};

/// An exact amount of power in whole watts.
///
/// **Positive is consumption, negative is feed-in**, as in UFTP 3.1 § 4.2.1: *"A positive value
/// indicates that power flows towards the prosumer (consumption), a negative value indicates
/// flow towards the grid (production)."* Build values with [`kw!`](crate::kw),
/// [`Power::consumption`] or [`Power::feed_in`] rather than negating by hand.
///
/// Arithmetic is checked: an overflow is an [`Error::Overflow`], never a wrap.
///
/// ```
/// use flexibility::{kw, Power};
/// assert_eq!(kw!(4.2), Power::from_watts(4_200));
/// assert_eq!(kw!(4.2).to_string(), "4.2 kW");
/// assert_eq!("-3 kW".parse::<Power>()?, Power::from_watts(-3_000));
/// # Ok::<(), flexibility::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Power(i64);

/// Power relative to a baseline, consumption positive: −3 kW is "3 kW less consumption, or
/// 3 kW more feed-in, than the baseline".
///
/// A deviation is not a power. The only crossings name the baseline:
/// [`Power::deviation_from`] and [`Power::checked_add_deviation`].
///
/// ```
/// use flexibility::{kw, Deviation};
/// let measured = kw!(4.1);
/// let baseline = kw!(7.4);
/// let d = measured.deviation_from(baseline)?;
/// assert_eq!(d.to_string(), "-3.3 kW");
/// assert_eq!(baseline.checked_add_deviation(d)?, measured);
/// # Ok::<(), flexibility::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Deviation(i64);

/// An exact amount of energy in whole watt-seconds, consumption positive.
///
/// An ISP is whole minutes and power is whole watts, so power × ISP is always exact: 1 W for
/// 15 minutes is 900 Ws, displayed as `0.25 Wh`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Energy(i64);

/// Which way power flows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
    /// Drawn from the grid.
    Consumption,
    /// Fed into the grid.
    FeedIn,
    /// Neither.
    Zero,
}

/// How a division may round. Every division in the crate names one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rounding {
    /// No rounding: a remainder is [`Error::Inexact`].
    Exact,
    /// To the nearest whole unit, halves away from zero (kaufmännisch).
    HalfAwayFromZero,
    /// Toward zero: never more than the exact value's magnitude. For a cap read from a coarse
    /// encoding (an IEC 104 normalized set point), the stricter side.
    TowardZero,
}

const fn direction_of(value: i64) -> Direction {
    match value {
        0 => Direction::Zero,
        v if v > 0 => Direction::Consumption,
        _ => Direction::FeedIn,
    }
}

fn overflow(
    quantity: &'static str,
    operation: &'static str,
    left: i64,
    right: Option<i64>,
) -> Error {
    Error::Overflow {
        quantity,
        operation,
        left: i128::from(left),
        right: right.map(i128::from),
    }
}

impl Power {
    /// No power.
    pub const ZERO: Power = Power(0);

    /// Power from signed watts, consumption positive.
    #[must_use]
    pub const fn from_watts(watts: i64) -> Power {
        Power(watts)
    }

    /// A consumption of `watts`.
    ///
    /// # Errors
    /// [`Error::PowerOutOfRange`] above `i64::MAX` watts.
    pub fn consumption(watts: u64) -> Result<Power, Error> {
        i64::try_from(watts)
            .map(Power)
            .map_err(|_| Error::PowerOutOfRange { watts })
    }

    /// A feed-in of `watts`, stored as negative power.
    ///
    /// # Errors
    /// [`Error::PowerOutOfRange`] above `i64::MAX` watts.
    pub fn feed_in(watts: u64) -> Result<Power, Error> {
        Self::consumption(watts).map(|p| Power(-p.0))
    }

    /// Signed watts, consumption positive.
    #[must_use]
    pub const fn watts(self) -> i64 {
        self.0
    }

    /// Which way the power flows.
    #[must_use]
    pub const fn direction(self) -> Direction {
        direction_of(self.0)
    }

    /// The amount without its sign, in watts.
    #[must_use]
    pub const fn magnitude(self) -> u64 {
        self.0.unsigned_abs()
    }

    /// `self + rhs`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_add(self, rhs: Power) -> Result<Power, Error> {
        self.0
            .checked_add(rhs.0)
            .map(Power)
            .ok_or_else(|| overflow("power", "+", self.0, Some(rhs.0)))
    }

    /// `self - rhs`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_sub(self, rhs: Power) -> Result<Power, Error> {
        self.0
            .checked_sub(rhs.0)
            .map(Power)
            .ok_or_else(|| overflow("power", "-", self.0, Some(rhs.0)))
    }

    /// `-self`: the same amount in the other direction.
    ///
    /// # Errors
    /// [`Error::Overflow`] for the most negative value, which has no positive counterpart.
    pub fn checked_neg(self) -> Result<Power, Error> {
        self.0
            .checked_neg()
            .map(Power)
            .ok_or_else(|| overflow("power", "negate", self.0, None))
    }

    /// How far `self` lies from `baseline`: `self − baseline`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn deviation_from(self, baseline: Power) -> Result<Deviation, Error> {
        self.0
            .checked_sub(baseline.0)
            .map(Deviation)
            .ok_or_else(|| overflow("deviation", "-", self.0, Some(baseline.0)))
    }

    /// `self` moved by `deviation`; `self` is the baseline the deviation is relative to.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_add_deviation(self, deviation: Deviation) -> Result<Power, Error> {
        self.0
            .checked_add(deviation.0)
            .map(Power)
            .ok_or_else(|| overflow("power", "+", self.0, Some(deviation.0)))
    }

    /// The energy of this power held for one ISP: exact, in watt-seconds.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn energy(self, isp: IspDuration) -> Result<Energy, Error> {
        let seconds = i64::from(isp.minutes()) * 60;
        self.0
            .checked_mul(seconds)
            .map(Energy)
            .ok_or_else(|| overflow("energy", "×", self.0, Some(seconds)))
    }

    /// The average power of `energy` over one ISP, rounded as named.
    ///
    /// ```
    /// use flexibility::{Energy, IspDuration, Power, Rounding};
    /// let wh = Energy::from_wh(1)?; // 1 Wh in a quarter hour is 4 W, exactly
    /// assert_eq!(Power::average(wh, IspDuration::FIFTEEN_MINUTES, Rounding::Exact)?, Power::from_watts(4));
    /// let ws = Energy::from_watt_seconds(1);
    /// assert!(Power::average(ws, IspDuration::FIFTEEN_MINUTES, Rounding::Exact).is_err());
    /// # Ok::<(), flexibility::Error>(())
    /// ```
    ///
    /// # Errors
    /// [`Error::Inexact`] for [`Rounding::Exact`] and a remainder; [`Error::Overflow`] never in
    /// practice, since an average is smaller than the energy.
    pub fn average(energy: Energy, isp: IspDuration, rounding: Rounding) -> Result<Power, Error> {
        let seconds = i128::from(isp.minutes()) * 60;
        let watts = div_round(i128::from(energy.0), seconds, rounding)?;
        i64::try_from(watts)
            .map(Power)
            .map_err(|_| overflow("power", "÷", energy.0, Some(isp.minutes().into())))
    }
}

impl Deviation {
    /// No deviation.
    pub const ZERO: Deviation = Deviation(0);

    /// A deviation of signed watts, consumption positive.
    #[must_use]
    pub const fn from_watts(watts: i64) -> Deviation {
        Deviation(watts)
    }

    /// Signed watts, consumption positive.
    #[must_use]
    pub const fn watts(self) -> i64 {
        self.0
    }

    /// The direction the deviation moves power.
    #[must_use]
    pub const fn direction(self) -> Direction {
        direction_of(self.0)
    }

    /// The amount without its sign, in watts.
    #[must_use]
    pub const fn magnitude(self) -> u64 {
        self.0.unsigned_abs()
    }

    /// `self + rhs`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_add(self, rhs: Deviation) -> Result<Deviation, Error> {
        self.0
            .checked_add(rhs.0)
            .map(Deviation)
            .ok_or_else(|| overflow("deviation", "+", self.0, Some(rhs.0)))
    }

    /// `self - rhs`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_sub(self, rhs: Deviation) -> Result<Deviation, Error> {
        self.0
            .checked_sub(rhs.0)
            .map(Deviation)
            .ok_or_else(|| overflow("deviation", "-", self.0, Some(rhs.0)))
    }

    /// `-self`.
    ///
    /// # Errors
    /// [`Error::Overflow`] for the most negative value.
    pub fn checked_neg(self) -> Result<Deviation, Error> {
        self.0
            .checked_neg()
            .map(Deviation)
            .ok_or_else(|| overflow("deviation", "negate", self.0, None))
    }
}

impl Energy {
    /// No energy.
    pub const ZERO: Energy = Energy(0);

    /// Energy of signed watt-seconds, consumption positive.
    #[must_use]
    pub const fn from_watt_seconds(watt_seconds: i64) -> Energy {
        Energy(watt_seconds)
    }

    /// Energy of signed watt-hours.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn from_wh(wh: i64) -> Result<Energy, Error> {
        wh.checked_mul(3_600)
            .map(Energy)
            .ok_or_else(|| overflow("energy", "×", wh, Some(3_600)))
    }

    /// Signed watt-seconds, consumption positive.
    #[must_use]
    pub const fn watt_seconds(self) -> i64 {
        self.0
    }

    /// `self + rhs`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_add(self, rhs: Energy) -> Result<Energy, Error> {
        self.0
            .checked_add(rhs.0)
            .map(Energy)
            .ok_or_else(|| overflow("energy", "+", self.0, Some(rhs.0)))
    }

    /// `self - rhs`.
    ///
    /// # Errors
    /// [`Error::Overflow`] outside the representable range.
    pub fn checked_sub(self, rhs: Energy) -> Result<Energy, Error> {
        self.0
            .checked_sub(rhs.0)
            .map(Energy)
            .ok_or_else(|| overflow("energy", "-", self.0, Some(rhs.0)))
    }

    pub(crate) fn from_sum(sum: i128) -> Result<Energy, Error> {
        i64::try_from(sum).map(Energy).map_err(|_| Error::Overflow {
            quantity: "energy",
            operation: "sum",
            left: sum,
            right: None,
        })
    }
}

/// `n / d` for `d > 0`, rounded as named.
pub(crate) fn div_round(n: i128, d: i128, rounding: Rounding) -> Result<i128, Error> {
    debug_assert!(d > 0);
    let q = n / d;
    let r = n % d;
    match rounding {
        Rounding::Exact if r != 0 => Err(Error::Inexact {
            numerator: n,
            denominator: d,
        }),
        Rounding::Exact | Rounding::TowardZero => Ok(q),
        Rounding::HalfAwayFromZero => {
            // |r| < d, so 2|r| cannot overflow i128 for the inputs this crate builds.
            if r.unsigned_abs().saturating_mul(2) >= d.unsigned_abs() {
                Ok(q + n.signum())
            } else {
                Ok(q)
            }
        }
    }
}

// --- Text ------------------------------------------------------------------------------------

/// The longest power text [`Power::from_str`] reads.
const MAX_TEXT: usize = 64;

/// Why a power text was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[doc(hidden)]
pub enum TextFault {
    TooLong,
    Malformed,
    Unit,
    NotWholeWatts,
    OutOfRange,
}

impl TextFault {
    const fn reason(self) -> &'static str {
        match self {
            TextFault::TooLong => "longer than 64 bytes",
            TextFault::Malformed => "not a number with a unit, such as 4.2 kW",
            TextFault::Unit => "the unit is not W, kW or MW",
            TextFault::NotWholeWatts => "not a whole number of watts",
            TextFault::OutOfRange => "outside the representable range",
        }
    }
}

const fn pow10(exp: u32) -> i128 {
    let mut v = 1i128;
    let mut i = 0;
    while i < exp {
        v *= 10;
        i += 1;
    }
    v
}

/// Parses `[sign] digits [. digits]` from `b[start..end]` scaled by `10^scale`, exactly.
/// `literal` allows `_` between digits and spaces after the sign, as `stringify!` writes them.
const fn parse_number(
    b: &[u8],
    start: usize,
    end: usize,
    scale: u32,
    signs: bool,
    literal: bool,
) -> Result<i128, TextFault> {
    let mut i = start;
    let mut negative = false;
    if i < end && (b[i] == b'-' || (b[i] == b'+' && signs)) {
        negative = b[i] == b'-';
        i += 1;
        while literal && i < end && b[i] == b' ' {
            i += 1;
        }
    }
    let mut value: i128 = 0;
    let mut digits = 0u32;
    let mut fraction: Option<u32> = None;
    let mut trailing = false;
    while i < end {
        let c = b[i];
        if c.is_ascii_digit() {
            if let Some(f) = fraction {
                if f == scale {
                    // Digits past the watt are allowed only as trailing zeros (`5.0 W`).
                    if c != b'0' {
                        return Err(TextFault::NotWholeWatts);
                    }
                    trailing = true;
                    i += 1;
                    continue;
                }
                fraction = Some(f + 1);
            }
            value = match value.checked_mul(10) {
                Some(v) => match v.checked_add((c - b'0') as i128) {
                    Some(v) => v,
                    None => return Err(TextFault::OutOfRange),
                },
                None => return Err(TextFault::OutOfRange),
            };
            digits += 1;
        } else if c == b'.' && fraction.is_none() && digits > 0 {
            fraction = Some(0);
        } else if c == b'_' && literal && digits > 0 {
            // a digit separator in a literal
        } else {
            return Err(TextFault::Malformed);
        }
        i += 1;
    }
    if digits == 0 || (matches!(fraction, Some(0)) && !trailing) {
        return Err(TextFault::Malformed);
    }
    let used = match fraction {
        Some(f) => f,
        None => 0,
    };
    // At most 64 bytes, so the scaled value fits i128 or the multiplication says so.
    value = match value.checked_mul(pow10(scale - used)) {
        Some(v) => v,
        None => return Err(TextFault::OutOfRange),
    };
    Ok(if negative { -value } else { value })
}

/// Parses `number [space] unit` with unit `W`, `kW` or `MW`.
const fn parse_with_unit(text: &str, signs: bool) -> Result<i64, TextFault> {
    let b = text.as_bytes();
    if b.len() > MAX_TEXT {
        return Err(TextFault::TooLong);
    }
    let (scale, unit_len) = if b.len() >= 2 && b[b.len() - 2] == b'k' && b[b.len() - 1] == b'W' {
        (3, 2)
    } else if b.len() >= 2 && b[b.len() - 2] == b'M' && b[b.len() - 1] == b'W' {
        (6, 2)
    } else if !b.is_empty() && b[b.len() - 1] == b'W' {
        (0, 1)
    } else {
        return Err(TextFault::Unit);
    };
    let mut end = b.len() - unit_len;
    if end > 0 && b[end - 1] == b' ' {
        end -= 1;
    }
    match parse_number(b, 0, end, scale, signs, false) {
        Ok(v) => narrow(v),
        Err(e) => Err(e),
    }
}

const fn narrow(v: i128) -> Result<i64, TextFault> {
    if v > i64::MAX as i128 || v < i64::MIN as i128 {
        Err(TextFault::OutOfRange)
    } else {
        #[allow(clippy::cast_possible_truncation)] // range checked above
        let w = v as i64;
        Ok(w)
    }
}

/// Used by [`w!`](crate::w), [`kw!`](crate::kw) and [`mw!`](crate::mw): the literal's text
/// scaled by `10^scale`, exactly. Not part of the stable API.
#[doc(hidden)]
#[must_use]
pub const fn __literal(text: &str, scale: u32) -> Option<Power> {
    let b = text.as_bytes();
    match parse_number(b, 0, b.len(), scale, false, true) {
        Ok(v) => match narrow(v) {
            Ok(w) => Some(Power(w)),
            Err(_) => None,
        },
        Err(_) => None,
    }
}

/// Used by [`wh!`](crate::wh), [`kwh!`](crate::kwh) and [`mwh!`](crate::mwh): the literal's
/// text in whole watt-hours (scaled by `10^scale`), as watt-seconds. Not part of the stable API.
#[doc(hidden)]
#[must_use]
pub const fn __energy_literal(text: &str, scale: u32) -> Option<Energy> {
    match __literal(text, scale) {
        Some(Power(wh)) => match wh.checked_mul(3_600) {
            Some(ws) => Some(Energy(ws)),
            None => None,
        },
        None => None,
    }
}

fn parse_error(text: &str, fault: TextFault) -> Error {
    let shown = if fault == TextFault::TooLong {
        format!("{} bytes", text.len())
    } else {
        text.to_owned()
    };
    Error::ParsePower {
        text: shown,
        reason: fault.reason(),
    }
}

impl FromStr for Power {
    type Err = Error;

    /// Parses `4.2 kW`, `-3 kW`, `500 W`, `1.5 MW` (a space before the unit is optional).
    fn from_str(text: &str) -> Result<Power, Error> {
        parse_with_unit(text, false)
            .map(Power)
            .map_err(|f| parse_error(text, f))
    }
}

impl FromStr for Deviation {
    type Err = Error;

    /// Parses `+2.2 kW`, `-3.3 kW`, `0 W`.
    fn from_str(text: &str) -> Result<Deviation, Error> {
        parse_with_unit(text, true)
            .map(Deviation)
            .map_err(|f| parse_error(text, f))
    }
}

/// Writes `magnitude / 10^scale` exactly, trailing fractional zeros dropped.
fn write_scaled(f: &mut fmt::Formatter<'_>, magnitude: u128, scale: u32) -> fmt::Result {
    let divisor = 10u128.pow(scale);
    let whole = magnitude / divisor;
    let frac = magnitude % divisor;
    write!(f, "{whole}")?;
    if frac != 0 {
        let width = scale as usize;
        let digits = format!("{frac:0width$}");
        write!(f, ".{}", digits.trim_end_matches('0'))?;
    }
    Ok(())
}

fn write_power(f: &mut fmt::Formatter<'_>, watts: i64, plus: bool) -> fmt::Result {
    if f.alternate() {
        return if plus && watts > 0 {
            write!(f, "+{watts} W")
        } else {
            write!(f, "{watts} W")
        };
    }
    if watts < 0 {
        f.write_str("-")?;
    } else if plus && watts > 0 {
        f.write_str("+")?;
    }
    let m = u128::from(watts.unsigned_abs());
    let (scale, unit) = match m {
        0..1_000 => (0, "W"),
        1_000..1_000_000 => (3, "kW"),
        _ => (6, "MW"),
    };
    write_scaled(f, m, scale)?;
    write!(f, " {unit}")
}

impl fmt::Display for Power {
    /// `4.2 kW`, `-3 kW`, `500 W`, `1.5 MW`; `{:#}` gives whole watts, `4200 W`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_power(f, self.0, false)
    }
}

impl fmt::Display for Deviation {
    /// `+2.2 kW`, `-3.3 kW`, `0 W`: always signed, so a deviation never reads as a power.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_power(f, self.0, true)
    }
}

impl fmt::Display for Energy {
    /// In Wh, kWh or MWh when exact within six decimals, otherwise whole `Ws`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let m = u128::from(self.0.unsigned_abs());
        let sign = if self.0 < 0 { "-" } else { "" };
        let (divisor, unit): (u128, &str) = match m {
            0..3_600_000 => (3_600, "Wh"),
            3_600_000..3_600_000_000 => (3_600_000, "kWh"),
            _ => (3_600_000_000, "MWh"),
        };
        for scale in 0..=6u32 {
            let scaled = m * 10u128.pow(scale);
            if scaled % divisor == 0 {
                f.write_str(sign)?;
                write_scaled(f, scaled / divisor, scale)?;
                return write!(f, " {unit}");
            }
        }
        write!(f, "{} Ws", self.0)
    }
}