Skip to main content

ocpp_kit/
types.rs

1//! Primitive types shared by every OCPP version.
2
3use alloc::borrow::ToOwned;
4use alloc::format;
5use alloc::string::String;
6use core::fmt;
7use core::str::FromStr;
8
9use serde::{Deserialize, Serialize};
10
11use crate::validate::{Validate, ValidationPath, Violations};
12
13// ---------------------------------------------------------------------------
14// DateTime
15// ---------------------------------------------------------------------------
16
17/// An OCPP `dateTime`: an instant, serialized as RFC 3339 with an explicit offset.
18///
19/// Parsing accepts more than it emits, because the field is full of stations that omit the
20/// offset or use a space separator. Which of those are tolerated is decided by
21/// [`DecodeOptions::datetime`](crate::decode::DecodeOptions::datetime): the strict
22/// `Deserialize` impl below requires an offset, and the decoder repairs the input first when
23/// leniency is enabled. Serialization always emits UTC (`…Z`).
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub struct DateTime(jiff::Timestamp);
26
27impl DateTime {
28    /// The Unix epoch.
29    pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
30
31    #[must_use]
32    /// Wraps a `jiff` timestamp.
33    pub const fn from_timestamp(timestamp: jiff::Timestamp) -> Self {
34        Self(timestamp)
35    }
36
37    #[must_use]
38    /// The underlying `jiff` timestamp.
39    pub const fn timestamp(self) -> jiff::Timestamp {
40        self.0
41    }
42
43    /// The current time from the system clock.
44    #[cfg(feature = "std")]
45    #[must_use]
46    pub fn now() -> Self {
47        Self(jiff::Timestamp::now())
48    }
49
50    /// Parses an RFC 3339 timestamp. The offset is mandatory, and so is the `T` between date
51    /// and time: RFC 3339's `date-time` grammar — which the schemas' `format` names — has no
52    /// other separator. A space is a [`DateTimeLeniency::AllowSpace`] repair.
53    ///
54    /// [`DateTimeLeniency::AllowSpace`]: crate::decode::DateTimeLeniency::AllowSpace
55    pub fn parse(text: &str) -> Result<Self, DateTimeError> {
56        if !matches!(text.as_bytes().get(10), Some(b'T' | b't')) {
57            return Err(DateTimeError {
58                input: text.to_owned(),
59            });
60        }
61        jiff::Timestamp::from_str(text)
62            .map(Self)
63            .map_err(|_| DateTimeError {
64                input: text.to_owned(),
65            })
66    }
67
68    /// Parses leniently: also accepts a missing offset (interpreted as UTC) and a space
69    /// instead of `T`, both of which occur in the field.
70    ///
71    /// Reachable from the decoder via
72    /// [`DateTimeLeniency`](crate::decode::DateTimeLeniency).
73    pub fn parse_lenient(text: &str) -> Result<Self, DateTimeError> {
74        if let Ok(value) = Self::parse(text) {
75            return Ok(value);
76        }
77        let normalized = normalize_datetime(text);
78        Self::parse(&normalized)
79    }
80}
81
82/// Rewrites the common non-conforming timestamp spellings into strict RFC 3339.
83///
84/// Returns the input unchanged when it does not look like a bare local timestamp.
85#[must_use]
86pub fn normalize_datetime(text: &str) -> String {
87    let trimmed = text.trim();
88    let with_t = match trimmed.find(' ') {
89        Some(index) if !trimmed.contains('T') => {
90            let mut s = trimmed.to_owned();
91            s.replace_range(index..=index, "T");
92            s
93        }
94        _ => trimmed.to_owned(),
95    };
96    let has_offset = with_t.ends_with('Z')
97        || with_t.ends_with('z')
98        // `+01:00` / `-05:00`, but not the date's own separators.
99        || with_t.rfind(['+', '-']).is_some_and(|i| i > 10);
100    if has_offset {
101        with_t
102    } else {
103        format!("{with_t}Z")
104    }
105}
106
107impl fmt::Display for DateTime {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        write!(f, "{}", self.0)
110    }
111}
112
113impl From<jiff::Timestamp> for DateTime {
114    fn from(value: jiff::Timestamp) -> Self {
115        Self(value)
116    }
117}
118
119impl From<DateTime> for jiff::Timestamp {
120    fn from(value: DateTime) -> Self {
121        value.0
122    }
123}
124
125impl FromStr for DateTime {
126    type Err = DateTimeError;
127
128    fn from_str(text: &str) -> Result<Self, Self::Err> {
129        Self::parse(text)
130    }
131}
132
133impl Serialize for DateTime {
134    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
135        ser.collect_str(&self.0)
136    }
137}
138
139impl<'de> Deserialize<'de> for DateTime {
140    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
141        struct Visitor;
142
143        impl serde::de::Visitor<'_> for Visitor {
144            type Value = DateTime;
145
146            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147                f.write_str("an RFC 3339 date-time (`T` separator, explicit offset)")
148            }
149
150            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<DateTime, E> {
151                DateTime::parse(text).map_err(E::custom)
152            }
153        }
154
155        // A visitor rather than `<&str>::deserialize`: a JSON string containing an escape
156        // cannot be borrowed, and asking for a borrowed one would report that as
157        // "invalid type: string" — a *type* violation, when the value is really the problem.
158        de.deserialize_str(Visitor)
159    }
160}
161
162impl Validate for DateTime {
163    fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
164}
165
166/// A timestamp that is not valid RFC 3339.
167#[derive(Clone, Debug, PartialEq, Eq)]
168pub struct DateTimeError {
169    input: String,
170}
171
172impl fmt::Display for DateTimeError {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        write!(
175            f,
176            "{:?} is not an RFC 3339 date-time (`T` separator, explicit offset)",
177            self.input
178        )
179    }
180}
181
182#[cfg(feature = "std")]
183impl std::error::Error for DateTimeError {}
184
185// ---------------------------------------------------------------------------
186// Decimal
187// ---------------------------------------------------------------------------
188
189pub use crate::decimal::{Decimal, ParseDecimalError};
190
191// ---------------------------------------------------------------------------
192// integer
193// ---------------------------------------------------------------------------
194
195/// Deserializers for OCPP `integer` members whose schema is JSON Schema draft-06 or later.
196///
197/// From draft-06 on, `"type": "integer"` matches *any number with a zero fractional part*, so
198/// `20000.0` is a valid `integer` for every OCPP 2.0.1 and 2.1 schema (and the OCPP 1.6
199/// security-extension schemas). `serde`'s own `i32` refuses it. The generated types use these
200/// functions on exactly the members whose schema file says draft-06; the OCPP 1.6 core
201/// schemas are draft-04, where an integer is "a JSON number without a fraction or exponent
202/// part", and keep `serde`'s exact reading (a lenient decode can still repair them, see
203/// [`WholeFloats`](crate::decode::WholeFloats)).
204///
205/// A real fraction (`20000.5`) is still a type error, and a value outside `i32` is still a
206/// property error — the same classification an integer literal gets.
207#[doc(hidden)]
208pub mod integer {
209    use alloc::vec::Vec;
210    use core::fmt;
211
212    use serde::de::{self, Deserialize, Deserializer, Unexpected, Visitor};
213
214    /// One `i32` that may arrive as `20000` or `20000.0`.
215    struct Int(i32);
216
217    struct IntVisitor;
218
219    impl Visitor<'_> for IntVisitor {
220        type Value = Int;
221
222        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223            f.write_str("i32")
224        }
225
226        fn visit_i64<E: de::Error>(self, v: i64) -> Result<Int, E> {
227            i32::try_from(v)
228                .map(Int)
229                .map_err(|_| E::invalid_value(Unexpected::Signed(v), &self))
230        }
231
232        fn visit_u64<E: de::Error>(self, v: u64) -> Result<Int, E> {
233            i32::try_from(v)
234                .map(Int)
235                .map_err(|_| E::invalid_value(Unexpected::Unsigned(v), &self))
236        }
237
238        #[allow(
239            clippy::cast_possible_truncation,
240            clippy::cast_precision_loss,
241            clippy::float_cmp
242        )]
243        fn visit_f64<E: de::Error>(self, v: f64) -> Result<Int, E> {
244            // `f64::fract` is `std`-only; a round trip through `i64` is the `no_std` test for
245            // a zero fractional part, guarded so the cast cannot saturate.
246            let whole = v.is_finite() && v.abs() < 9.0e15 && (v as i64) as f64 == v;
247            if !whole {
248                return Err(E::invalid_type(Unexpected::Float(v), &self));
249            }
250            self.visit_i64(v as i64)
251        }
252    }
253
254    impl<'de> Deserialize<'de> for Int {
255        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
256            deserializer.deserialize_any(IntVisitor)
257        }
258    }
259
260    /// A required `integer` member.
261    pub fn one<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i32, D::Error> {
262        Int::deserialize(deserializer).map(|v| v.0)
263    }
264
265    /// An optional `integer` member.
266    pub fn option<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<i32>, D::Error> {
267        Option::<Int>::deserialize(deserializer).map(|v| v.map(|v| v.0))
268    }
269
270    /// A required array of `integer`.
271    pub fn list<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<i32>, D::Error> {
272        Vec::<Int>::deserialize(deserializer).map(|v| v.into_iter().map(|v| v.0).collect())
273    }
274
275    /// An optional array of `integer`.
276    pub fn option_list<'de, D: Deserializer<'de>>(
277        deserializer: D,
278    ) -> Result<Option<Vec<i32>>, D::Error> {
279        Option::<Vec<Int>>::deserialize(deserializer)
280            .map(|v| v.map(|v| v.into_iter().map(|v| v.0).collect()))
281    }
282}
283
284// ---------------------------------------------------------------------------
285// CustomData
286// ---------------------------------------------------------------------------
287
288/// The OCPP 2.x `CustomDataType` extension point.
289///
290/// This is the one object the schemas deliberately leave open, so the unrecognised members
291/// are kept in [`extra`](Self::extra) instead of being dropped — a Local Controller can relay
292/// them and a CSMS can round-trip them.
293#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
294pub struct CustomData {
295    /// Vendor identifier, at most 255 characters.
296    #[serde(rename = "vendorId")]
297    pub vendor_id: String,
298    /// Everything else the vendor put in this object.
299    #[serde(flatten)]
300    pub extra: serde_json::Map<String, serde_json::Value>,
301}
302
303impl CustomData {
304    /// Creates custom data for one vendor.
305    #[must_use]
306    pub fn new(vendor_id: impl Into<String>) -> Self {
307        Self {
308            vendor_id: vendor_id.into(),
309            extra: serde_json::Map::new(),
310        }
311    }
312
313    /// Adds one custom member.
314    #[must_use]
315    pub fn with(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
316        self.extra.insert(key.into(), value.into());
317        self
318    }
319}
320
321impl Validate for CustomData {
322    fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
323        path.push_key("vendorId");
324        crate::validate::string(&self.vendor_id, None, Some(255), path, out);
325        path.pop();
326    }
327}
328
329// ---------------------------------------------------------------------------
330// Identity
331// ---------------------------------------------------------------------------
332
333/// A Charging Station identity.
334///
335/// Carried as the last segment of the WebSocket URL path and, under security profiles 1 and
336/// 2, as the HTTP Basic user name. At most 48 characters, and it must not contain `:`
337/// because that would make the Basic credentials ambiguous (A00.FR.204).
338#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
339#[serde(transparent)]
340pub struct Identity(String);
341
342/// The maximum length of a Charging Station identity, in characters.
343pub const IDENTITY_MAX_LEN: usize = 48;
344
345impl Identity {
346    /// Validates and wraps an identity.
347    pub fn new(value: impl Into<String>) -> Result<Self, IdentityError> {
348        let value = value.into();
349        if value.is_empty() {
350            return Err(IdentityError::Empty);
351        }
352        let len = value.chars().count();
353        if len > IDENTITY_MAX_LEN {
354            return Err(IdentityError::TooLong(len));
355        }
356        // A00.FR.204 — the identity doubles as the Basic-Auth user name.
357        if value.contains(':') {
358            return Err(IdentityError::Colon);
359        }
360        if value.chars().any(char::is_control) {
361            return Err(IdentityError::Control);
362        }
363        Ok(Self(value))
364    }
365
366    #[must_use]
367    /// The identity as a string slice.
368    pub fn as_str(&self) -> &str {
369        &self.0
370    }
371
372    /// Unwraps the identity.
373    #[must_use]
374    pub fn into_string(self) -> String {
375        self.0
376    }
377}
378
379impl fmt::Display for Identity {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.write_str(&self.0)
382    }
383}
384
385impl FromStr for Identity {
386    type Err = IdentityError;
387
388    fn from_str(value: &str) -> Result<Self, Self::Err> {
389        Self::new(value)
390    }
391}
392
393impl<'de> Deserialize<'de> for Identity {
394    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
395        let value = String::deserialize(de)?;
396        Self::new(value).map_err(serde::de::Error::custom)
397    }
398}
399
400/// Why an identity was rejected.
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402#[non_exhaustive]
403pub enum IdentityError {
404    /// The identity is empty.
405    Empty,
406    /// Longer than [`IDENTITY_MAX_LEN`] characters.
407    TooLong(usize),
408    /// Contains `:`, which HTTP Basic authentication cannot represent (A00.FR.204).
409    Colon,
410    /// Contains a control character, which cannot appear in a URL path segment.
411    Control,
412}
413
414impl fmt::Display for IdentityError {
415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416        match self {
417            IdentityError::Empty => f.write_str("charging station identity is empty"),
418            IdentityError::TooLong(len) => {
419                write!(
420                    f,
421                    "charging station identity is {len} characters, maximum is {IDENTITY_MAX_LEN}"
422                )
423            }
424            IdentityError::Colon => {
425                f.write_str("charging station identity must not contain ':' (A00.FR.204)")
426            }
427            IdentityError::Control => {
428                f.write_str("charging station identity contains a control character")
429            }
430        }
431    }
432}
433
434#[cfg(feature = "std")]
435impl std::error::Error for IdentityError {}
436
437// ---------------------------------------------------------------------------
438// MessageId
439// ---------------------------------------------------------------------------
440
441/// The maximum length of an OCPP-J message id, in characters (Part 4 §4.1.1).
442pub const MESSAGE_ID_MAX_LEN: usize = 36;
443
444/// An OCPP-J `MessageId` (1.6J calls it `UniqueId`): a string of at most 36 characters that
445/// correlates a `CALL` with its `CALLRESULT` / `CALLERROR`.
446#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
447#[serde(transparent)]
448pub struct MessageId(String);
449
450impl MessageId {
451    /// Validates and wraps a message id.
452    pub fn new(value: impl Into<String>) -> Result<Self, MessageIdError> {
453        let value = value.into();
454        if value.is_empty() {
455            return Err(MessageIdError::Empty);
456        }
457        let len = value.chars().count();
458        if len > MESSAGE_ID_MAX_LEN {
459            return Err(MessageIdError::TooLong(len));
460        }
461        Ok(Self(value))
462    }
463
464    /// Wraps an id exactly as a peer sent it, including one that is too long.
465    ///
466    /// The framing layer must echo the id it received verbatim or the peer cannot correlate
467    /// the answer, so length is *reported* — see [`is_conforming`](Self::is_conforming) —
468    /// rather than silently changed.
469    #[must_use]
470    pub fn from_wire(value: &str) -> Self {
471        Self(value.to_owned())
472    }
473
474    /// Whether the id respects the 36-character limit.
475    #[must_use]
476    pub fn is_conforming(&self) -> bool {
477        !self.0.is_empty() && self.0.chars().count() <= MESSAGE_ID_MAX_LEN
478    }
479
480    /// Wraps a value, truncating it to [`MESSAGE_ID_MAX_LEN`] characters.
481    ///
482    /// For ids this peer generates, so an over-long prefix cannot produce an invalid id.
483    #[must_use]
484    pub fn truncating(value: &str) -> Self {
485        match value.char_indices().nth(MESSAGE_ID_MAX_LEN) {
486            Some((cut, _)) => Self(value[..cut].to_owned()),
487            None => Self(value.to_owned()),
488        }
489    }
490
491    /// The id OCPP 2.x prescribes when the incoming `MessageId` itself could not be read
492    /// (Part 4 §4.1.1).
493    #[must_use]
494    pub fn unreadable() -> Self {
495        Self("-1".to_owned())
496    }
497
498    /// The id as a string slice.
499    #[must_use]
500    pub fn as_str(&self) -> &str {
501        &self.0
502    }
503
504    /// Unwraps the id.
505    #[must_use]
506    pub fn into_string(self) -> String {
507        self.0
508    }
509}
510
511impl fmt::Display for MessageId {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.write_str(&self.0)
514    }
515}
516
517impl FromStr for MessageId {
518    type Err = MessageIdError;
519
520    fn from_str(value: &str) -> Result<Self, Self::Err> {
521        Self::new(value)
522    }
523}
524
525impl<'de> Deserialize<'de> for MessageId {
526    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
527        let value = String::deserialize(de)?;
528        Self::new(value).map_err(serde::de::Error::custom)
529    }
530}
531
532/// Why a message id was rejected.
533#[derive(Clone, Copy, Debug, PartialEq, Eq)]
534#[non_exhaustive]
535pub enum MessageIdError {
536    /// The id is empty.
537    Empty,
538    /// Longer than [`MESSAGE_ID_MAX_LEN`] characters.
539    TooLong(usize),
540}
541
542impl fmt::Display for MessageIdError {
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        match self {
545            MessageIdError::Empty => f.write_str("message id is empty"),
546            MessageIdError::TooLong(len) => {
547                write!(
548                    f,
549                    "message id is {len} characters, maximum is {MESSAGE_ID_MAX_LEN}"
550                )
551            }
552        }
553    }
554}
555
556#[cfg(feature = "std")]
557impl std::error::Error for MessageIdError {}
558
559/// Source of outgoing [`MessageId`]s.
560///
561/// Pluggable because constrained devices cannot afford an entropy source, and a Local
562/// Controller needs ids that provably cannot collide with the CSMS's (Part 4 §6.4).
563///
564/// # The uniqueness rule
565///
566/// Part 4 §4.1.4 is stricter than it first looks: a `MessageId` must differ from every id the
567/// same sender has used for a `CALL` or a `SEND` **on any WebSocket connection under the same
568/// Charging Station identity** — not merely within one connection. A retransmission of the
569/// same message *may* reuse its id, and nothing else may.
570pub trait IdGenerator {
571    /// Produces the next id.
572    ///
573    /// Implementations must satisfy the uniqueness rule above.
574    fn next_id(&mut self) -> MessageId;
575}
576
577/// A random generator: a version 4 UUID per id, 36 characters exactly.
578///
579/// The default wherever an entropy source is available. 122 random bits make a collision
580/// across reboots — which is what Part 4 §4.1.4 actually forbids — not worth reasoning about.
581///
582/// It also carries a counter, which only matters in the case that should never happen: if the
583/// operating system's entropy source fails, the ids fall back to being *distinct* rather than
584/// random. A repeating `MessageId` is the one outcome §4.1.4 rules out, and it is exactly what
585/// a fixed fallback value would produce.
586#[cfg(feature = "getrandom")]
587#[derive(Clone, Copy, Debug, Default)]
588pub struct RandomIds {
589    counter: u64,
590}
591
592#[cfg(feature = "getrandom")]
593impl RandomIds {
594    /// A generator drawing from the operating system's entropy source.
595    #[must_use]
596    pub fn new() -> Self {
597        Self { counter: 0 }
598    }
599}
600
601#[cfg(feature = "getrandom")]
602impl IdGenerator for RandomIds {
603    fn next_id(&mut self) -> MessageId {
604        self.counter = self.counter.wrapping_add(1);
605        MessageId(uuid_v4().unwrap_or_else(|| degraded_uuid(self.counter)))
606    }
607}
608
609/// A random version 4 UUID, in the canonical 36-character hyphenated form.
610///
611/// `None` when the operating system's entropy source failed — which on a supported target
612/// means it is not merely low on entropy but unavailable. There is no safe constant to return:
613/// two OCPP identifiers are required to be unique across a Charging Station's whole lifetime —
614/// the `MessageId` (Part 4 §4.1.4) and the `transactionId` (E01.FR.08, which spells out "even
615/// when the Charging Station is rebooted, repaired, firmware is updated etc." and recommends
616/// UUIDs by name) — so a fixed fallback would break precisely the guarantee callers came for.
617/// Callers that must produce *something* use a counter instead; see [`RandomIds`].
618#[cfg(feature = "getrandom")]
619#[must_use]
620pub fn uuid_v4() -> Option<String> {
621    let mut bytes = [0u8; 16];
622    getrandom::fill(&mut bytes).ok()?;
623    bytes[6] = (bytes[6] & 0x0F) | 0x40; // version 4
624    bytes[8] = (bytes[8] & 0x3F) | 0x80; // variant RFC 4122
625    Some(hyphenate(bytes))
626}
627
628/// A UUID-shaped id built from a counter, for the case where entropy is unavailable.
629///
630/// Version 4 is *not* claimed — the version nibble is `8`, which no RFC 4122 version uses —
631/// so a reader can tell at a glance that these ids are unique within a process run and nothing
632/// more. Across a reboot they repeat, which is why this is a last resort and not a mode.
633#[cfg(feature = "getrandom")]
634#[must_use]
635fn degraded_uuid(counter: u64) -> String {
636    let mut bytes = [0u8; 16];
637    bytes[..8].copy_from_slice(&counter.to_be_bytes());
638    bytes[6] = (bytes[6] & 0x0F) | 0x80;
639    bytes[8] = (bytes[8] & 0x3F) | 0x80;
640    hyphenate(bytes)
641}
642
643/// Renders 16 bytes as `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`.
644#[cfg(feature = "getrandom")]
645fn hyphenate(bytes: [u8; 16]) -> String {
646    const HEX: &[u8; 16] = b"0123456789abcdef";
647    let mut out = [0u8; 36];
648    let mut index = 0;
649    for (position, byte) in bytes.iter().enumerate() {
650        if matches!(position, 4 | 6 | 8 | 10) {
651            out[index] = b'-';
652            index += 1;
653        }
654        out[index] = HEX[usize::from(byte >> 4)];
655        out[index + 1] = HEX[usize::from(byte & 0x0F)];
656        index += 2;
657    }
658    // Every byte written is ASCII hex or `-`.
659    core::str::from_utf8(&out)
660        .unwrap_or("00000000-0000-8000-8000-000000000000")
661        .to_owned()
662}
663
664/// A counter-based generator: `<prefix><counter>`, base-36 encoded.
665///
666/// For targets with no entropy source. It satisfies Part 4 §4.1.4 **only if the prefix is
667/// different on every boot** — a persisted boot counter, a serial number plus a session
668/// number, anything that does not repeat. With a constant prefix the ids restart at zero
669/// after a power cut and collide with the ones used before it, which is exactly what §4.1.4
670/// forbids and what makes a CSMS mismatch a response to the wrong request.
671///
672/// A Local Controller uses the prefix for a second purpose: keeping its own ids disjoint from
673/// the CSMS's (Part 4 §6.4).
674#[derive(Clone, Debug)]
675pub struct CounterIds {
676    prefix: String,
677    next: u64,
678}
679
680impl CounterIds {
681    /// Starts a generator with the given prefix. Read the type's documentation first: the
682    /// prefix is what makes the ids unique across reboots.
683    #[must_use]
684    pub fn with_prefix(prefix: impl Into<String>) -> Self {
685        Self {
686            prefix: prefix.into(),
687            next: 0,
688        }
689    }
690}
691
692impl Default for CounterIds {
693    fn default() -> Self {
694        Self::with_prefix("")
695    }
696}
697
698impl IdGenerator for CounterIds {
699    fn next_id(&mut self) -> MessageId {
700        let value = self.next;
701        self.next = self.next.wrapping_add(1);
702        let mut digits = [0u8; 13];
703        let mut index = digits.len();
704        let mut remaining = value;
705        loop {
706            index -= 1;
707            let digit = u8::try_from(remaining % 36).unwrap_or(0);
708            digits[index] = if digit < 10 {
709                b'0' + digit
710            } else {
711                b'a' + digit - 10
712            };
713            remaining /= 36;
714            if remaining == 0 {
715                break;
716            }
717        }
718        let suffix = core::str::from_utf8(&digits[index..]).unwrap_or("0");
719        MessageId::truncating(&format!("{}{suffix}", self.prefix))
720    }
721}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726
727    #[test]
728    fn a_strict_date_time_needs_the_t_separator() {
729        assert!(DateTime::parse("2026-11-07T12:00:05Z").is_ok());
730        assert!(DateTime::parse("2026-11-07t12:00:05z").is_ok()); // RFC 3339 §5.6: case-insensitive
731        assert!(DateTime::parse("2026-11-07 12:00:05Z").is_err());
732        assert_eq!(
733            DateTime::parse_lenient("2026-11-07 12:00:05Z").unwrap(),
734            DateTime::parse("2026-11-07T12:00:05Z").unwrap()
735        );
736    }
737
738    #[test]
739    fn identity_rejects_colon_per_a00_fr_204() {
740        assert_eq!(Identity::new("cs:1"), Err(IdentityError::Colon));
741        assert!(Identity::new("CS-0001").is_ok());
742        assert_eq!(
743            Identity::new("x".repeat(49)),
744            Err(IdentityError::TooLong(49))
745        );
746    }
747
748    #[test]
749    fn message_id_truncates_to_36_characters() {
750        let id = MessageId::truncating(&"a".repeat(80));
751        assert_eq!(id.as_str().chars().count(), 36);
752    }
753
754    #[test]
755    fn counter_ids_are_unique_and_prefixed() {
756        let mut ids = CounterIds::with_prefix("lc-");
757        assert_eq!(ids.next_id().as_str(), "lc-0");
758        assert_eq!(ids.next_id().as_str(), "lc-1");
759        for _ in 0..40 {
760            ids.next_id();
761        }
762        assert_eq!(ids.next_id().as_str(), "lc-16");
763    }
764
765    #[cfg(feature = "getrandom")]
766    #[test]
767    fn random_ids_are_uuids_and_do_not_repeat() {
768        let mut ids = RandomIds::new();
769        let mut seen = std::collections::HashSet::new();
770        for _ in 0..256 {
771            let id = ids.next_id();
772            assert_eq!(id.as_str().len(), 36, "{id}");
773            assert!(id.is_conforming());
774            assert_eq!(&id.as_str()[14..15], "4", "version nibble: {id}");
775            assert!(seen.insert(id.into_string()));
776        }
777    }
778
779    #[test]
780    fn datetime_leniency_matches_field_behaviour() {
781        assert!(DateTime::parse("2024-01-01T10:00:00").is_err());
782        assert_eq!(
783            DateTime::parse_lenient("2024-01-01T10:00:00").unwrap(),
784            DateTime::parse("2024-01-01T10:00:00Z").unwrap()
785        );
786        assert_eq!(
787            DateTime::parse_lenient("2024-01-01 10:00:00").unwrap(),
788            DateTime::parse("2024-01-01T10:00:00Z").unwrap()
789        );
790        assert_eq!(
791            DateTime::parse_lenient("2024-01-01T10:00:00+02:00").unwrap(),
792            DateTime::parse("2024-01-01T08:00:00Z").unwrap()
793        );
794    }
795}