metering 0.25.0

German energy metering quantities: DST-correct Europe/Berlin and 06:00-Gastag calendar arithmetic, exact decimal values, and the market's own code lists. Zero I/O, no async, no clock.
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
//! One value, one string — the property that makes a persisted key trustworthy.
//!
//! Every type here has a `Display` form that a consumer will end up storing:
//! in a database column, a merge key, a filename, a Kafka message key. The
//! moment one value has two spellings, two rows that mean the same thing stop
//! comparing equal, and nothing anywhere reports an error — a correction simply
//! fails to supersede the reading it corrects, and the total is overstated.
//!
//! `ObisCode` had exactly that bug: `FromStr` defaulted the storage group to 255
//! and `Display` always printed it, so `"1-0:1.8.0"` — the spelling MSCONS
//! carries and people type — came back out as `"1-0:1.8.0*255"`.
//!
//! The invariants below are what "canonical" has to mean:
//!
//! 1. **Stability** — `s.parse()?.to_string() == s` for every canonical `s`.
//! 2. **Totality** — `v.to_string().parse()? == v` for every value `v`.
//! 3. **Idempotence** — normalising twice equals normalising once, so every
//!    accepted spelling converges on one string.
//! 4. **Injectivity** — different values never render to the same string.
//!
//! Parsing is deliberately lenient and `Display` deliberately is not. That is
//! what makes 1–4 co-exist: a lenient parser accepting *n* spellings and a
//! canonical writer emitting one is a normalisation, and normalisations compose.

use metering::{ObisCode, Resolution};
use proptest::prelude::*;

// ── ObisCode ─────────────────────────────────────────────────────────────────

prop_compose! {
    fn arb_obis()(
        a in 0u8..=255, b in 0u8..=255, c in 0u8..=255,
        d in 0u8..=255, e in 0u8..=255, f in 0u8..=255,
    ) -> ObisCode {
        ObisCode { a, b, c, d, e, f }
    }
}

proptest! {
    /// Totality: whatever a code renders as, it reads back as itself — through
    /// the canonical form and the explicit one alike.
    #[test]
    fn obis_display_round_trips(code in arb_obis()) {
        prop_assert_eq!(code.to_string().parse::<ObisCode>(), Ok(code));
        prop_assert_eq!(format!("{code:#}").parse::<ObisCode>(), Ok(code));
    }

    /// Stability: the canonical form is a fixed point of parse-then-render.
    #[test]
    fn obis_canonical_form_is_stable(code in arb_obis()) {
        let canonical = code.to_string();
        prop_assert_eq!(canonical.parse::<ObisCode>().map(|c| c.to_string()), Ok(canonical.clone()));
    }

    /// Idempotence: both spellings converge, so a row written through either
    /// path lands on one key.
    #[test]
    fn obis_both_spellings_normalise_alike(code in arb_obis()) {
        let canonical = code.to_string();
        prop_assert_eq!(format!("{code:#}").parse::<ObisCode>().map(|c| c.to_string()), Ok(canonical));
    }

    /// Injectivity: two codes share a string only if they are the same code.
    /// Without this, eliding `*F` would merge distinct billing-period registers.
    #[test]
    fn obis_strings_are_injective(x in arb_obis(), y in arb_obis()) {
        prop_assert_eq!(x == y, x.to_string() == y.to_string());
    }

    /// `MAX_LEN` must actually bound the rendered length, in both spellings —
    /// it is what a consumer sizes a `VARCHAR` column from, and the `Display`
    /// impl writes through a stack buffer of exactly that size.
    #[test]
    fn max_len_bounds_every_rendering(code in arb_obis()) {
        prop_assert!(code.to_string().len() <= ObisCode::MAX_LEN);
        let full = format!("{code:#}");
        prop_assert!(full.len() <= ObisCode::MAX_LEN);
        prop_assert!(code.to_string().is_ascii());
    }

    /// Width, fill and alignment reach the output. A `Display` impl that writes
    /// straight to the formatter silently ignores them and misaligns tables.
    #[test]
    fn display_honours_width_and_alignment(code in arb_obis()) {
        let plain = code.to_string();
        let width = ObisCode::MAX_LEN + 2;
        let right = format!("{code:>width$}");
        prop_assert_eq!(right.len(), width);
        prop_assert!(right.ends_with(&plain));
        prop_assert_eq!(format!("{code:-<width$}").len(), width);
        // ...and no width still means no padding.
        prop_assert_eq!(format!("{code}"), plain);
    }

    /// Leading zeros and padding are accepted, and normalise away.
    #[test]
    fn obis_tolerates_padding_and_leading_zeros(code in arb_obis()) {
        let padded = format!(
            "  {:03}-{:03}:{:03}.{:03}.{:03}*{:03}  ",
            code.a, code.b, code.c, code.d, code.e, code.f
        );
        prop_assert_eq!(padded.parse::<ObisCode>(), Ok(code));
        prop_assert_eq!(padded.parse::<ObisCode>().map(|c| c.to_string()), Ok(code.to_string()));
    }
}

