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