Skip to main content

oicp_kit/types/
ids.rs

1//! The OICP identifier types: parsed, structured, and byte-exact on the wire.
2//!
3//! # Two grammars, one field
4//!
5//! Every identifier in OICP accepts **two** encodings, and the specification gives one regular
6//! expression that unions them:
7//!
8//! * **ISO 15118-1** — `DE*AB7*E840*6487`, `DEAB7E8406487`. Alpha-2 country code, `*` optional.
9//! * **DIN SPEC 91286:2011-11** — `+49*810*000*438`. ITU-T E.164 country code, `*` mandatory.
10//!
11//! A library that models these as `String` cannot tell an operator's ID from a provider's, cannot
12//! tell you which country an EVSE is in, and — worse — invites the caller to normalise. A library
13//! that *normalises* breaks production: Hubject compares the `OperatorID`/`ProviderID` in the URL
14//! path against the partner's TLS client certificate, and answers a mismatch with status code
15//! `017 Unauthorized Access`. `DE*ABC` and `DEABC` are the same operator to a human and to this
16//! crate's [`Eq`], but they are different strings to a certificate check.
17//!
18//! So the types here are **parse-preserving**:
19//!
20//! * [`FromStr`] parses the grammar and records which standard matched.
21//! * The components — country, operator, instance, check digit — are available as accessors.
22//! * [`Display`](core::fmt::Display) and `Serialize` return **the exact text that arrived**.
23//! * [`PartialEq`], [`Hash`] and [`Ord`] compare *semantically*: case-insensitively, ignoring the
24//!   optional separators and the optional DIN `+`. `DE*ABC*E123 == deabce123` and
25//!   `+49*810*000*438 == 49*810*000*438` — the spec writes each pair as one charging spot.
26//!
27//!   The standard a value follows is **not** part of its identity, and does not need to be: the
28//!   two grammars are disjoint where they say different things (an ISO id begins with two letters,
29//!   a DIN one with digits) and identical where they do not ([`ProviderId`] — the spec lists
30//!   `DE8EO` under both headings). Folding the standard into equality instead buys nothing and
31//!   costs transitivity, because a value that satisfies both grammars would have to compare equal
32//!   to two values that differ from each other.
33//!
34//! ```
35//! use oicp_kit::types::EvseId;
36//!
37//! let a: EvseId = "DE*AB7*E840*6487".parse()?;
38//! let b: EvseId = "DEAB7E8406487".parse()?;
39//!
40//! assert_eq!(a, b);                                 // the same charging spot
41//! assert_eq!(a.to_string(), "DE*AB7*E840*6487");    // …written back exactly as it arrived
42//! assert_eq!(b.to_string(), "DEAB7E8406487");
43//! assert_eq!(a.country(), "DE");
44//! assert_eq!(a.operator_id().to_string(), "DE*AB7");
45//! # Ok::<(), oicp_kit::types::IdError>(())
46//! ```
47//!
48//! # Validation without a regex engine
49//!
50//! The specification states each grammar as a regular expression. This module implements those
51//! grammars as hand-written character checks rather than pulling in a regex engine: the crate
52//! stays dependency-light, parsing a page of 2000 EVSE records stays allocation-free per field,
53//! and each rule sits next to the sentence of the spec it comes from. The
54//! [`tests`](#) in this module check the hand-written parsers against the spec's own examples,
55//! and `tests/properties.rs` fuzzes them for round-trip exactness.
56
57use core::fmt;
58use core::hash::{Hash, Hasher};
59use core::str::FromStr;
60
61use serde::{Deserialize, Deserializer, Serialize, Serializer};
62
63use super::validate::{Validate, Validator, ViolationCode};
64
65/// Which of the two identifier standards a value follows.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
67pub enum IdStandard {
68    /// ISO 15118-1: alpha-2 country code, separators optional.
69    Iso,
70    /// DIN SPEC 91286:2011-11: ITU-T E.164 numeric country code, separators mandatory.
71    Din,
72    /// The two grammars coincide for this identifier type, so the value does not say which.
73    ///
74    /// [`ProviderId`] is the case: the specification lists `DE8EO` and `DE-8EO` as examples under
75    /// **both** headings, and only permits `*` as an additional separator under DIN. A value like
76    /// `DE-8EO` is therefore simultaneously a valid ISO and a valid DIN provider id, and this is
77    /// the honest answer to "which standard is it?" — not a guess at one of the two.
78    Either,
79}
80
81impl IdStandard {
82    /// A short, stable slug.
83    #[must_use]
84    pub const fn as_str(self) -> &'static str {
85        match self {
86            Self::Iso => "ISO",
87            Self::Din => "DIN",
88            Self::Either => "ISO/DIN",
89        }
90    }
91}
92
93impl fmt::Display for IdStandard {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.write_str(self.as_str())
96    }
97}
98
99/// Why a string is not a valid OICP identifier.
100#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
101#[error("{value:?} is not a valid {type_name}: {reason}")]
102pub struct IdError {
103    type_name: &'static str,
104    value: String,
105    reason: &'static str,
106}
107
108impl IdError {
109    fn new(type_name: &'static str, value: &str, reason: &'static str) -> Self {
110        Self { type_name, value: value.to_owned(), reason }
111    }
112
113    /// The identifier type that rejected the value.
114    #[must_use]
115    pub const fn type_name(&self) -> &'static str {
116        self.type_name
117    }
118
119    /// The text that was rejected.
120    #[must_use]
121    pub fn value(&self) -> &str {
122        &self.value
123    }
124}
125
126/// The bytes that carry an identifier's meaning: upper case, without the optional separators and
127/// without the optional DIN `+`.
128///
129/// The `+` matters. `EvseID`'s DIN grammar is `\+?[0-9]{1,3}\*…`, so `+49*810*000*438` and
130/// `49*810*000*438` are the same charging spot — the specification prints both. Keeping the `+` in
131/// the comparison makes them two, and an EMP that stores one and looks up the other finds nothing.
132///
133/// Allocation-free on purpose: this runs inside `Eq`, `Hash` and `Ord`, which a `BTreeMap` of a
134/// few hundred thousand charging points calls on every operation.
135fn significant_bytes(s: &str) -> impl Iterator<Item = u8> + '_ {
136    s.strip_prefix('+').unwrap_or(s).bytes().filter(|c| !is_separator(*c)).map(|c| c.to_ascii_uppercase())
137}
138
139/// Compares two identifiers the way the roaming network does: ignoring ASCII case, the optional
140/// `*` / `-` separators, and the optional DIN `+`.
141fn semantic_eq(a: &str, b: &str) -> bool {
142    significant_bytes(a).eq(significant_bytes(b))
143}
144
145/// A total order consistent with [`semantic_eq`], so `Ord` and `Eq` agree — which `BTreeMap`
146/// requires and which comparing the canonical *strings* would also give, at the cost of two
147/// allocations per comparison.
148fn semantic_cmp(a: &str, b: &str) -> core::cmp::Ordering {
149    significant_bytes(a).cmp(significant_bytes(b))
150}
151
152fn semantic_hash<H: Hasher>(s: &str, state: &mut H) {
153    for c in significant_bytes(s) {
154        state.write_u8(c);
155    }
156    state.write_u8(0xff);
157}
158
159/// Compares two strings ignoring ASCII case, without allocating.
160fn case_insensitive_cmp(a: &str, b: &str) -> core::cmp::Ordering {
161    a.bytes().map(|c| c.to_ascii_uppercase()).cmp(b.bytes().map(|c| c.to_ascii_uppercase()))
162}
163
164const fn is_separator(c: u8) -> bool {
165    matches!(c, b'*' | b'-')
166}
167
168// Each grammar below walks the bytes with a cursor, guarding every step with
169// `if b.len() < i + n || !b[i..i + n]…`. The `||` is what keeps the slice in bounds, and the guard
170// only fires on an input short enough to reach it — which is why the tests feed every prefix of a
171// valid value rather than a hand-picked set of lengths.
172
173/// Generates the shared body of an identifier newtype: wire-exact storage, semantic equality,
174/// serde, validation and schema.
175macro_rules! oicp_id {
176    (
177        $(#[$meta:meta])*
178        $name:ident, $type_name:literal
179    ) => {
180        $(#[$meta])*
181        #[derive(Clone, Debug)]
182        pub struct $name {
183            /// Exactly the text that arrived on the wire.
184            raw: String,
185            standard: IdStandard,
186        }
187
188        impl $name {
189            /// Parses `value`, keeping its text verbatim.
190            ///
191            /// # Errors
192            ///
193            /// Returns [`IdError`] when the value matches neither the ISO nor the DIN grammar.
194            pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
195                let raw = value.into();
196                let standard = Self::classify(&raw)?;
197                Ok(Self { raw, standard })
198            }
199
200            /// Accepts `value` **without** checking the grammar.
201            ///
202            /// For decoding a peer's payload, where a malformed id must arrive and be reported by
203            /// [`Validate`] rather than break the whole page. `standard` is a best guess; the
204            /// value is reported by [`Validate::validate`] either way.
205            #[must_use]
206            pub fn new_unchecked(value: impl Into<String>) -> Self {
207                let raw = value.into();
208                let standard = Self::classify(&raw).unwrap_or(if raw.starts_with('+') || raw.starts_with(|c: char| c.is_ascii_digit()) {
209                    IdStandard::Din
210                } else {
211                    IdStandard::Iso
212                });
213                Self { raw, standard }
214            }
215
216            /// The identifier exactly as it appears on the wire.
217            #[must_use]
218            pub fn as_str(&self) -> &str {
219                &self.raw
220            }
221
222            /// Which standard this identifier follows.
223            #[must_use]
224            pub const fn standard(&self) -> IdStandard {
225                self.standard
226            }
227
228            /// The identifier with every optional separator removed, upper-cased.
229            ///
230            /// Use this as a database key. Never put it on the wire: Hubject matches identifiers
231            /// against the TLS client certificate as text.
232            #[must_use]
233            pub fn canonical(&self) -> String {
234                significant_bytes(&self.raw).map(char::from).collect()
235            }
236
237            /// Whether this value satisfies the specification's grammar.
238            #[must_use]
239            pub fn is_well_formed(&self) -> bool {
240                Self::classify(&self.raw).is_ok()
241            }
242        }
243
244        impl fmt::Display for $name {
245            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246                f.write_str(&self.raw)
247            }
248        }
249
250        // `Eq`, `Hash` and `Ord` all read the same significant bytes, so they cannot disagree:
251        // equal values hash alike and compare `Equal`, which is what a `HashMap` and a `BTreeMap`
252        // of charging points each rely on. `standard` is metadata about the spelling and takes no
253        // part — see the module documentation.
254        impl PartialEq for $name {
255            fn eq(&self, other: &Self) -> bool {
256                semantic_eq(&self.raw, &other.raw)
257            }
258        }
259        impl Eq for $name {}
260
261        impl Hash for $name {
262            fn hash<H: Hasher>(&self, state: &mut H) {
263                semantic_hash(&self.raw, state);
264            }
265        }
266
267        impl PartialOrd for $name {
268            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
269                Some(self.cmp(other))
270            }
271        }
272
273        impl Ord for $name {
274            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
275                semantic_cmp(&self.raw, &other.raw)
276            }
277        }
278
279        impl FromStr for $name {
280            type Err = IdError;
281            fn from_str(s: &str) -> Result<Self, Self::Err> {
282                Self::new(s)
283            }
284        }
285
286        impl Validate for $name {
287            fn validate_in(&self, v: &mut Validator) {
288                if let Err(e) = Self::classify(&self.raw) {
289                    v.report(ViolationCode::PatternMismatch, e.to_string());
290                }
291            }
292        }
293
294        impl Serialize for $name {
295            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
296                s.serialize_str(&self.raw)
297            }
298        }
299
300        impl<'de> Deserialize<'de> for $name {
301            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
302                // Permissive by design: a malformed id on one record of a 2000-record page must
303                // not fail the page. `Validate` reports it.
304                Ok(Self::new_unchecked(String::deserialize(d)?))
305            }
306        }
307
308        #[cfg(feature = "schema")]
309        impl schemars::JsonSchema for $name {
310            fn schema_name() -> std::borrow::Cow<'static, str> { $type_name.into() }
311            fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
312                schemars::json_schema!({ "type": "string" })
313            }
314        }
315    };
316}
317
318// --- EvseID -------------------------------------------------------------------------------
319
320oicp_id! {
321    /// The ID that identifies a charging spot.
322    ///
323    /// Spec pattern:
324    /// `^(([A-Za-z]{2}\*?[A-Za-z0-9]{3}\*?E[A-Za-z0-9\*]{1,30})|(\+?[0-9]{1,3}\*[0-9]{3}\*[0-9\*]{1,32}))$`
325    ///
326    /// ISO: `DE*AB7*E840*6487`, `DEAB7E8406487` — the `E` after the operator part is what marks an
327    /// id as ISO beyond doubt. DIN: `+49*810*000*438`.
328    EvseId, "EvseID"
329}
330
331impl EvseId {
332    fn classify(s: &str) -> Result<IdStandard, IdError> {
333        if let Ok(()) = Self::check_iso(s) {
334            return Ok(IdStandard::Iso);
335        }
336        Self::check_din(s).map(|()| IdStandard::Din)
337    }
338
339    /// `[A-Za-z]{2} \*? [A-Za-z0-9]{3} \*? E [A-Za-z0-9\*]{1,30}`
340    fn check_iso(s: &str) -> Result<(), IdError> {
341        let b = s.as_bytes();
342        let mut i = 0;
343        let err = |reason| Err(IdError::new("EvseID", s, reason));
344        if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
345            return err("an ISO EvseID starts with a two-letter country code");
346        }
347        i += 2;
348        if b.get(i) == Some(&b'*') {
349            i += 1;
350        }
351        if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
352            return err("the operator part of an ISO EvseID is three alphanumeric characters");
353        }
354        i += 3;
355        if b.get(i) == Some(&b'*') {
356            i += 1;
357        }
358        if b.get(i).is_none_or(|c| !c.eq_ignore_ascii_case(&b'E')) {
359            return err("an ISO EvseID has an 'E' after the operator part");
360        }
361        i += 1;
362        let rest = &b[i..];
363        if rest.is_empty() || rest.len() > 30 {
364            return err("the instance part of an ISO EvseID is 1 to 30 characters");
365        }
366        if !rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'*') {
367            return err("the instance part of an ISO EvseID is alphanumeric with optional '*' separators");
368        }
369        Ok(())
370    }
371
372    /// `\+? [0-9]{1,3} \* [0-9]{3} \* [0-9\*]{1,32}`
373    fn check_din(s: &str) -> Result<(), IdError> {
374        let err = |reason| Err(IdError::new("EvseID", s, reason));
375        let body = s.strip_prefix('+').unwrap_or(s);
376        let mut parts = body.splitn(3, '*');
377        let (Some(country), Some(operator), Some(instance)) = (parts.next(), parts.next(), parts.next())
378        else {
379            return err("a DIN EvseID is country*operator*instance, separated by mandatory '*'");
380        };
381        if country.is_empty() || country.len() > 3 || !country.bytes().all(|c| c.is_ascii_digit()) {
382            return err("the country code of a DIN EvseID is 1 to 3 digits (ITU-T E.164)");
383        }
384        if operator.len() != 3 || !operator.bytes().all(|c| c.is_ascii_digit()) {
385            return err("the operator part of a DIN EvseID is exactly three digits");
386        }
387        if instance.is_empty()
388            || instance.len() > 32
389            || !instance.bytes().all(|c| c.is_ascii_digit() || c == b'*')
390        {
391            return err("the instance part of a DIN EvseID is 1 to 32 digits with optional '*' separators");
392        }
393        Ok(())
394    }
395
396    /// The two- or three-character country code this EVSE belongs to.
397    ///
398    /// Alpha-2 (ISO 3166-1) for an ISO id, numeric (ITU-T E.164) for a DIN one.
399    #[must_use]
400    pub fn country(&self) -> &str {
401        match self.standard() {
402            IdStandard::Din => {
403                let body = self.as_str().strip_prefix('+').unwrap_or(self.as_str());
404                body.split('*').next().unwrap_or("")
405            }
406            // An EvseID always distinguishes the two grammars, so `Either` cannot occur here.
407            IdStandard::Iso | IdStandard::Either => &self.as_str()[..2],
408        }
409    }
410
411    /// The operator that runs this charging spot.
412    ///
413    /// OICP has no `OperatorID` field on most messages — Hubject *derives* the operator from the
414    /// `EvseID`, and so can you. Used by [`MockHubject`](crate::testkit::MockHubject) for routing.
415    #[must_use]
416    pub fn operator_id(&self) -> OperatorId {
417        let raw = match self.standard() {
418            IdStandard::Iso | IdStandard::Either => {
419                // country [sep] operator, stopping before the 'E' marker.
420                let b = self.as_str().as_bytes();
421                let mut end = 2;
422                if b.get(end) == Some(&b'*') {
423                    end += 1;
424                }
425                end += 3;
426                &self.as_str()[..end]
427            }
428            IdStandard::Din => {
429                let s = self.as_str();
430                let plus = usize::from(s.starts_with('+'));
431                let body = &s[plus..];
432                match body.match_indices('*').nth(1) {
433                    Some((idx, _)) => &s[..plus + idx],
434                    None => s,
435                }
436            }
437        };
438        OperatorId::new_unchecked(raw)
439    }
440}
441
442// --- EvcoID -------------------------------------------------------------------------------
443
444oicp_id! {
445    /// The contract ID that identifies an EV driver's contract with an EMP.
446    ///
447    /// Spec pattern:
448    /// `^(([A-Za-z]{2}\-?[A-Za-z0-9]{3}\-?C[A-Za-z0-9]{8}\-?[\d|A-Za-z])|([A-Za-z]{2}[\*|\-]?[A-Za-z0-9]{3}[\*|\-]?[A-Za-z0-9]{6}[\*|\-]?[\d|X]))$`
449    ///
450    /// ISO: eight-character instance prefixed with `C`, separator `-`, then a check character —
451    /// `DE-8EO-CAet5e4XY-3`. DIN: six-character instance, separator `*` or `-` —
452    /// `DE*8EO*Aet5e4*3`.
453    EvcoId, "EvcoID"
454}
455
456impl EvcoId {
457    fn classify(s: &str) -> Result<IdStandard, IdError> {
458        if Self::check_iso(s).is_ok() {
459            return Ok(IdStandard::Iso);
460        }
461        Self::check_din(s).map(|()| IdStandard::Din)
462    }
463
464    /// `[A-Za-z]{2} \-? [A-Za-z0-9]{3} \-? C [A-Za-z0-9]{8} \-? [\d|A-Za-z]`
465    fn check_iso(s: &str) -> Result<(), IdError> {
466        let b = s.as_bytes();
467        let err = |reason| Err(IdError::new("EvcoID", s, reason));
468        let mut i = 0;
469        if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
470            return err("an ISO EvcoID starts with a two-letter country code");
471        }
472        i += 2;
473        if b.get(i) == Some(&b'-') {
474            i += 1;
475        }
476        if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
477            return err("the provider part of an ISO EvcoID is three alphanumeric characters");
478        }
479        i += 3;
480        if b.get(i) == Some(&b'-') {
481            i += 1;
482        }
483        if b.get(i).is_none_or(|c| !c.eq_ignore_ascii_case(&b'C')) {
484            return err("an ISO EvcoID prefixes its instance part with 'C'");
485        }
486        i += 1;
487        if b.len() < i + 8 || !b[i..i + 8].iter().all(u8::is_ascii_alphanumeric) {
488            return err("the instance part of an ISO EvcoID is exactly eight alphanumeric characters");
489        }
490        i += 8;
491        if b.get(i) == Some(&b'-') {
492            i += 1;
493        }
494        if b.len() != i + 1 || !b[i].is_ascii_alphanumeric() {
495            return err("an ISO EvcoID ends with a single check character");
496        }
497        Ok(())
498    }
499
500    /// `[A-Za-z]{2} [\*\-]? [A-Za-z0-9]{3} [\*\-]? [A-Za-z0-9]{6} [\*\-]? [\dX]`
501    fn check_din(s: &str) -> Result<(), IdError> {
502        let b = s.as_bytes();
503        let err = |reason| Err(IdError::new("EvcoID", s, reason));
504        let mut i = 0;
505        if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
506            return err("a DIN EvcoID starts with a two-letter country code");
507        }
508        i += 2;
509        if b.get(i).is_some_and(|c| is_separator(*c)) {
510            i += 1;
511        }
512        if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
513            return err("the provider part of a DIN EvcoID is three alphanumeric characters");
514        }
515        i += 3;
516        if b.get(i).is_some_and(|c| is_separator(*c)) {
517            i += 1;
518        }
519        if b.len() < i + 6 || !b[i..i + 6].iter().all(u8::is_ascii_alphanumeric) {
520            return err("the instance part of a DIN EvcoID is exactly six alphanumeric characters");
521        }
522        i += 6;
523        if b.get(i).is_some_and(|c| is_separator(*c)) {
524            i += 1;
525        }
526        if b.len() != i + 1 || !(b[i].is_ascii_digit() || b[i].eq_ignore_ascii_case(&b'X')) {
527            return err("a DIN EvcoID ends with a check digit or 'X'");
528        }
529        Ok(())
530    }
531
532    /// The EMP that issued this contract.
533    ///
534    /// Hubject routes an authorization to the EMP named by the EvcoID's provider part, so this is
535    /// how a CPO — or [`MockHubject`](crate::testkit::MockHubject) — finds the counterparty.
536    #[must_use]
537    pub fn provider_id(&self) -> ProviderId {
538        let b = self.as_str().as_bytes();
539        let mut end = 2;
540        if b.get(end).is_some_and(|c| is_separator(*c)) {
541            end += 1;
542        }
543        end = (end + 3).min(self.as_str().len());
544        ProviderId::new_unchecked(&self.as_str()[..end])
545    }
546}
547
548// --- OperatorID ---------------------------------------------------------------------------
549
550oicp_id! {
551    /// Identifies a Charge Point Operator, including its country code.
552    ///
553    /// Spec pattern: `^(([A-Za-z]{2}\*?[A-Za-z0-9]{3})|(\+?[0-9]{1,3}\*[0-9]{3}))$`
554    ///
555    /// ISO: `DE*A36`, `DEA36`. DIN: `+49*536`.
556    ///
557    /// This is the value Hubject matches against the partner's TLS client certificate when it
558    /// appears in a URL path, which is why it is never rewritten on the way out.
559    OperatorId, "OperatorID"
560}
561
562impl OperatorId {
563    fn classify(s: &str) -> Result<IdStandard, IdError> {
564        let b = s.as_bytes();
565        let err = |reason| Err(IdError::new("OperatorID", s, reason));
566        // ISO: two letters, optional '*', three alphanumerics.
567        if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1].is_ascii_alphabetic() {
568            let rest = if b.get(2) == Some(&b'*') { &b[3..] } else { &b[2..] };
569            if rest.len() == 3 && rest.iter().all(u8::is_ascii_alphanumeric) {
570                return Ok(IdStandard::Iso);
571            }
572            return err("an ISO OperatorID is a two-letter country code and three alphanumeric characters");
573        }
574        // DIN: optional '+', 1-3 digits, '*', exactly three digits.
575        let body = s.strip_prefix('+').unwrap_or(s);
576        let mut parts = body.splitn(2, '*');
577        let (Some(country), Some(operator)) = (parts.next(), parts.next()) else {
578            return err("a DIN OperatorID is country*operator with a mandatory '*'");
579        };
580        if country.is_empty() || country.len() > 3 || !country.bytes().all(|c| c.is_ascii_digit()) {
581            return err("the country code of a DIN OperatorID is 1 to 3 digits");
582        }
583        if operator.len() != 3 || !operator.bytes().all(|c| c.is_ascii_digit()) {
584            return err("the operator part of a DIN OperatorID is exactly three digits");
585        }
586        Ok(IdStandard::Din)
587    }
588
589    /// The country code of this operator.
590    #[must_use]
591    pub fn country(&self) -> &str {
592        match self.standard() {
593            IdStandard::Din => {
594                let body = self.as_str().strip_prefix('+').unwrap_or(self.as_str());
595                body.split('*').next().unwrap_or("")
596            }
597            // An OperatorID always distinguishes the two grammars, so `Either` cannot occur here.
598            IdStandard::Iso | IdStandard::Either => &self.as_str()[..2],
599        }
600    }
601}
602
603// --- ProviderID ---------------------------------------------------------------------------
604
605oicp_id! {
606    /// Identifies an e-Mobility Provider. Assigned by Hubject.
607    ///
608    /// Spec pattern: `^([A-Za-z]{2}\-?[A-Za-z0-9]{3}|[A-Za-z]{2}[\*|-]?[A-Za-z0-9]{3})$`
609    ///
610    /// `DE8EO`, `DE-8EO`, `DE*8EO` are the same provider.
611    ///
612    /// This is the value Hubject matches against the partner's TLS client certificate when it
613    /// appears in a URL path, which is why it is never rewritten on the way out.
614    ProviderId, "ProviderID"
615}
616
617impl ProviderId {
618    fn classify(s: &str) -> Result<IdStandard, IdError> {
619        let b = s.as_bytes();
620        let err = |reason| Err(IdError::new("ProviderID", s, reason));
621        if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
622            return err("a ProviderID starts with a two-letter country code");
623        }
624        let (rest, separated) =
625            if b.get(2).is_some_and(|c| is_separator(*c)) { (&b[3..], true) } else { (&b[2..], false) };
626        if rest.len() != 3 || !rest.iter().all(u8::is_ascii_alphanumeric) {
627            return err("a ProviderID is a two-letter country code and three alphanumeric characters");
628        }
629        // The spec lists `DE8EO` and `DE-8EO` under *both* the ISO and the DIN heading and adds
630        // `DE*8EO` under DIN, so no provider id distinguishes the two grammars. Claiming one
631        // would make `DE-8EO` and `DE*8EO` — the same EMP — compare unequal.
632        let _ = separated;
633        Ok(IdStandard::Either)
634    }
635
636    /// The country code of this provider.
637    #[must_use]
638    pub fn country(&self) -> &str {
639        &self.as_str()[..2]
640    }
641}
642
643// --- ChargingPoolID -----------------------------------------------------------------------
644
645oicp_id! {
646    /// Groups EVSEs into a charging pool, per the emi³ standard definition.
647    ///
648    /// Spec pattern: `([A-Za-z]{2}\*?[A-Za-z0-9]{3}\*?P[A-Za-z0-9\*]{1,30})` — the ISO `EvseID`
649    /// grammar with `P` (pool) in place of `E`. There is no DIN form and no check digit.
650    ///
651    /// Example: `IT*123*P456*AB789`.
652    ChargingPoolId, "ChargingPoolID"
653}
654
655impl ChargingPoolId {
656    fn classify(s: &str) -> Result<IdStandard, IdError> {
657        let b = s.as_bytes();
658        let err = |reason| Err(IdError::new("ChargingPoolID", s, reason));
659        let mut i = 0;
660        if b.len() < 2 || !b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic() {
661            return err("a ChargingPoolID starts with a two-letter country code");
662        }
663        i += 2;
664        if b.get(i) == Some(&b'*') {
665            i += 1;
666        }
667        if b.len() < i + 3 || !b[i..i + 3].iter().all(u8::is_ascii_alphanumeric) {
668            return err("the operator part of a ChargingPoolID is three alphanumeric characters");
669        }
670        i += 3;
671        if b.get(i) == Some(&b'*') {
672            i += 1;
673        }
674        if b.get(i).is_none_or(|c| !c.eq_ignore_ascii_case(&b'P')) {
675            return err("a ChargingPoolID has a 'P' after the operator part, marking it as a pool");
676        }
677        i += 1;
678        let rest = &b[i..];
679        if rest.is_empty() || rest.len() > 30 {
680            return err("the pool part of a ChargingPoolID is 1 to 30 characters");
681        }
682        if !rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'*') {
683            return err("the pool part of a ChargingPoolID is alphanumeric with optional '*' separators");
684        }
685        Ok(IdStandard::Iso)
686    }
687}
688
689// --- SessionID ----------------------------------------------------------------------------
690
691/// The Hubject session identifier that ties an authorization, its charging process and its CDR
692/// together.
693///
694/// Spec pattern: `^[A-Za-z0-9]{8}(-[A-Za-z0-9]{4}){3}-[A-Za-z0-9]{12}$` — GUID-shaped, but note
695/// that OICP allows *letters* in every group, so it is not necessarily a hex UUID.
696///
697/// Example: `b2688855-7f00-0002-6d8e-48d883f6abb6`.
698#[derive(Clone, Debug)]
699pub struct SessionId(String);
700
701impl SessionId {
702    /// Parses `value`.
703    ///
704    /// # Errors
705    ///
706    /// Returns [`IdError`] when the value does not have the GUID shape OICP requires.
707    pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
708        let raw = value.into();
709        Self::check(&raw)?;
710        Ok(Self(raw))
711    }
712
713    /// Accepts `value` without checking the grammar; [`Validate`] reports it.
714    #[must_use]
715    pub fn new_unchecked(value: impl Into<String>) -> Self {
716        Self(value.into())
717    }
718
719    /// The session id exactly as it appears on the wire.
720    #[must_use]
721    pub fn as_str(&self) -> &str {
722        &self.0
723    }
724
725    /// Whether this value satisfies the specification's grammar.
726    #[must_use]
727    pub fn is_well_formed(&self) -> bool {
728        Self::check(&self.0).is_ok()
729    }
730
731    fn check(s: &str) -> Result<(), IdError> {
732        let err = |reason| Err(IdError::new("SessionID", s, reason));
733        let groups: Vec<&str> = s.split('-').collect();
734        if groups.len() != 5 {
735            return err("a SessionID has five '-'-separated groups");
736        }
737        let expected = [8usize, 4, 4, 4, 12];
738        for (group, want) in groups.iter().zip(expected) {
739            if group.len() != want || !group.bytes().all(|c| c.is_ascii_alphanumeric()) {
740                return err("a SessionID is 8-4-4-4-12 alphanumeric characters");
741            }
742        }
743        Ok(())
744    }
745}
746
747impl fmt::Display for SessionId {
748    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749        f.write_str(&self.0)
750    }
751}
752
753impl PartialEq for SessionId {
754    fn eq(&self, other: &Self) -> bool {
755        self.0.eq_ignore_ascii_case(&other.0)
756    }
757}
758impl Eq for SessionId {}
759
760impl Hash for SessionId {
761    fn hash<H: Hasher>(&self, state: &mut H) {
762        for c in self.0.bytes() {
763            state.write_u8(c.to_ascii_uppercase());
764        }
765    }
766}
767
768impl PartialOrd for SessionId {
769    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
770        Some(self.cmp(other))
771    }
772}
773
774impl Ord for SessionId {
775    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
776        case_insensitive_cmp(&self.0, &other.0)
777    }
778}
779
780impl FromStr for SessionId {
781    type Err = IdError;
782    fn from_str(s: &str) -> Result<Self, Self::Err> {
783        Self::new(s)
784    }
785}
786
787impl Validate for SessionId {
788    fn validate_in(&self, v: &mut Validator) {
789        if let Err(e) = Self::check(&self.0) {
790            v.report(ViolationCode::PatternMismatch, e.to_string());
791        }
792    }
793}
794
795impl Serialize for SessionId {
796    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
797        s.serialize_str(&self.0)
798    }
799}
800
801impl<'de> Deserialize<'de> for SessionId {
802    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
803        Ok(Self::new_unchecked(String::deserialize(d)?))
804    }
805}
806
807#[cfg(feature = "schema")]
808impl schemars::JsonSchema for SessionId {
809    fn schema_name() -> std::borrow::Cow<'static, str> {
810        "SessionID".into()
811    }
812    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
813        schemars::json_schema!({ "type": "string" })
814    }
815}
816
817// --- UID ----------------------------------------------------------------------------------
818
819/// An RFID card's unique identifier.
820///
821/// Spec pattern: `^([0-9A-F]{8,8}|[0-9A-F]{14,14}|[0-9A-F]{20,20})$` — uppercase hexadecimal, of
822/// exactly 8, 14 or 20 characters (single, double and triple-length Mifare UIDs).
823///
824/// # Case
825///
826/// Equality is case-insensitive: a reader that reports `7568290fff765f` has read the same card as
827/// one that reports `7568290FFF765F`, and an EMP whose blocklist misses that has a real problem.
828/// The wire form is still preserved exactly.
829///
830/// But the specification writes `[0-9A-F]`, so a lowercase UID is a violation: it **decodes** via
831/// [`new_unchecked`](Self::new_unchecked), compares equal to its uppercase twin, and
832/// [`canonical`](Self::canonical) gives the key — but [`new`](Self::new) refuses it and
833/// [`Validate`] reports it, because a case-sensitive peer will not match what this crate emits.
834#[derive(Clone, Debug)]
835pub struct Uid(String);
836
837impl Uid {
838    /// Parses `value`.
839    ///
840    /// # Errors
841    ///
842    /// Returns [`IdError`] unless the value is 8, 14 or 20 hexadecimal characters.
843    pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
844        let raw = value.into();
845        Self::check(&raw)?;
846        Ok(Self(raw))
847    }
848
849    /// Accepts `value` without checking the grammar; [`Validate`] reports it.
850    #[must_use]
851    pub fn new_unchecked(value: impl Into<String>) -> Self {
852        Self(value.into())
853    }
854
855    /// The UID exactly as it appears on the wire.
856    #[must_use]
857    pub fn as_str(&self) -> &str {
858        &self.0
859    }
860
861    /// The UID upper-cased — the form to use as a lookup key.
862    #[must_use]
863    pub fn canonical(&self) -> String {
864        self.0.to_ascii_uppercase()
865    }
866
867    /// Whether this value satisfies the specification's grammar.
868    #[must_use]
869    pub fn is_well_formed(&self) -> bool {
870        Self::check(&self.0).is_ok()
871    }
872
873    fn check(s: &str) -> Result<(), IdError> {
874        if !matches!(s.len(), 8 | 14 | 20) {
875            return Err(IdError::new("UID", s, "an RFID UID is 8, 14 or 20 characters"));
876        }
877        if !s.bytes().all(|c| c.is_ascii_hexdigit()) {
878            return Err(IdError::new("UID", s, "an RFID UID is hexadecimal"));
879        }
880        // The specification writes `[0-9A-F]`. Readers that emit lower case are common, so a
881        // lowercase UID must *decode* — `new_unchecked` accepts it, `Eq` matches it against its
882        // uppercase twin, and `canonical()` gives the key. But this crate does not *emit* one,
883        // because a case-sensitive peer would not match it.
884        if s.bytes().any(|c| c.is_ascii_lowercase()) {
885            return Err(IdError::new(
886                "UID",
887                s,
888                "the specification writes an RFID UID in uppercase hexadecimal",
889            ));
890        }
891        Ok(())
892    }
893}
894
895impl fmt::Display for Uid {
896    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897        f.write_str(&self.0)
898    }
899}
900
901impl PartialEq for Uid {
902    fn eq(&self, other: &Self) -> bool {
903        self.0.eq_ignore_ascii_case(&other.0)
904    }
905}
906impl Eq for Uid {}
907
908impl Hash for Uid {
909    fn hash<H: Hasher>(&self, state: &mut H) {
910        for c in self.0.bytes() {
911            state.write_u8(c.to_ascii_uppercase());
912        }
913    }
914}
915
916impl PartialOrd for Uid {
917    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
918        Some(self.cmp(other))
919    }
920}
921
922impl Ord for Uid {
923    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
924        case_insensitive_cmp(&self.0, &other.0)
925    }
926}
927
928impl FromStr for Uid {
929    type Err = IdError;
930    fn from_str(s: &str) -> Result<Self, Self::Err> {
931        Self::new(s)
932    }
933}
934
935impl Validate for Uid {
936    fn validate_in(&self, v: &mut Validator) {
937        if let Err(e) = Self::check(&self.0) {
938            v.report(ViolationCode::PatternMismatch, e.to_string());
939        }
940    }
941}
942
943impl Serialize for Uid {
944    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
945        s.serialize_str(&self.0)
946    }
947}
948
949impl<'de> Deserialize<'de> for Uid {
950    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
951        Ok(Self::new_unchecked(String::deserialize(d)?))
952    }
953}
954
955#[cfg(feature = "schema")]
956impl schemars::JsonSchema for Uid {
957    fn schema_name() -> std::borrow::Cow<'static, str> {
958        "UID".into()
959    }
960    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
961        schemars::json_schema!({ "type": "string" })
962    }
963}
964
965// --- ProviderIdOrAll ----------------------------------------------------------------------
966
967/// A [`ProviderId`], or the literal `*` meaning "every subscribed EMP".
968///
969/// The pricing pushes (`PushPricingProductData`, `PushEVSEPricing`) accept an asterisk in place of
970/// a provider id, for offer-to-all prices. Modelling that as a `String` invites a CPO to publish
971/// a price to the entire roaming network by typo, so it is a distinct variant instead.
972///
973/// Spec: `ProviderIDAsterisk`.
974#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
975pub enum ProviderIdOrAll {
976    /// One specific EMP.
977    One(ProviderId),
978    /// Every EMP subscribed to the operator's service — the literal `*`.
979    All,
980}
981
982impl ProviderIdOrAll {
983    /// The value as it appears on the wire.
984    #[must_use]
985    pub fn as_str(&self) -> &str {
986        match self {
987            Self::One(id) => id.as_str(),
988            Self::All => "*",
989        }
990    }
991
992    /// Whether this addresses every subscribed EMP.
993    #[must_use]
994    pub const fn is_all(&self) -> bool {
995        matches!(self, Self::All)
996    }
997}
998
999impl fmt::Display for ProviderIdOrAll {
1000    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001        f.write_str(self.as_str())
1002    }
1003}
1004
1005impl From<ProviderId> for ProviderIdOrAll {
1006    fn from(id: ProviderId) -> Self {
1007        Self::One(id)
1008    }
1009}
1010
1011impl FromStr for ProviderIdOrAll {
1012    type Err = IdError;
1013    fn from_str(s: &str) -> Result<Self, Self::Err> {
1014        if s == "*" { Ok(Self::All) } else { ProviderId::new(s).map(Self::One) }
1015    }
1016}
1017
1018impl Validate for ProviderIdOrAll {
1019    fn validate_in(&self, v: &mut Validator) {
1020        if let Self::One(id) = self {
1021            id.validate_in(v);
1022        }
1023    }
1024}
1025
1026impl Serialize for ProviderIdOrAll {
1027    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1028        s.serialize_str(self.as_str())
1029    }
1030}
1031
1032impl<'de> Deserialize<'de> for ProviderIdOrAll {
1033    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1034        let s = String::deserialize(d)?;
1035        Ok(if s == "*" { Self::All } else { Self::One(ProviderId::new_unchecked(s)) })
1036    }
1037}
1038
1039#[cfg(feature = "schema")]
1040impl schemars::JsonSchema for ProviderIdOrAll {
1041    fn schema_name() -> std::borrow::Cow<'static, str> {
1042        "ProviderIDAsterisk".into()
1043    }
1044    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
1045        schemars::json_schema!({ "type": "string" })
1046    }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use super::*;
1052
1053    #[test]
1054    fn evse_id_accepts_every_example_the_spec_gives() {
1055        for (text, standard) in [
1056            ("DE*AB7*E840*6487", IdStandard::Iso),
1057            ("DEAB7E8406487", IdStandard::Iso),
1058            ("DE*XYZ*ETEST1", IdStandard::Iso),
1059            ("+49*810*000*438", IdStandard::Din),
1060            ("49*810*000*438", IdStandard::Din),
1061        ] {
1062            let id: EvseId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1063            assert_eq!(id.standard(), standard, "{text}");
1064            assert_eq!(id.to_string(), text, "{text} was rewritten");
1065        }
1066    }
1067
1068    #[test]
1069    fn evse_ids_that_differ_only_in_separators_and_case_are_equal() {
1070        let a: EvseId = "DE*AB7*E840*6487".parse().unwrap();
1071        let b: EvseId = "DEAB7E8406487".parse().unwrap();
1072        let c: EvseId = "de*ab7*e840*6487".parse().unwrap();
1073        assert_eq!(a, b);
1074        assert_eq!(a, c);
1075        // …and each keeps its own text.
1076        assert_eq!(a.to_string(), "DE*AB7*E840*6487");
1077        assert_eq!(b.to_string(), "DEAB7E8406487");
1078    }
1079
1080    #[test]
1081    fn an_iso_id_never_equals_a_din_one() {
1082        // Not because the standard is compared, but because the grammars cannot collide: an ISO
1083        // id starts with two letters and a DIN one with digits.
1084        let iso: EvseId = "DE*AB7*E840*6487".parse().unwrap();
1085        let din: EvseId = "+49*810*000*438".parse().unwrap();
1086        assert_ne!(iso, din);
1087    }
1088
1089    #[test]
1090    fn the_optional_din_plus_does_not_make_a_second_charging_spot() {
1091        // `\+?[0-9]{1,3}\*…`: the specification prints both spellings of the same EVSE.
1092        let with: EvseId = "+49*810*000*438".parse().unwrap();
1093        let without: EvseId = "49*810*000*438".parse().unwrap();
1094
1095        assert_eq!(with, without);
1096        assert_eq!(with.cmp(&without), core::cmp::Ordering::Equal);
1097        assert_eq!(with.canonical(), without.canonical());
1098        assert_eq!(with.to_string(), "+49*810*000*438", "and each keeps its own text");
1099        assert_eq!(with.operator_id(), without.operator_id());
1100    }
1101
1102    #[test]
1103    fn ordering_agrees_with_equality_for_every_identifier() {
1104        // `BTreeMap` needs `cmp(a, b) == Equal` to mean `a == b`; a `HashMap` needs equal values
1105        // to hash alike. One set of significant bytes feeds all three.
1106        use std::hash::{BuildHasher as _, RandomState};
1107        let hasher = RandomState::new();
1108        let spellings = ["DE*AB7*E840*6487", "DEAB7E8406487", "de-ab7-e840-6487", "DE*XYZ*ETEST1"];
1109        for a in spellings {
1110            for b in spellings {
1111                let (x, y) = (EvseId::new_unchecked(a), EvseId::new_unchecked(b));
1112                assert_eq!(
1113                    (x.cmp(&y) == core::cmp::Ordering::Equal),
1114                    x == y,
1115                    "Ord and Eq disagree on {a:?} vs {b:?}"
1116                );
1117                if x == y {
1118                    assert_eq!(hasher.hash_one(&x), hasher.hash_one(&y), "{a:?} and {b:?} hash apart");
1119                } else {
1120                    // Without this half, a `Hash` that hashes nothing passes: every key collides,
1121                    // the map degrades to a linear scan, and no test notices.
1122                    assert_ne!(hasher.hash_one(&x), hasher.hash_one(&y), "{a:?} and {b:?} hash alike");
1123                }
1124            }
1125        }
1126    }
1127
1128    #[test]
1129    fn the_operator_is_derived_from_the_evse_id_the_way_hubject_does_it() {
1130        let iso: EvseId = "DE*AB7*E840*6487".parse().unwrap();
1131        assert_eq!(iso.operator_id().to_string(), "DE*AB7");
1132        assert_eq!(iso.country(), "DE");
1133
1134        let packed: EvseId = "DEAB7E8406487".parse().unwrap();
1135        assert_eq!(packed.operator_id().to_string(), "DEAB7");
1136        // Same operator, whichever way the EvseID was written.
1137        assert_eq!(iso.operator_id(), packed.operator_id());
1138
1139        let din: EvseId = "+49*810*000*438".parse().unwrap();
1140        assert_eq!(din.operator_id().to_string(), "+49*810");
1141        assert_eq!(din.country(), "49");
1142    }
1143
1144    #[test]
1145    fn evco_id_accepts_every_example_the_spec_gives() {
1146        for (text, standard) in [
1147            ("DE-8EO-CAet5e4XY-3", IdStandard::Iso),
1148            ("DE8EOCAet5e43X1", IdStandard::Iso),
1149            ("DE*8EO*Aet5e4*3", IdStandard::Din),
1150            ("DE-8EO-Aet5e4-3", IdStandard::Din),
1151            ("DE8EOAet5e43", IdStandard::Din),
1152            ("DE-DCB-C12345678-X", IdStandard::Iso),
1153        ] {
1154            let id: EvcoId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1155            assert_eq!(id.standard(), standard, "{text}");
1156            assert_eq!(id.to_string(), text);
1157        }
1158    }
1159
1160    #[test]
1161    fn the_provider_is_derived_from_the_evco_id() {
1162        let iso: EvcoId = "DE-8EO-CAet5e4XY-3".parse().unwrap();
1163        assert_eq!(iso.provider_id().to_string(), "DE-8EO");
1164        let din: EvcoId = "DE*8EO*Aet5e4*3".parse().unwrap();
1165        assert_eq!(din.provider_id().to_string(), "DE*8EO");
1166        assert_eq!(iso.provider_id(), din.provider_id());
1167    }
1168
1169    #[test]
1170    fn operator_and_provider_ids_accept_the_spec_examples() {
1171        for text in ["DE*A36", "DEA36", "+49*536", "49*536"] {
1172            let id: OperatorId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1173            assert_eq!(id.to_string(), text);
1174        }
1175        for text in ["DE8EO", "DE-8EO", "DE*8EO"] {
1176            let id: ProviderId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1177            assert_eq!(id.to_string(), text);
1178            assert_eq!(id.country(), "DE");
1179        }
1180    }
1181
1182    #[test]
1183    fn malformed_ids_are_rejected_by_new_but_survive_deserialisation() {
1184        assert!("not-an-evse-id".parse::<EvseId>().is_err());
1185        assert!("DE*AB7*840*6487".parse::<EvseId>().is_err()); // no 'E' marker
1186
1187        // A bad id on one record must not fail a 2000-record page.
1188        let id: EvseId = serde_json::from_str(r#""garbage""#).unwrap();
1189        assert!(!id.is_well_formed());
1190        assert_eq!(serde_json::to_string(&id).unwrap(), r#""garbage""#);
1191        assert_eq!(id.validate().unwrap_err().as_slice()[0].code, ViolationCode::PatternMismatch);
1192    }
1193
1194    #[test]
1195    fn every_prefix_of_a_valid_identifier_is_rejected_without_panicking() {
1196        // Each grammar walks the bytes with a cursor and guards every step with
1197        // `if b.len() < i + n || !b[i..i + n]…`. The `||` is what stops the slice from going out
1198        // of bounds, and the guard only *fires* on an input short enough to reach it — which no
1199        // test had. Feeding every prefix of a valid value walks the cursor to each guard in turn,
1200        // so all of them are exercised by construction rather than by enumeration.
1201        //
1202        // It matters because the crate's promise is that a malformed identifier decodes and is
1203        // reported, never panics: `fuzz/fuzz_targets/identifiers.rs` asserts exactly that against
1204        // arbitrary bytes, and this is the same property with the interesting inputs named.
1205        let valid = [
1206            "DE*AB7*E840*6487",
1207            "DEAB7E8406487",
1208            "+49*810*000*438",
1209            "DE-8EO-CAet5e4XY-3",
1210            "DE*8EO*Aet5e4*3",
1211            "DE*A36",
1212            "+49*536",
1213            "DE-8EO",
1214            "IT*123*P456*AB789",
1215            "b2688855-7f00-0002-6d8e-48d883f6abb6",
1216            "7568290FFF765F",
1217        ];
1218
1219        for text in valid {
1220            // Every prefix, and one character past the end of every bound.
1221            let extended = format!("{text}9");
1222            for cut in 0..=extended.len() {
1223                let candidate = &extended[..cut];
1224
1225                // Every type sees every candidate: a truncated EvcoID is a perfectly good thing to
1226                // hand an EvseID parser, and the point is that nothing anywhere unwinds. The
1227                // contract asserted is the one a caller relies on — the cheap question and the
1228                // detailed one agree — which is also what makes an unreached guard visible, since
1229                // a guard that cannot fire cannot make them disagree.
1230                assert_eq!(
1231                    EvseId::new_unchecked(candidate).is_well_formed(),
1232                    EvseId::new(candidate).is_ok(),
1233                    "EvseID disagreed with itself on {candidate:?}"
1234                );
1235                assert_eq!(
1236                    EvcoId::new_unchecked(candidate).is_well_formed(),
1237                    EvcoId::new(candidate).is_ok(),
1238                    "EvcoID disagreed with itself on {candidate:?}"
1239                );
1240                assert_eq!(
1241                    OperatorId::new_unchecked(candidate).is_well_formed(),
1242                    OperatorId::new(candidate).is_ok(),
1243                    "OperatorID disagreed with itself on {candidate:?}"
1244                );
1245                assert_eq!(
1246                    ProviderId::new_unchecked(candidate).is_well_formed(),
1247                    ProviderId::new(candidate).is_ok(),
1248                    "ProviderID disagreed with itself on {candidate:?}"
1249                );
1250                assert_eq!(
1251                    ChargingPoolId::new_unchecked(candidate).is_well_formed(),
1252                    ChargingPoolId::new(candidate).is_ok(),
1253                    "ChargingPoolID disagreed with itself on {candidate:?}"
1254                );
1255                assert_eq!(
1256                    SessionId::new_unchecked(candidate).is_well_formed(),
1257                    SessionId::new(candidate).is_ok(),
1258                    "SessionID disagreed with itself on {candidate:?}"
1259                );
1260                assert_eq!(
1261                    Uid::new_unchecked(candidate).is_well_formed(),
1262                    Uid::new(candidate).is_ok(),
1263                    "UID disagreed with itself on {candidate:?}"
1264                );
1265            }
1266        }
1267
1268        // The prefixes that must specifically be refused, named so the reason is on the record.
1269        assert!("DE".parse::<EvseId>().is_err(), "no operator part at all");
1270        assert!("DE*A".parse::<EvseId>().is_err(), "one operator character");
1271        assert!("DE*AB7*E".parse::<EvseId>().is_err(), "no instance after the E marker");
1272        assert!("DE-8EO-C".parse::<EvcoId>().is_err(), "no instance after the C marker");
1273        assert!("IT*123*P".parse::<ChargingPoolId>().is_err(), "no pool part after the P marker");
1274        assert!("DE".parse::<OperatorId>().is_err(), "a country code is not an OperatorID");
1275        assert!("DE".parse::<ProviderId>().is_err(), "nor a ProviderID");
1276    }
1277
1278    #[test]
1279    fn both_characters_of_a_country_code_must_be_letters() {
1280        // Every grammar opens with `!b[0].is_ascii_alphabetic() || !b[1].is_ascii_alphabetic()`,
1281        // and the two halves need separate cases: written as `&&`, the check demands that *both*
1282        // characters be wrong before it complains, so a country code with one digit in it sails
1283        // through and the whole identifier is accepted. `DE` is the only shape the specification
1284        // allows, and a value like `D3*AB7*E840` is one keystroke away from a real one.
1285        for bad in [
1286            "1EAB7E840",        // EvseID, first character a digit
1287            "E1AB7E840",        // EvseID, second character a digit
1288            "D3*AB7*E840*6487", // …and with the separators in place
1289        ] {
1290            assert!(bad.parse::<EvseId>().is_err(), "{bad} should be rejected");
1291        }
1292        for bad in ["1E-8EO-CAet5e4XY-3", "D3-8EO-CAet5e4XY-3", "1E*8EO*Aet5e4*3", "D3*8EO*Aet5e4*3"] {
1293            assert!(bad.parse::<EvcoId>().is_err(), "{bad} should be rejected");
1294        }
1295        for bad in ["1E8EO", "D38EO", "1E-8EO"] {
1296            assert!(bad.parse::<ProviderId>().is_err(), "{bad} should be rejected");
1297        }
1298        for bad in ["1T*123*P456", "I3*123*P456"] {
1299            assert!(bad.parse::<ChargingPoolId>().is_err(), "{bad} should be rejected");
1300        }
1301        for bad in ["1E*A36", "D3*A36"] {
1302            assert!(bad.parse::<OperatorId>().is_err(), "{bad} should be rejected");
1303        }
1304
1305        // The valid neighbours, so the check is not simply refusing everything.
1306        assert!("DE*AB7*E840*6487".parse::<EvseId>().is_ok());
1307        assert!("DE-8EO-CAet5e4XY-3".parse::<EvcoId>().is_ok());
1308        assert!("DE-8EO".parse::<ProviderId>().is_ok());
1309        assert!("IT*123*P456".parse::<ChargingPoolId>().is_ok());
1310        assert!("DE*A36".parse::<OperatorId>().is_ok());
1311    }
1312
1313    #[test]
1314    fn the_din_grammars_reject_each_part_on_its_own() {
1315        // The DIN branch splits on `*` and checks three parts. Each check needs its own case, or
1316        // an `||` written as an `&&` is caught by nothing.
1317        for bad in [
1318            "49810000438",  // no separators at all
1319            "49*810",       // only two parts
1320            "*810*000",     // empty country
1321            "4999*810*000", // four-digit country
1322            "4a*810*000",   // non-digit country
1323            "49*81*000",    // two-digit operator
1324            "49*8100*000",  // four-digit operator
1325            "49*8a0*000",   // non-digit operator
1326            "49*810*",      // empty instance
1327            "49*810*00a",   // non-digit instance
1328        ] {
1329            assert!(bad.parse::<EvseId>().is_err(), "{bad} should be rejected");
1330            assert!(!EvseId::new_unchecked(bad).is_well_formed(), "{bad}");
1331        }
1332        assert!(format!("49*810*{}", "0".repeat(32)).parse::<EvseId>().is_ok(), "thirty-two digits");
1333        assert!(format!("49*810*{}", "0".repeat(33)).parse::<EvseId>().is_err(), "thirty-three is too many");
1334
1335        // OperatorID's DIN branch, the same way.
1336        for bad in ["49810", "49", "*536", "4999*536", "4a*536", "49*53", "49*5366", "49*5a6"] {
1337            assert!(bad.parse::<OperatorId>().is_err(), "{bad} should be rejected");
1338        }
1339        assert!("+999*536".parse::<OperatorId>().is_ok(), "a three-digit country code");
1340    }
1341
1342    #[test]
1343    fn the_components_a_caller_reads_are_the_ones_in_the_identifier() {
1344        // `country()` feeds routing and `oicp id`; an empty answer is a plausible-looking lie.
1345        assert_eq!("DE*A36".parse::<OperatorId>().unwrap().country(), "DE");
1346        assert_eq!("DEA36".parse::<OperatorId>().unwrap().country(), "DE");
1347        assert_eq!("+49*536".parse::<OperatorId>().unwrap().country(), "49");
1348        assert_eq!("999*536".parse::<OperatorId>().unwrap().country(), "999");
1349        assert_eq!("DE-8EO".parse::<ProviderId>().unwrap().country(), "DE");
1350
1351        let session: SessionId = "b2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1352        assert_eq!(session.as_str(), "b2688855-7f00-0002-6d8e-48d883f6abb6");
1353        assert!(session.is_well_formed());
1354        let broken = SessionId::new_unchecked("nope");
1355        assert_eq!(broken.as_str(), "nope");
1356        assert!(!broken.is_well_formed());
1357    }
1358
1359    #[test]
1360    fn the_pricing_asterisk_survives_every_road_in_and_out() {
1361        let all: ProviderIdOrAll = "*".parse().unwrap();
1362        let one: ProviderIdOrAll = "DE-8EO".parse().unwrap();
1363
1364        assert_eq!(all.to_string(), "*");
1365        assert_eq!(one.to_string(), "DE-8EO");
1366        assert_eq!(all.as_str(), "*");
1367        assert!(all.is_all() && !one.is_all());
1368        assert!(all.validate().is_ok(), "the asterisk is not an identifier to validate");
1369        assert!(one.validate().is_ok());
1370        assert!(ProviderIdOrAll::One(ProviderId::new_unchecked("nope")).validate().is_err());
1371
1372        // The `*` is recognised on the way in, not just on the way out.
1373        assert_eq!(serde_json::from_str::<ProviderIdOrAll>(r#""*""#).unwrap(), ProviderIdOrAll::All);
1374        assert_eq!(serde_json::from_str::<ProviderIdOrAll>(r#""DE-8EO""#).unwrap(), one);
1375        assert_eq!(serde_json::to_string(&all).unwrap(), r#""*""#);
1376    }
1377
1378    #[test]
1379    fn a_rejection_says_which_type_rejected_what() {
1380        // `IdError`'s accessors are what a conformance report is built from, and `oicp id` prints
1381        // the standard. All three are load-bearing text.
1382        let err = "not-an-evse-id".parse::<EvseId>().unwrap_err();
1383        assert_eq!(err.type_name(), "EvseID");
1384        assert_eq!(err.value(), "not-an-evse-id");
1385        assert!(err.to_string().contains("EvseID"), "{err}");
1386        assert!(err.to_string().contains("not-an-evse-id"), "{err}");
1387
1388        assert_eq!("DE*A36".parse::<OperatorId>().unwrap().standard().as_str(), "ISO");
1389        assert_eq!("+49*536".parse::<OperatorId>().unwrap().standard().as_str(), "DIN");
1390        assert_eq!("DE8EO".parse::<ProviderId>().unwrap().standard().as_str(), "ISO/DIN");
1391        assert_eq!(IdStandard::Iso.to_string(), "ISO");
1392        assert_eq!(IdStandard::Din.to_string(), "DIN");
1393        assert_eq!(IdStandard::Either.to_string(), "ISO/DIN");
1394    }
1395
1396    #[cfg(feature = "schema")]
1397    #[test]
1398    fn the_published_schema_describes_every_identifier_as_a_string() {
1399        // `oicp schema` is an artefact partners generate clients from. An empty schema validates
1400        // anything, which is the one answer that helps nobody.
1401        let mut generator = schemars::SchemaGenerator::default();
1402        for (name, schema) in [
1403            ("EvseID", <EvseId as schemars::JsonSchema>::json_schema(&mut generator)),
1404            ("EvcoID", <EvcoId as schemars::JsonSchema>::json_schema(&mut generator)),
1405            ("OperatorID", <OperatorId as schemars::JsonSchema>::json_schema(&mut generator)),
1406            ("ProviderID", <ProviderId as schemars::JsonSchema>::json_schema(&mut generator)),
1407            ("ChargingPoolID", <ChargingPoolId as schemars::JsonSchema>::json_schema(&mut generator)),
1408            ("SessionID", <SessionId as schemars::JsonSchema>::json_schema(&mut generator)),
1409            ("UID", <Uid as schemars::JsonSchema>::json_schema(&mut generator)),
1410            ("ProviderIDAsterisk", <ProviderIdOrAll as schemars::JsonSchema>::json_schema(&mut generator)),
1411        ] {
1412            let json = serde_json::to_value(&schema).unwrap();
1413            assert_eq!(json["type"], "string", "{name} published an empty schema: {json}");
1414        }
1415        assert_eq!(<EvseId as schemars::JsonSchema>::schema_name(), "EvseID");
1416        assert_eq!(<Uid as schemars::JsonSchema>::schema_name(), "UID");
1417        assert_eq!(<ProviderIdOrAll as schemars::JsonSchema>::schema_name(), "ProviderIDAsterisk");
1418    }
1419
1420    #[test]
1421    fn session_ids_compare_hash_and_order_as_one_session() {
1422        // Every routing decision the broker makes turns on this: the session an authorization
1423        // opened is the session a CDR settles. An `eq` that says yes to everything routes every
1424        // CDR to the first session it finds.
1425        use std::hash::{BuildHasher as _, RandomState};
1426        let hasher = RandomState::new();
1427
1428        let lower: SessionId = "b2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1429        let upper: SessionId = "B2688855-7F00-0002-6D8E-48D883F6ABB6".parse().unwrap();
1430        let other: SessionId = "c2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1431
1432        assert_eq!(lower, upper, "one session, written two ways");
1433        assert_eq!(hasher.hash_one(&lower), hasher.hash_one(&upper));
1434        assert_eq!(lower.cmp(&upper), core::cmp::Ordering::Equal);
1435        assert_eq!(lower.to_string(), "b2688855-7f00-0002-6d8e-48d883f6abb6", "and each keeps its text");
1436
1437        assert_ne!(lower, other, "two sessions are two sessions");
1438        assert_ne!(hasher.hash_one(&lower), hasher.hash_one(&other));
1439        assert!(lower < other);
1440        assert!(other > upper);
1441        assert_eq!(lower.partial_cmp(&other), Some(core::cmp::Ordering::Less));
1442    }
1443
1444    #[test]
1445    fn rfid_uids_compare_hash_and_order_as_one_card() {
1446        // An EMP's blocklist is a set of these. A `hash` that hashes nothing turns it into a linear
1447        // scan; an `eq` that says yes to everything blocks every card.
1448        use std::hash::{BuildHasher as _, RandomState};
1449        let hasher = RandomState::new();
1450
1451        let upper: Uid = "7568290FFF765F".parse().unwrap();
1452        let lower = Uid::new_unchecked("7568290fff765f");
1453        let other: Uid = "AABBCCDDEEFF11".parse().unwrap();
1454
1455        assert_eq!(upper, lower);
1456        assert_eq!(hasher.hash_one(&upper), hasher.hash_one(&lower));
1457        assert_eq!(upper.cmp(&lower), core::cmp::Ordering::Equal);
1458
1459        assert_ne!(upper, other);
1460        assert_ne!(hasher.hash_one(&upper), hasher.hash_one(&other));
1461        assert!(other > upper, "A sorts after 7");
1462        assert_eq!(upper.partial_cmp(&other), Some(core::cmp::Ordering::Less));
1463    }
1464
1465    /// Every length bound in the grammars, at the exact value and one step past it.
1466    ///
1467    /// A `<` written as `<=`, or an `||` as an `&&`, changes only what happens *at* the boundary —
1468    /// so a test that probes the middle of a range agrees with the mutant and the specification
1469    /// alike, and says nothing.
1470    #[test]
1471    fn every_grammar_boundary_is_checked_at_the_boundary() {
1472        // EvseID ISO: three alphanumerics after the country, then `E`, then 1..=30 more.
1473        assert!("DE*AB7*E1".parse::<EvseId>().is_ok(), "one instance character is enough");
1474        assert!(format!("DE*AB7*E{}", "1".repeat(30)).parse::<EvseId>().is_ok(), "thirty is the cap");
1475        assert!(format!("DE*AB7*E{}", "1".repeat(31)).parse::<EvseId>().is_err(), "thirty-one is not");
1476        assert!("DE*AB7*E".parse::<EvseId>().is_err(), "an empty instance part is not an EvseID");
1477        assert!("DE*AB*E1".parse::<EvseId>().is_err(), "two operator characters is not three");
1478        assert!("DE*AB7".parse::<EvseId>().is_err(), "and the E marker is not optional");
1479
1480        // EvcoID ISO: `C` then exactly eight, then exactly one check character.
1481        assert!("DE-8EO-CAet5e4XY-3".parse::<EvcoId>().is_ok());
1482        assert!("DE-8EO-CAet5e4X-3".parse::<EvcoId>().is_err(), "seven is not eight");
1483        assert!("DE-8EO-CAet5e4XYZ-3".parse::<EvcoId>().is_err(), "nor is nine");
1484        assert!("DE-8EO-CAet5e4XY-".parse::<EvcoId>().is_err(), "the check character is not optional");
1485        assert!("DE-8EO-CAet5e4XY-34".parse::<EvcoId>().is_err(), "and there is exactly one of it");
1486        assert!("DE-8E-CAet5e4XY-3".parse::<EvcoId>().is_err(), "two provider characters is not three");
1487
1488        // EvcoID DIN: exactly six in the instance, then exactly one digit or X.
1489        assert!("DE*8EO*Aet5e4*3".parse::<EvcoId>().is_ok());
1490        assert!("DE*8EO*Aet5e*3".parse::<EvcoId>().is_err(), "five is not six");
1491        assert!("DE*8EO*Aet5e44*3".parse::<EvcoId>().is_err(), "nor is seven");
1492        assert!("DE*8EO*Aet5e4*".parse::<EvcoId>().is_err(), "the check digit is not optional");
1493        assert!("DE*8EO*Aet5e4*33".parse::<EvcoId>().is_err(), "and there is exactly one of it");
1494        assert!("DE*8EO*Aet5e4*X".parse::<EvcoId>().is_ok(), "X is a check digit");
1495        assert!("DE*8EO*Aet5e4*Y".parse::<EvcoId>().is_err(), "Y is not");
1496
1497        // ChargingPoolID: the ISO EvseID shape with `P`, and the same 1..=30 pool part.
1498        assert!("IT*123*P4".parse::<ChargingPoolId>().is_ok());
1499        assert!(format!("IT*123*P{}", "4".repeat(30)).parse::<ChargingPoolId>().is_ok());
1500        assert!(format!("IT*123*P{}", "4".repeat(31)).parse::<ChargingPoolId>().is_err());
1501        assert!("IT*123*P".parse::<ChargingPoolId>().is_err(), "an empty pool part is not a pool");
1502        assert!("IT*12*P456".parse::<ChargingPoolId>().is_err(), "two operator characters is not three");
1503        assert!("IT*123*456".parse::<ChargingPoolId>().is_err(), "and the P marker is not optional");
1504
1505        // SessionID: 8-4-4-4-12, each group exact.
1506        assert!("b2688855-7f00-0002-6d8e-48d883f6abb6".parse::<SessionId>().is_ok());
1507        for bad in [
1508            "b268885-7f00-0002-6d8e-48d883f6abb6",   // 7 in the first group
1509            "b26888556-7f00-0002-6d8e-48d883f6abb6", // 9
1510            "b2688855-7f0-0002-6d8e-48d883f6abb6",   // 3 in the second
1511            "b2688855-7f00-0002-6d8e-48d883f6abb",   // 11 in the last
1512            "b2688855-7f00-0002-6d8e-48d883f6abb6a", // 13
1513            "b2688855-7f00-0002-6d8e-48d883f6ab_6",  // not alphanumeric
1514        ] {
1515            assert!(bad.parse::<SessionId>().is_err(), "{bad} should be rejected");
1516        }
1517    }
1518
1519    #[test]
1520    fn session_ids_follow_the_guid_shape() {
1521        let id: SessionId = "b2688855-7f00-0002-6d8e-48d883f6abb6".parse().unwrap();
1522        assert_eq!(id.to_string(), "b2688855-7f00-0002-6d8e-48d883f6abb6");
1523        assert!("b2688855-7f00-0002-6d8e".parse::<SessionId>().is_err());
1524        // OICP allows letters everywhere, so this is not a hex-only UUID.
1525        assert!("zzzzzzzz-aaaa-bbbb-cccc-dddddddddddd".parse::<SessionId>().is_ok());
1526    }
1527
1528    #[test]
1529    fn rfid_uids_match_case_insensitively_but_only_uppercase_is_emitted() {
1530        let upper: Uid = "7568290FFF765F".parse().unwrap();
1531        // A reader that reports lower case is common, so the value must decode…
1532        let lower = Uid::new_unchecked("7568290fff765f");
1533
1534        assert_eq!(upper, lower, "the same card");
1535        assert_eq!(lower.to_string(), "7568290fff765f", "and its text survives");
1536        assert_eq!(lower.canonical(), "7568290FFF765F", "with an uppercase key for lookups");
1537
1538        // …but the specification writes [0-9A-F], so this crate will not construct or emit one.
1539        assert!("7568290fff765f".parse::<Uid>().is_err());
1540        assert!(lower.validate().is_err());
1541        assert!(!lower.is_well_formed());
1542        assert!(upper.validate().is_ok());
1543        assert!("123".parse::<Uid>().is_err());
1544    }
1545
1546    #[test]
1547    fn is_well_formed_agrees_with_validate_for_every_identifier() {
1548        // The contract a caller relies on — and one a fuzz target checks for arbitrary input,
1549        // which is how the lowercase-UID disagreement above was found.
1550        for text in ["7568290FFF765F", "7568290fff765f", "123", "", "DE*ABC*E1", "not an id"] {
1551            let uid = Uid::new_unchecked(text);
1552            assert_eq!(uid.is_well_formed(), uid.validate().is_ok(), "Uid disagreed on {text:?}");
1553            let evse = EvseId::new_unchecked(text);
1554            assert_eq!(evse.is_well_formed(), evse.validate().is_ok(), "EvseId disagreed on {text:?}");
1555            let session = SessionId::new_unchecked(text);
1556            assert_eq!(
1557                session.is_well_formed(),
1558                session.validate().is_ok(),
1559                "SessionId disagreed on {text:?}"
1560            );
1561        }
1562    }
1563
1564    #[test]
1565    fn charging_pool_ids_use_the_p_marker() {
1566        let id: ChargingPoolId = "IT*123*P456*AB789".parse().unwrap();
1567        assert_eq!(id.to_string(), "IT*123*P456*AB789");
1568        assert!("IT*123*E456*AB789".parse::<ChargingPoolId>().is_err());
1569    }
1570
1571    #[test]
1572    fn the_pricing_asterisk_is_its_own_variant() {
1573        let all: ProviderIdOrAll = "*".parse().unwrap();
1574        assert!(all.is_all());
1575        assert_eq!(serde_json::to_string(&all).unwrap(), r#""*""#);
1576        let one: ProviderIdOrAll = "DE-8EO".parse().unwrap();
1577        assert!(!one.is_all());
1578    }
1579}