/// The reported failure, end to end: a reading written through one path and a
/// correction written through the other must share a merge key.
#[test]
fn obis_correction_supersedes_the_reading_it_corrects() {
    let reading_key = "1-0:1.8.0".parse::<ObisCode>().unwrap().to_string(); // raw SQL / MSCONS
    let correction_key = ObisCode::STROM_BEZUG_TOTAL.to_string(); // via the crate

    assert_eq!(
        reading_key, correction_key,
        "one channel must produce one merge key, whichever path wrote it"
    );
}

// ── Resolution ───────────────────────────────────────────────────────

fn arb_resolution() -> impl Strategy<Value = Resolution> {
    prop_oneof![
        Just(Resolution::QUARTER_HOUR),
        Just(Resolution::HALF_HOUR),
        Just(Resolution::Hour),
        Just(Resolution::Day),
        Just(Resolution::Month),
        Just(Resolution::Year),
        prop::sample::select(vec![1u8, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30])
            .prop_map(|m| Resolution::minutes(m).unwrap()),
    ]
}

proptest! {
    #[test]
    fn resolution_display_round_trips(r in arb_resolution()) {
        prop_assert_eq!(r.to_string().parse::<Resolution>(), Ok(r));
    }

    /// No string outside the closed set parses, and none panics — ASCII or
    /// not.
    #[test]
    fn resolution_parse_never_panics(s in "\\PC{0,12}") {
        let _ = s.parse::<Resolution>();
    }

    #[test]
    fn resolution_strings_are_injective(x in arb_resolution(), y in arb_resolution()) {
        prop_assert_eq!(x == y, x.to_string() == y.to_string());
    }

    /// One duration, one value: the set is closed, so no two resolutions share
    /// a fixed length.
    #[test]
    fn one_fixed_length_is_one_value(x in arb_resolution(), y in arb_resolution()) {
        if let (Some(a), Some(b)) = (x.fixed_seconds(), y.fixed_seconds()) {
            prop_assert_eq!(a == b, x == y);
        }
    }

    /// `from_seconds` answers exactly for the closed set and nothing else.
    #[test]
    fn from_seconds_is_the_normal_form(secs in 1u32..1_000_000) {
        match Resolution::from_seconds(secs) {
            Some(r) => {
                prop_assert_eq!(r.fixed_seconds(), Some(secs));
                prop_assert_eq!(r.to_string().parse::<Resolution>(), Ok(r));
            }
            None => prop_assert!(secs % 60 != 0 || secs > 3600 || 3600 % secs != 0),
        }
    }
}

// ── LoadProfile and the lifecycle codes ──────────────────────────────────────

