uftp 0.1.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! The UFTP simple types. Each one refuses, on construction, every value its XSD
//! restriction forbids, so a value of the type is always valid on the wire.

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

use rust_decimal::Decimal;

use crate::error::Rejection;

macro_rules! display_as_str {
    ($t:ty) => {
        impl fmt::Display for $t {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
    };
}

fn no_line_breaks(s: &str) -> bool {
    !s.contains(['\n', '\r'])
}

/// The Shapeshifter specification version a message claims, `major.minor.patch`
/// `[XSD SpecVersion]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SpecVersion(String);

impl SpecVersion {
    /// The version this crate implements and emits by default.
    pub const CURRENT: &'static str = "3.1.0";

    /// `3.1.0`.
    #[must_use]
    pub fn current() -> Self {
        Self(Self::CURRENT.to_owned())
    }

    /// The version as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The major version, which selects the schema.
    #[must_use]
    pub fn major(&self) -> u64 {
        self.0
            .split('.')
            .next()
            .and_then(|m| m.parse().ok())
            .unwrap_or(0)
    }
}

impl FromStr for SpecVersion {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let parts: Vec<&str> = s.split('.').collect();
        if parts.len() == 3
            && parts
                .iter()
                .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
        {
            Ok(Self(s.to_owned()))
        } else {
            Err(Rejection::schema(
                "[XSD SpecVersion]",
                format!(
                    "{s} is not a version of the form 3.1.0.",
                    s = crate::error::quote(&s)
                ),
            ))
        }
    }
}
display_as_str!(SpecVersion);

/// A message or conversation identifier: a UUID in the hyphenated 8-4-4-4-12 form
/// `[XSD UUIDType]`. Compared without regard to case.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MessageUuid(uuid::Uuid);

impl MessageUuid {
    /// Wraps a UUID the caller generated (the library has no random source).
    #[must_use]
    pub fn from_uuid(id: uuid::Uuid) -> Self {
        Self(id)
    }

    /// Builds an id from 16 bytes, for callers that bring their own generator.
    #[must_use]
    pub fn from_bytes(bytes: [u8; 16]) -> Self {
        Self(uuid::Uuid::from_bytes(bytes))
    }

    /// The UUID.
    #[must_use]
    pub fn as_uuid(&self) -> &uuid::Uuid {
        &self.0
    }
}

impl FromStr for MessageUuid {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let groups: Vec<&str> = s.split('-').collect();
        let shape_ok = groups.len() == 5
            && groups
                .iter()
                .zip([8, 4, 4, 4, 12])
                .all(|(g, n)| g.len() == n && g.bytes().all(|b| b.is_ascii_hexdigit()));
        if !shape_ok {
            return Err(Rejection::schema(
                "[XSD UUIDType]",
                format!(
                    "{s} is not a UUID in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.",
                    s = crate::error::quote(&s)
                ),
            ));
        }
        uuid::Uuid::parse_str(s).map(Self).map_err(|_| {
            Rejection::schema(
                "[XSD UUIDType]",
                format!("{s} is not a UUID.", s = crate::error::quote(&s)),
            )
        })
    }
}

impl fmt::Display for MessageUuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0.hyphenated(), f)
    }
}

/// The address of a congestion point or other entity `[XSD EntityAddressType]`:
/// `ean.` followed by 12 to 34 digits, or `ea1.YYYY-MM.<naming authority>:<name>`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EntityAddress(String);

impl EntityAddress {
    /// The address as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for EntityAddress {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let ok = if let Some(digits) = s.strip_prefix("ean.") {
            (12..=34).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit())
        } else if let Some(rest) = s.strip_prefix("ea1.") {
            let b = rest.as_bytes();
            let date_ok = b.len() > 8
                && b[..4].iter().all(u8::is_ascii_digit)
                && b[4] == b'-'
                && b[5..7].iter().all(u8::is_ascii_digit)
                && b[7] == b'.';
            date_ok && no_line_breaks(rest) && {
                let tail = &rest[8..];
                // `.{1,244}:.{1,244}`: some colon splits the tail into two runs of 1 to 244
                // characters.
                tail.char_indices()
                    .filter(|&(_, c)| c == ':')
                    .any(|(i, _)| {
                        let (l, r) = (tail[..i].chars().count(), tail[i + 1..].chars().count());
                        (1..=244).contains(&l) && (1..=244).contains(&r)
                    })
            }
        } else {
            false
        };
        if ok {
            Ok(Self(s.to_owned()))
        } else {
            Err(Rejection::schema(
                "[XSD EntityAddressType]",
                format!(
                    "{s} is not an entity address (ean.<12–34 digits> or ea1.YYYY-MM.<authority>:<name>).",
                    s = crate::error::quote(&s)
                ),
            ))
        }
    }
}
display_as_str!(EntityAddress);