/// Every closed-vocabulary enum with a `Display` form obeys the same four
/// invariants, so they are checked in one place rather than per module.
#[test]
fn closed_vocabularies_round_trip_and_stay_injective() {
    use metering::slp::strom::LoadProfile;
    use std::collections::BTreeSet;

    macro_rules! check {
        ($ty:ty) => {{
            let all = <$ty>::ALL;
            assert_eq!(all.len(), <$ty>::CODES.len(), stringify!($ty));
            let mut seen = BTreeSet::new();
            for (v, code) in all.iter().zip(<$ty>::CODES) {
                assert_eq!(v.as_str(), *code, "{v:?}");
                assert_eq!(&v.to_string(), *code, "{v:?}");
                assert_eq!(&v.to_string().parse::<$ty>().unwrap(), v, "{v:?}");
                // Lenient in, canonical out — as everywhere in this crate.
                assert_eq!(
                    &format!("  {}  ", code.to_lowercase())
                        .parse::<$ty>()
                        .unwrap(),
                    v,
                    "{v:?}"
                );
                assert!(seen.insert(*code), "duplicate code {code}");
            }
            assert!("NOT_A_CODE".parse::<$ty>().is_err(), stringify!($ty));
        }};
    }

    check!(LoadProfile);
}

// ── MaloId / MeloId ──────────────────────────────────────────────────────────

mod market_ids {
    use metering::{MaloId, MeloId};
    use proptest::prelude::*;

    /// A structurally valid MaLo-ID: leading digit 1–9, nine free digits, and
    /// the check digit the Bildungsvorschrift derives from them.
    pub fn arb_malo() -> impl Strategy<Value = MaloId> {
        ("[1-9][0-9]{9}").prop_map(|body| {
            let check = MaloId::compute_check_digit(&body).expect("ten digits");
            format!("{body}{check}").parse().expect("constructed valid")
        })
    }

    proptest! {
        /// Stability + totality: eleven digits out, the same value back.
        #[test]
        fn malo_display_round_trips(id in arb_malo()) {
            let s = id.to_string();
            prop_assert_eq!(s.len(), MaloId::LEN);
            prop_assert_eq!(s.parse::<MaloId>(), Ok(id));
        }

        /// Injectivity is trivial here — the string *is* the value — but the
        /// check digit adds a stronger property: a single-digit corruption of
        /// the first ten digits is rejected, **except** the scheme's one blind
        /// spot — a ±5 change in an even position, which doubles to a shift of
        /// exactly 10 and so leaves the check digit unchanged. The exception
        /// is asserted explicitly below rather than glossed over.
        #[test]
        fn malo_single_digit_corruption_is_caught(id in arb_malo(), pos in 0usize..10, bump in 1u8..10) {
            let mut bytes = id.to_string().into_bytes();
            bytes[pos] = b'0' + ((bytes[pos] - b'0') + bump) % 10;
            let corrupted = String::from_utf8(bytes).unwrap();
            // 1-based even positions are the doubled group: a bump of 5 there
            // shifts the total by 10 and is undetectable by construction.
            let blind_spot = pos % 2 == 1 && bump == 5;
            if blind_spot {
                prop_assert!(corrupted.parse::<MaloId>().is_ok(), "{}", corrupted);
            } else {
                // Corrupting the leading digit to 0 fails on structure;
                // everything else fails on the check digit.
                prop_assert!(corrupted.parse::<MaloId>().is_err(), "{}", corrupted);
            }
        }

        /// A well-shaped MeLo round-trips, and lowercase input converges on
        /// the uppercase spelling.
        #[test]
        fn melo_round_trips_and_uppercases(tail in "[A-Z0-9]{25}") {
            let canonical = format!("DE000562{tail}");
            let id: MeloId = canonical.parse().unwrap();
            prop_assert_eq!(id.as_str(), canonical.as_str());
            let relaxed: MeloId = canonical.to_lowercase().parse().unwrap();
            prop_assert_eq!(relaxed, id);
        }
    }
}

// ── Eic ──────────────────────────────────────────────────────────────────────

mod eic {
    use metering::ids::{Eic, EicType};
    use proptest::prelude::*;

    /// Every character an EIC may carry, in value order.
    const ALPHABET: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-";

    /// A structurally valid EIC: two digits of issuing office, a real object
    /// type letter, twelve permitted characters, and the check character the
    /// scheme derives from them.
    ///
    /// One body in thirty-seven computes to the minus sign, which §5.2 forbids
    /// as a check character; for those the last body character is walked
    /// through the alphabet until one does have a code. That always
    /// terminates: it carries weight 2, and 2 is invertible modulo the
    /// scheme's prime 37, so the thirty-seven candidates cover every residue.
    pub fn arb_eic() -> impl Strategy<Value = Eic> {
        ("[0-9]{2}", 0usize..EicType::ALL.len(), "[0-9A-Z-]{12}").prop_map(
            |(office, type_index, body)| {
                let letter = EicType::ALL[type_index].as_str();
                let head = format!("{office}{letter}{body}");
                ALPHABET
                    .iter()
                    .find_map(|c| {
                        let mut bytes = head.clone().into_bytes();
                        bytes[14] = *c;
                        let candidate = String::from_utf8(bytes).expect("ascii");
                        let check = Eic::compute_check_character(&candidate)?;
                        format!("{candidate}{check}").parse::<Eic>().ok()
                    })
                    .expect("every residue is reachable from the last body character")
            },
        )
    }

    proptest! {
        /// Stability + totality: sixteen characters out, the same value back.
        #[test]
        fn eic_round_trips(id in arb_eic()) {
            let s = id.to_string();
            prop_assert_eq!(s.len(), Eic::LEN);
            prop_assert_eq!(s.parse::<Eic>(), Ok(id));
        }

        /// Injectivity: two different codes cannot share a spelling.
        #[test]
        fn eics_are_injective(x in arb_eic(), y in arb_eic()) {
            prop_assert_eq!(x == y, x.to_string() == y.to_string());
        }

        /// Idempotence: lowercase and surrounding whitespace converge on the
        /// one canonical spelling.
        #[test]
        fn eic_normalises_case_and_padding(id in arb_eic()) {
            let messy = format!("  {}\t", id.to_string().to_lowercase());
            prop_assert_eq!(messy.parse::<Eic>(), Ok(id));
        }

        /// The check character is the point of the type: a single wrong
        /// character in the body is always caught, because changing one
        /// character changes the weighted sum by `w × δ` with `w` in 2..=16
        /// and `|δ| < 37`, which is never a multiple of 37.
        #[test]
        fn eic_single_character_corruption_is_caught(
            id in arb_eic(),
            pos in 0usize..15,
            bump in 1u32..37,
        ) {
            let mut bytes = id.to_string().into_bytes();
            let current = ALPHABET.iter().position(|c| *c == bytes[pos]).expect("in alphabet");
            let replacement = ALPHABET[(current + bump as usize) % ALPHABET.len()];
            if replacement == bytes[pos] {
                return Ok(());
            }
            bytes[pos] = replacement;
            let corrupted = String::from_utf8(bytes).expect("ascii");
            prop_assert!(
                corrupted.parse::<Eic>().is_err(),
                "{corrupted} was accepted",
            );
        }

        /// The object type is read off position 3 and nothing else.
        #[test]
        fn the_object_type_is_the_third_character(id in arb_eic()) {
            let letter = &id.to_string()[2..3];
            prop_assert_eq!(
                id.object_type().map(|t| t.as_str().to_owned()),
                Some(letter.to_owned()),
            );
        }
    }
}

// ── BdewCode ─────────────────────────────────────────────────────────────────

mod marktpartner_id {
    use metering::ids::{BdewCode, Issuer};
    use proptest::prelude::*;

    /// Twelve digits plus the BDEW check digit computed for them.
    pub fn arb_bdew_code() -> impl Strategy<Value = BdewCode> {
        "[0-9]{12}".prop_map(|body| {
            let check = BdewCode::compute_check_digit(&body).expect("twelve digits");
            format!("{body}{check}")
                .parse()
                .expect("a valid check digit")
        })
    }