/// The Internet domain of a participant `[XSD InternetDomainType]`: lower-case labels of
/// letters, digits and inner hyphens, and a top-level label of two or more letters.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct InternetDomain(String);

impl InternetDomain {
    /// The domain as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for InternetDomain {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let labels: Vec<&str> = s.split('.').collect();
        let label_ok = |l: &&str| {
            !l.is_empty()
                && !l.starts_with('-')
                && !l.ends_with('-')
                && !l.contains("--")
                && l.bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        };
        let ok = labels.len() >= 2
            && labels[..labels.len() - 1].iter().all(label_ok)
            && labels
                .last()
                .is_some_and(|t| t.len() >= 2 && t.bytes().all(|b| b.is_ascii_lowercase()));
        if ok {
            Ok(Self(s.to_owned()))
        } else {
            Err(Rejection::schema(
                "[XSD InternetDomainType]",
                format!(
                    "{s} is not a lower-case Internet domain such as dso.example.com.",
                    s = crate::error::quote(&s)
                ),
            ))
        }
    }
}
display_as_str!(InternetDomain);

/// An ISO 4217 currency code, three upper-case letters `[XSD ISO4217CurrencyType]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Currency([u8; 3]);

impl Currency {
    /// The euro.
    pub const EUR: Self = Self(*b"EUR");

    /// The code as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        // Construction admits only ASCII upper-case letters.
        std::str::from_utf8(&self.0).unwrap_or("???")
    }
}

impl FromStr for Currency {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        match s.as_bytes() {
            &[a, b, c] if [a, b, c].iter().all(u8::is_ascii_uppercase) => Ok(Self([a, b, c])),
            _ => Err(Rejection::schema(
                "[XSD ISO4217CurrencyType]",
                format!(
                    "{s} is not a three-letter currency code.",
                    s = crate::error::quote(&s)
                ),
            )),
        }
    }
}
display_as_str!(Currency);

fn parse_xsd_decimal(s: &str, rule: &'static str) -> Result<Decimal, Rejection> {
    // xs:decimal lexical space: optional sign, digits, optional fraction; no exponent.
    let body = s.strip_prefix(['+', '-']).unwrap_or(s);
    let (int, frac) = body.split_once('.').unwrap_or((body, ""));
    let lexical_ok = !(int.is_empty() && frac.is_empty())
        && int.bytes().all(|b| b.is_ascii_digit())
        && frac.bytes().all(|b| b.is_ascii_digit());
    if !lexical_ok {
        return Err(Rejection::schema(
            rule,
            format!("{s} is not a decimal number.", s = crate::error::quote(&s)),
        ));
    }
    let normalised = if int.is_empty() {
        format!("0{s}")
    } else {
        s.to_owned()
    };
    // The scale is kept as written ("95.00" stays 95.00): a counterpart may require the
    // currency's minor digits (Shapeshifter SH-02).
    Decimal::from_str_exact(normalised.trim_start_matches('+')).map_err(|_| {
        Rejection::schema(
            rule,
            format!(
                "{s} is out of the supported decimal range.",
                s = crate::error::quote(&s)
            ),
        )
    })
}

/// A money amount with at most four fraction digits `[XSD CurrencyAmountType]`. Too
/// many digits are refused, never rounded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Amount(Decimal);

impl Amount {
    /// Zero.
    pub const ZERO: Self = Self(Decimal::ZERO);

    /// Checks a decimal: at most four fraction digits once trailing zeros are removed. The
    /// scale is kept as given (`95.00` is written `95.00`), unless it is longer than four
    /// digits of trailing zeros, which are dropped.
    ///
    /// # Errors
    /// If the value has more than four significant fraction digits.
    pub fn new(value: Decimal) -> Result<Self, Rejection> {
        if value.scale() <= 4 {
            return Ok(Self(value));
        }
        let v = value.normalize();
        if v.scale() <= 4 {
            Ok(Self(v))
        } else {
            Err(Rejection::schema(
                "[XSD CurrencyAmountType]",
                format!("{value} has more than four fraction digits."),
            ))
        }
    }

    /// The value.
    #[must_use]
    pub fn value(&self) -> Decimal {
        self.0
    }
}

impl FromStr for Amount {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        Self::new(parse_xsd_decimal(s, "[XSD CurrencyAmountType]")?)
    }
}

impl fmt::Display for Amount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// The share of an offer option that is activated, 0.01 to 1.00 with at most two fraction
/// digits `[XSD ActivationFactorType]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ActivationFactor(Decimal);

impl ActivationFactor {
    /// Full activation, the XSD default.
    pub const FULL: Self = Self(Decimal::ONE);

    /// Checks a decimal.
    ///
    /// # Errors
    /// If the value is outside 0.01–1.00 or has more than two fraction digits.
    pub fn new(value: Decimal) -> Result<Self, Rejection> {
        let v = value.normalize();
        if v.scale() <= 2 && v >= Decimal::new(1, 2) && v <= Decimal::ONE {
            Ok(Self(v))
        } else {
            Err(Rejection::schema(
                "[XSD ActivationFactorType]",
                format!(
                    "{value} is not an activation factor between 0.01 and 1.00 with two decimals."
                ),
            ))
        }
    }

    /// The value.
    #[must_use]
    pub fn value(&self) -> Decimal {
        self.0
    }
}

impl Default for ActivationFactor {
    fn default() -> Self {
        Self::FULL
    }
}

impl FromStr for ActivationFactor {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        Self::new(parse_xsd_decimal(s, "[XSD ActivationFactorType]")?)
    }
}

impl fmt::Display for ActivationFactor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:.2}", self.0)
    }
}

/// An IANA time-zone name such as `Europe/Amsterdam`.
///
/// It must match `[XSD TimeZoneNameType]`, which admits only Africa, America, Australia,
/// Europe and Pacific (spec note SS-09), *and* be known to the bundled time-zone database.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneName {
    name: String,
    zone: jiff::tz::TimeZone,
}

impl TimeZoneName {
    /// The name as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.name
    }

    /// The resolved zone.
    #[must_use]
    pub fn zone(&self) -> &jiff::tz::TimeZone {
        &self.zone
    }
}

impl FromStr for TimeZoneName {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let pattern_ok = s.split_once('/').is_some_and(|(area, rest)| {
            ["Africa", "America", "Australia", "Europe", "Pacific"].contains(&area)
                && rest.len() >= 3
                && rest
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/')
        });
        if !pattern_ok {
            return Err(Rejection::schema(
                "[XSD TimeZoneNameType]",
                format!(
                    "{s} is not an Africa/, America/, Australia/, Europe/ or Pacific/ time-zone name.",
                    s = crate::error::quote(&s)
                ),
            ));
        }
        let zone = jiff::tz::db().get(s).map_err(|_| {
            Rejection::schema(
                "[XSD TimeZoneNameType]",
                format!(
                    "{s} is not in the IANA time-zone database.",
                    s = crate::error::quote(&s)
                ),
            )
        })?;
        Ok(Self {
            name: s.to_owned(),
            zone,
        })
    }
}
display_as_str!(TimeZoneName);

/// The length of an imbalance settlement period, whole minutes that divide a day
/// (`PT15M`) `[UFTP §4.2.2 ISP-Duration]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IspDuration(u16);

impl IspDuration {
    /// Fifteen minutes, the European ISP.
    pub const PT15M: Self = Self(15);

    /// Checks a number of minutes.
    ///
    /// # Errors
    /// If the minutes are zero or do not divide 1440.
    pub fn from_minutes(minutes: u16) -> Result<Self, Rejection> {
        if minutes > 0 && 1440 % minutes == 0 {
            Ok(Self(minutes))
        } else {
            Err(Rejection::schema(
                "[UFTP §4.2.2 ISP-Duration]",
                format!("{minutes} minutes is not an ISP length that divides a day."),
            ))
        }
    }

    /// The length in minutes.
    #[must_use]
    pub fn minutes(self) -> u16 {
        self.0
    }
}

impl FromStr for IspDuration {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let minutes = s
            .strip_prefix("PT")
            .and_then(|m| m.strip_suffix('M'))
            .filter(|m| !m.is_empty() && m.bytes().all(|b| b.is_ascii_digit()))
            .and_then(|m| m.parse::<u16>().ok())
            .ok_or_else(|| {
                Rejection::schema(
                    "[UFTP §4.2.2 ISP-Duration]",
                    format!(
                        "{s} is not a duration in whole minutes such as PT15M.",
                        s = crate::error::quote(&s)
                    ),
                )
            })?;
        Self::from_minutes(minutes)
    }
}