    proptest! {
        /// Stability + totality: thirteen digits out, the same value back.
        #[test]
        fn bdew_code_round_trips(id in arb_bdew_code()) {
            let s = id.to_string();
            prop_assert_eq!(s.len(), BdewCode::LEN);
            prop_assert!(s.bytes().all(|b| b.is_ascii_digit()));
            prop_assert_eq!(s.parse::<BdewCode>(), Ok(id));
        }

        /// Injectivity: two different codes cannot share a spelling.
        #[test]
        fn bdew_codes_are_injective(x in arb_bdew_code(), y in arb_bdew_code()) {
            prop_assert_eq!(x == y, x.to_string() == y.to_string());
        }

        /// Surrounding whitespace is tolerated on the way in and never written
        /// on the way out — the same leniency every parser here has.
        #[test]
        fn bdew_code_tolerates_padding(id in arb_bdew_code()) {
            let padded = format!("  {id}\t");
            prop_assert_eq!(padded.parse::<BdewCode>(), Ok(id));
        }

        /// With a valid BDEW check digit the issuer is the leading pair.
        #[test]
        fn the_issuer_is_the_leading_pair(id in arb_bdew_code()) {
            let expected = match &id.to_string()[..2] {
                "99" => Issuer::Bdew,
                "98" => Issuer::Dvgw,
                _ => Issuer::Gs1,
            };
            prop_assert_eq!(id.issuer(), expected);
        }

        /// A code built from twelve digits plus the computed thirteenth always
        /// satisfies the BDEW procedure; changing one digit of the body almost
        /// never does.
        #[test]
        fn the_check_digit_is_advisory_but_correct(body in "[0-9]{12}") {
            let check = BdewCode::compute_check_digit(&body).expect("twelve digits");
            let consistent: BdewCode = format!("{body}{check}").parse().unwrap();
            prop_assert!(consistent.has_bdew_check_digit());
            prop_assert_eq!(consistent.check_digit(), check);

            // A wrong digit parses only when GS1's procedure happens to hold.
            let wrong = (check + 1) % 10;
            if let Ok(mismatched) = format!("{body}{wrong}").parse::<BdewCode>() {
                prop_assert!(!mismatched.has_bdew_check_digit());
                prop_assert_eq!(mismatched.issuer(), Issuer::Gs1);
            }
        }

        /// Anything that is not thirteen digits is refused.
        #[test]
        fn malformed_codes_are_refused(s in "[0-9]{0,12}|[0-9]{14,20}|[A-Za-z][A-Za-z0-9]{12}") {
            prop_assert!(s.parse::<BdewCode>().is_err(), "{}", s);
        }
    }
}

// ── The serde form is the same string ────────────────────────────────────────

#[cfg(feature = "serde")]
mod serde_agrees_with_display {
    use super::market_ids::arb_malo;
    use super::marktpartner_id::arb_bdew_code;
    use super::{arb_obis, arb_resolution};
    use metering::{MaloId, MeloId, ObisCode, Resolution, ids::BdewCode};
    use proptest::prelude::*;