impl fmt::Display for IspDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PT{}M", self.0)
    }
}

macro_rules! xsd_enum {
    ($(#[$doc:meta])* $name:ident, $rule:literal, { $($(#[$vdoc:meta])* $variant:ident => $text:literal),+ $(,)? }) => {
        $(#[$doc])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum $name {
            $($(#[$vdoc])* $variant),+
        }

        impl $name {
            /// The value as written in XML.
            #[must_use]
            pub fn as_str(self) -> &'static str {
                match self { $(Self::$variant => $text),+ }
            }
        }

        impl FromStr for $name {
            type Err = Rejection;
            fn from_str(s: &str) -> Result<Self, Rejection> {
                match s {
                    $($text => Ok(Self::$variant),)+
                    _ => Err(Rejection::schema($rule, format!(concat!("{} is not one of: ", $($text, " "),+), crate::error::quote(s)))),
                }
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
    };
}

xsd_enum!(
    /// A USEF role `[XSD USEF-RoleType]`.
    Role, "[XSD USEF-RoleType]", {
        /// Aggregator.
        Agr => "AGR",
        /// Common Reference Operator.
        Cro => "CRO",
        /// Distribution System Operator.
        Dso => "DSO",
    }
);

xsd_enum!(
    /// The outcome of a request `[XSD AcceptedRejectedType]`.
    AcceptedRejected, "[XSD AcceptedRejectedType]", {
        /// Accepted.
        Accepted => "Accepted",
        /// Rejected; the response then carries a reason.
        Rejected => "Rejected",
    }
);

xsd_enum!(
    /// Whether a FlexRequest ISP asks for flexibility or only shows room for it
    /// `[XSD AvailableRequestedType]`.
    AvailableRequested, "[XSD AvailableRequestedType]", {
        /// There is room to deviate.
        Available => "Available",
        /// A deviation is needed.
        Requested => "Requested",
    }
);

xsd_enum!(
    /// The AGR's answer to one order settlement `[XSD AcceptedDisputedType]`.
    AcceptedDisputed, "[XSD AcceptedDisputedType]", {
        /// The AGR accepts and will invoice accordingly.
        Accepted => "Accepted",
        /// The AGR disputes; the status then carries a reason.
        Disputed => "Disputed",
    }
);

xsd_enum!(
    /// Who is responsible for redispatch on a congestion point `[XSD RedispatchByType]`.
    RedispatchBy, "[XSD RedispatchByType]", {
        /// The aggregator.
        Agr => "AGR",
        /// The DSO.
        Dso => "DSO",
    }
);

xsd_enum!(
    /// The kind of data in a metering profile `[XSD MeteringProfileEnum]`.
    MeteringProfileType, "[XSD MeteringProfileEnum]", {
        /// Average active power in the ISP, import minus export, in kW.
        Power => "Power",
        /// Energy imported in the ISP, in kWh.
        ImportEnergy => "ImportEnergy",
        /// Energy exported in the ISP, in kWh.
        ExportEnergy => "ExportEnergy",
        /// The import register at the end of the ISP, in kWh.
        ImportMeterReading => "ImportMeterReading",
        /// The export register at the end of the ISP, in kWh.
        ExportMeterReading => "ExportMeterReading",
    }
);

impl MeteringProfileType {
    /// The unit `[UFTP §4.2.26]` prescribes: kW for Power, kWh for every other type.
    #[must_use]
    pub fn unit(self) -> MeteringUnit {
        match self {
            Self::Power => MeteringUnit::Kw,
            _ => MeteringUnit::Kwh,
        }
    }
}

xsd_enum!(
    /// The unit of a metering profile `[XSD MeteringUnitType]`.
    MeteringUnit, "[XSD MeteringUnitType]", {
        /// Kilowatt.
        Kw => "kW",
        /// Kilowatt-hour.
        Kwh => "kWh",
    }
);

/// The connection a Metering message is about `[XSD EANType]`: `E` (or `e`) followed by 18
/// digits. Unlike an [`EntityAddress`] it has no `ean.` prefix. The case is kept as
/// received.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Ean(String);

impl Ean {
    /// The EAN as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for Ean {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let b = s.as_bytes();
        if b.len() == 19 && matches!(b[0], b'E' | b'e') && b[1..].iter().all(u8::is_ascii_digit) {
            Ok(Self(s.to_owned()))
        } else {
            Err(Rejection::schema(
                "[XSD EANType]",
                format!(
                    "{s} is not an EAN: E followed by 18 digits.",
                    s = crate::error::quote(&s)
                ),
            ))
        }
    }
}

display_as_str!(Ean);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ean_form() {
        assert!("E871685900012636543".parse::<Ean>().is_ok());
        assert!("e871685900012636543".parse::<Ean>().is_ok());
        assert!("ean.871685900012636543".parse::<Ean>().is_err());
        assert!("E87168590001263654".parse::<Ean>().is_err());
        assert_eq!(MeteringProfileType::Power.unit().as_str(), "kW");
        assert_eq!(
            MeteringProfileType::ImportMeterReading.unit().as_str(),
            "kWh"
        );
    }

    #[test]
    fn entity_address_forms() {
        assert!("ean.871685900012636543".parse::<EntityAddress>().is_ok());
        assert!(
            "ea1.2026-11.de.stadtwerk-example:feeder-12"
                .parse::<EntityAddress>()
                .is_ok()
        );
        assert!("ean.12345".parse::<EntityAddress>().is_err());
        assert!(
            "ea1.2026-11.de.example".parse::<EntityAddress>().is_err(),
            "needs a colon"
        );
        assert!("ea1.2026-11.a:b\nc".parse::<EntityAddress>().is_err());
        assert!("EAN.871685900012636543".parse::<EntityAddress>().is_err());
    }

    #[test]
    fn domain_is_lower_case() {
        assert!("dso.example.com".parse::<InternetDomain>().is_ok());
        assert!("my-agr.example".parse::<InternetDomain>().is_ok());
        assert!("DSO.example.com".parse::<InternetDomain>().is_err());
        assert!("example".parse::<InternetDomain>().is_err());
        assert!("-a.example".parse::<InternetDomain>().is_err());
        assert!("a.e1".parse::<InternetDomain>().is_err());
    }

    #[test]
    fn uuid_shape_only_hyphenated() {
        assert!(
            "3F2504E0-4F89-11D3-9A0C-0305E82C3301"
                .parse::<MessageUuid>()
                .is_ok()
        );
        assert!(
            "3f2504e04f8911d39a0c0305e82c3301"
                .parse::<MessageUuid>()
                .is_err()
        );
        assert!(
            "{3f2504e0-4f89-11d3-9a0c-0305e82c3301}"
                .parse::<MessageUuid>()
                .is_err()
        );
        let a: MessageUuid = "3F2504E0-4F89-11D3-9A0C-0305E82C3301".parse().unwrap();
        let b: MessageUuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301".parse().unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn amounts_refuse_extra_digits() {
        // The written scale is kept, up to four digits.
        assert_eq!("12.5000".parse::<Amount>().unwrap().to_string(), "12.5000");
        assert!("0.00001".parse::<Amount>().is_err());
        assert!("1e3".parse::<Amount>().is_err());
        assert!("-3.25".parse::<Amount>().is_ok());
        assert!(".5".parse::<Amount>().is_ok());
    }

    #[test]
    fn activation_factor_bounds() {
        assert!("0.01".parse::<ActivationFactor>().is_ok());
        assert!("1.00".parse::<ActivationFactor>().is_ok());
        assert!("0.005".parse::<ActivationFactor>().is_err());
        assert!("1.01".parse::<ActivationFactor>().is_err());
        assert!("0".parse::<ActivationFactor>().is_err());
        assert_eq!(ActivationFactor::FULL.to_string(), "1.00");
    }

    #[test]
    fn time_zone_pattern_and_database() {
        assert!("Europe/Amsterdam".parse::<TimeZoneName>().is_ok());
        assert!(
            "America/Argentina/Buenos_Aires"
                .parse::<TimeZoneName>()
                .is_ok()
        );
        assert!(
            "Asia/Tokyo".parse::<TimeZoneName>().is_err(),
            "SS-09: the XSD pattern excludes Asia"
        );
        assert!("Europe/Atlantis".parse::<TimeZoneName>().is_err());
    }

    #[test]
    fn isp_duration() {
        assert_eq!("PT15M".parse::<IspDuration>().unwrap(), IspDuration::PT15M);
        assert!("PT15M30S".parse::<IspDuration>().is_err());
        assert!("PT7M".parse::<IspDuration>().is_err());
        assert!("PT0M".parse::<IspDuration>().is_err());
        assert!("P1D".parse::<IspDuration>().is_err());
    }
}