    proptest! {
        /// A value written by `serde` and a value written by `Display` must be
        /// the same bytes. Two writers, one spelling.
        #[test]
        fn obis_serde_form_is_the_display_form(code in arb_obis()) {
            let encoded = serde_json::to_string(&code).unwrap();
            prop_assert_eq!(&encoded, &format!("\"{code}\""));
            prop_assert_eq!(serde_json::from_str::<ObisCode>(&encoded).unwrap(), code);
        }

        #[test]
        fn resolution_serde_form_is_the_display_form(r in arb_resolution()) {
            let encoded = serde_json::to_string(&r).unwrap();
            prop_assert_eq!(&encoded, &format!("\"{r}\""));
            prop_assert_eq!(serde_json::from_str::<Resolution>(&encoded).unwrap(), r);
        }

        /// The identifiers travel as their digits too — the same rule.
        #[test]
        fn malo_serde_form_is_the_display_form(id in arb_malo()) {
            let encoded = serde_json::to_string(&id).unwrap();
            prop_assert_eq!(&encoded, &format!("\"{id}\""));
            prop_assert_eq!(serde_json::from_str::<MaloId>(&encoded).unwrap(), id);
        }

        #[test]
        fn bdew_code_serde_form_is_the_display_form(id in arb_bdew_code()) {
            let encoded = serde_json::to_string(&id).unwrap();
            prop_assert_eq!(&encoded, &format!("\"{id}\""));
            prop_assert_eq!(serde_json::from_str::<BdewCode>(&encoded).unwrap(), id);
        }

        /// …and so does the Zählpunktbezeichnung, uppercased on the way in.
        ///
        /// Two letters, the six-digit Netzbetreiber number, then twenty-five
        /// free alphanumerics: 33 characters exactly.
        #[test]
        fn melo_serde_form_is_the_display_form(
            nb in "[0-9]{6}",
            tail in "[A-Za-z0-9]{25}",
        ) {
            let raw = format!("DE{nb}{tail}");
            let id: MeloId = raw.parse().unwrap();
            let encoded = serde_json::to_string(&id).unwrap();
            prop_assert_eq!(&encoded, &format!("\"{id}\""));
            prop_assert_eq!(serde_json::from_str::<MeloId>(&encoded).unwrap(), id);
        }
    }

    /// Both spellings deserialise, so archives written before the canonical
    /// form was pinned still read.
    #[test]
    fn obis_deserialises_from_either_spelling() {
        let short: ObisCode = serde_json::from_str("\"1-0:1.8.0\"").unwrap();
        let long: ObisCode = serde_json::from_str("\"1-0:1.8.0*255\"").unwrap();
        assert_eq!(short, long);
        assert_eq!(short, ObisCode::STROM_BEZUG_TOTAL);
    }

    /// Non-borrowing deserialisers must work.
    ///
    /// `serde(try_from = "&str")` required the deserialiser to hand out a
    /// borrowed `&str`, so `from_reader`, bincode, postcard and MessagePack all
    /// failed with "invalid type: string … expected a borrowed string" —
    /// regardless of what the payload said. Streaming a file of intervals was
    /// simply impossible.
    #[test]
    fn obis_deserialises_from_a_non_borrowing_deserialiser() {
        let json = r#"["1-0:1.8.0","7-0:3.0.0","1-0:1.8.0*1"]"#;
        let decoded: Vec<ObisCode> = serde_json::from_reader(std::io::Cursor::new(json))
            .expect("a reader-backed deserialiser must work");
        assert_eq!(
            decoded,
            vec![
                ObisCode::STROM_BEZUG_TOTAL,
                ObisCode::GAS_VOLUME_M3,
                "1-0:1.8.0*1".parse().unwrap(),
            ]
        );
    }

    #[test]
    fn resolution_deserialises_from_a_non_borrowing_deserialiser() {
        let json = r#"["PT15M","P1D","PT5M"]"#;
        let decoded: Vec<Resolution> =
            serde_json::from_reader(std::io::Cursor::new(json)).expect("reader-backed");
        assert_eq!(
            decoded,
            vec![
                Resolution::QUARTER_HOUR,
                Resolution::Day,
                Resolution::minutes(5).unwrap(),
            ]
        );
    }

    /// A malformed string is an error, never a silent default.
    #[test]
    fn malformed_strings_are_rejected() {
        assert!(serde_json::from_str::<ObisCode>("\"1-0:1.8\"").is_err());
        assert!(serde_json::from_str::<ObisCode>("\"\"").is_err());
        assert!(serde_json::from_str::<Resolution>("\"hourly\"").is_err());
        // The old derived spellings are gone and must not be silently accepted.
        assert!(serde_json::from_str::<Resolution>("\"QuarterHour\"").is_err());
        assert!(serde_json::from_str::<Resolution>(r#"{"Custom":300}"#).is_err());
    }
}