Skip to main content

s2_kit/types/
id.rs

1//! [`Id`] — the S2 identifier type.
2//!
3//! `S2J schemas/ID` defines an identifier as a **string** matching
4//! `[a-zA-Z0-9\-_:]{2,64}`. Its description says "An identifier expressed as a UUID",
5//! which is not what the pattern says and not what the standard's own examples use —
6//! the EV and heat-pump walkthroughs identify actuators as `"actuator1"` and operation
7//! modes as `"om1"`. The pattern is the contract (see erratum E1), so
8//! `Id` is a validated string and UUID generation is a convenience rather than a
9//! requirement.
10//!
11//! Because the pattern caps an identifier at 64 ASCII characters, `Id` is an inline
12//! fixed buffer: [`Copy`], allocation-free and usable without `alloc`. A Resource
13//! Manager describes its actuators once and then resolves every instruction against the
14//! identifiers it generated, so ids are copied constantly and should not be a field of
15//! `.clone()` calls.
16
17use core::fmt;
18use core::hash::{Hash, Hasher};
19use core::str::FromStr;
20
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22
23/// An S2 identifier: 2 to 64 characters of `[a-zA-Z0-9-_:]`.
24///
25/// # Examples
26///
27/// ```
28/// use s2_kit::types::Id;
29///
30/// let from_docs = Id::parse("actuator1").unwrap();
31/// assert_eq!(from_docs.as_str(), "actuator1");
32///
33/// // A compile-time constant, validated during const evaluation.
34/// const OFF: Id = Id::new_const("om1");
35/// assert_eq!(OFF.as_str(), "om1");
36///
37/// assert!(Id::parse("a").is_err()); // too short
38/// assert!(Id::parse("has space").is_err()); // illegal character
39/// ```
40#[derive(Clone, Copy)]
41pub struct Id {
42    bytes: [u8; Id::MAX_LEN],
43    len: u8,
44}
45
46/// Why a string is not a valid [`Id`].
47#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
48pub enum InvalidId {
49    /// Shorter than [`Id::MIN_LEN`].
50    #[error("an S2 identifier must be at least {} characters", Id::MIN_LEN)]
51    TooShort,
52    /// Longer than [`Id::MAX_LEN`].
53    #[error("an S2 identifier must be at most {} characters", Id::MAX_LEN)]
54    TooLong,
55    /// Contains a character outside `[a-zA-Z0-9-_:]`.
56    #[error("an S2 identifier may only contain [a-zA-Z0-9-_:], found {found:?} at byte {index}")]
57    IllegalCharacter {
58        /// The offending character.
59        found: char,
60        /// Its byte offset in the input.
61        index: usize,
62    },
63}
64
65impl Id {
66    /// The longest identifier the schema pattern allows.
67    pub const MAX_LEN: usize = 64;
68    /// The shortest identifier the schema pattern allows.
69    pub const MIN_LEN: usize = 2;
70
71    /// Whether `b` is one of the characters the pattern allows.
72    #[must_use]
73    pub const fn is_legal_byte(b: u8) -> bool {
74        b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b':'
75    }
76
77    /// Parse and validate an identifier.
78    #[allow(clippy::cast_possible_truncation)] // the length is checked against MAX_LEN first
79    pub fn parse(s: &str) -> Result<Self, InvalidId> {
80        let raw = s.as_bytes();
81        if raw.len() < Self::MIN_LEN {
82            return Err(InvalidId::TooShort);
83        }
84        if raw.len() > Self::MAX_LEN {
85            return Err(InvalidId::TooLong);
86        }
87        for (index, &b) in raw.iter().enumerate() {
88            if !Self::is_legal_byte(b) {
89                return Err(InvalidId::IllegalCharacter {
90                    // Every illegal byte is either ASCII (and so a `char`) or part of a
91                    // multi-byte sequence; reporting the replacement character for the
92                    // latter is more useful than refusing to name it at all.
93                    found: char::from_u32(u32::from(b)).unwrap_or(char::REPLACEMENT_CHARACTER),
94                    index,
95                });
96            }
97        }
98        let mut bytes = [0u8; Self::MAX_LEN];
99        bytes
100            .get_mut(..raw.len())
101            .unwrap_or(&mut [])
102            .copy_from_slice(raw);
103        #[allow(clippy::cast_possible_truncation)] // checked against MAX_LEN above
104        Ok(Self {
105            bytes,
106            len: raw.len() as u8,
107        })
108    }
109
110    /// Build an identifier during const evaluation, for literals in code.
111    ///
112    /// # Panics
113    ///
114    /// At compile time, when `s` does not match the S2 identifier pattern.
115    #[must_use]
116    // const-evaluated: a panic is a compile error, and the length is asserted above.
117    #[allow(
118        clippy::panic,
119        clippy::indexing_slicing,
120        clippy::cast_possible_truncation
121    )]
122    pub const fn new_const(s: &str) -> Self {
123        let raw = s.as_bytes();
124        assert!(raw.len() >= Self::MIN_LEN, "S2 identifier is too short");
125        assert!(raw.len() <= Self::MAX_LEN, "S2 identifier is too long");
126        let mut bytes = [0u8; Self::MAX_LEN];
127        let mut i = 0;
128        while i < raw.len() {
129            assert!(
130                Self::is_legal_byte(raw[i]),
131                "S2 identifiers may only contain [a-zA-Z0-9-_:]"
132            );
133            bytes[i] = raw[i];
134            i += 1;
135        }
136        Self {
137            bytes,
138            len: raw.len() as u8,
139        }
140    }
141
142    /// The identifier as a string slice.
143    #[must_use]
144    pub fn as_str(&self) -> &str {
145        let used = self.bytes.get(..self.len as usize).unwrap_or(&[]);
146        // Only bytes that passed `is_legal_byte` are ever stored, and all of them are
147        // ASCII, so this cannot fail.
148        core::str::from_utf8(used).unwrap_or("")
149    }
150
151    /// How many characters the identifier has.
152    #[must_use]
153    pub fn len(&self) -> usize {
154        self.len as usize
155    }
156
157    /// Always `false` — an `Id` has at least [`Id::MIN_LEN`] characters.
158    #[must_use]
159    pub fn is_empty(&self) -> bool {
160        false
161    }
162
163    /// A fresh random identifier (UUIDv4, hyphenated, lowercase).
164    #[cfg(feature = "uuid")]
165    #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
166    #[must_use]
167    pub fn generate() -> Self {
168        Self::from_uuid(uuid::Uuid::new_v4())
169    }
170
171    /// A fresh time-ordered identifier (UUIDv7, hyphenated, lowercase).
172    ///
173    /// Sortable by creation time, which makes transcripts and databases of S2 traffic
174    /// cheaper to index than the random v4 form.
175    #[cfg(all(feature = "uuid", feature = "std"))]
176    #[cfg_attr(docsrs, doc(cfg(all(feature = "uuid", feature = "std"))))]
177    #[must_use]
178    pub fn generate_v7() -> Self {
179        Self::from_uuid(uuid::Uuid::now_v7())
180    }
181
182    /// An identifier holding the hyphenated lowercase form of `uuid`.
183    #[cfg(feature = "uuid")]
184    #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
185    #[must_use]
186    pub fn from_uuid(uuid: uuid::Uuid) -> Self {
187        let mut buf = [0u8; uuid::fmt::Hyphenated::LENGTH];
188        let s = uuid.hyphenated().encode_lower(&mut buf);
189        Self::parse(s).unwrap_or(Self {
190            bytes: [b'0'; Self::MAX_LEN],
191            len: 2,
192        })
193    }
194
195    /// The identifier as a [`uuid::Uuid`], when it happens to be one.
196    ///
197    /// Returns `None` for the many legal S2 identifiers that are not UUIDs.
198    #[cfg(feature = "uuid")]
199    #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
200    #[must_use]
201    pub fn as_uuid(&self) -> Option<uuid::Uuid> {
202        uuid::Uuid::try_parse(self.as_str()).ok()
203    }
204
205    /// The all-zero UUID, which the ecosystem uses as `subject_message_id` when a
206    /// message arrived with no readable `message_id` at all.
207    ///
208    /// `S2J messages/ReceptionStatus` requires the field, and `INVALID_DATA` is defined
209    /// as the answer to a message with "no message_id found" — leaving nothing to name.
210    /// `s2-python` and `s2energy` both send the nil UUID; `[s2-json #21]` is the open
211    /// issue (erratum E10).
212    pub const NIL: Self = Self::new_const("00000000-0000-0000-0000-000000000000");
213}
214
215impl AsRef<str> for Id {
216    fn as_ref(&self) -> &str {
217        self.as_str()
218    }
219}
220
221impl core::ops::Deref for Id {
222    type Target = str;
223    fn deref(&self) -> &str {
224        self.as_str()
225    }
226}
227
228impl core::borrow::Borrow<str> for Id {
229    fn borrow(&self) -> &str {
230        self.as_str()
231    }
232}
233
234impl PartialEq for Id {
235    fn eq(&self, other: &Self) -> bool {
236        self.as_str() == other.as_str()
237    }
238}
239
240impl Eq for Id {}
241
242impl PartialEq<str> for Id {
243    fn eq(&self, other: &str) -> bool {
244        self.as_str() == other
245    }
246}
247
248impl PartialEq<&str> for Id {
249    fn eq(&self, other: &&str) -> bool {
250        self.as_str() == *other
251    }
252}
253
254impl PartialOrd for Id {
255    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
256        Some(self.cmp(other))
257    }
258}
259
260impl Ord for Id {
261    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
262        self.as_str().cmp(other.as_str())
263    }
264}
265
266impl Hash for Id {
267    fn hash<H: Hasher>(&self, state: &mut H) {
268        self.as_str().hash(state);
269    }
270}
271
272impl fmt::Display for Id {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.write_str(self.as_str())
275    }
276}
277
278impl fmt::Debug for Id {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        write!(f, "Id({:?})", self.as_str())
281    }
282}
283
284impl FromStr for Id {
285    type Err = InvalidId;
286    fn from_str(s: &str) -> Result<Self, Self::Err> {
287        Self::parse(s)
288    }
289}
290
291impl TryFrom<&str> for Id {
292    type Error = InvalidId;
293    fn try_from(s: &str) -> Result<Self, Self::Error> {
294        Self::parse(s)
295    }
296}
297
298impl Serialize for Id {
299    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
300        serializer.serialize_str(self.as_str())
301    }
302}
303
304impl<'de> Deserialize<'de> for Id {
305    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
306        struct Visitor;
307        impl serde::de::Visitor<'_> for Visitor {
308            type Value = Id;
309            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310                f.write_str("an S2 identifier matching [a-zA-Z0-9-_:]{2,64}")
311            }
312            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Id, E> {
313                Id::parse(v).map_err(E::custom)
314            }
315        }
316        deserializer.deserialize_str(Visitor)
317    }
318}
319
320#[cfg(feature = "schemars")]
321impl schemars::JsonSchema for Id {
322    fn schema_name() -> alloc::borrow::Cow<'static, str> {
323        "ID".into()
324    }
325    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
326        schemars::json_schema!({
327            "type": "string",
328            "pattern": r"[a-zA-Z0-9\-_:]{2,64}",
329        })
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn accepts_the_identifiers_the_standards_own_examples_use() {
339        // From docs `learn/examples/ev` and `learn/examples/heat-pump`. A crate that
340        // models `ID` as a UUID rejects every one of these.
341        for s in [
342            "actuator1",
343            "om1",
344            "om0",
345            "instr0",
346            "transition1",
347            "timer0",
348            "acme_ev_xxxxxx",
349            "powerConstraint1",
350            "energyconstraint1",
351            "pe_xxx",
352            "envelope1",
353            "a:b",
354            "00000000-0000-0000-0000-000000000000",
355        ] {
356            assert_eq!(Id::parse(s).unwrap().as_str(), s, "should accept {s:?}");
357        }
358    }
359
360    #[test]
361    fn rejects_what_the_pattern_rejects() {
362        assert_eq!(Id::parse("a"), Err(InvalidId::TooShort));
363        assert_eq!(Id::parse(""), Err(InvalidId::TooShort));
364        assert_eq!(Id::parse(&"x".repeat(65)), Err(InvalidId::TooLong));
365        assert!(matches!(
366            Id::parse("a b"),
367            Err(InvalidId::IllegalCharacter { index: 1, .. })
368        ));
369        assert!(matches!(
370            Id::parse("a.b"),
371            Err(InvalidId::IllegalCharacter { found: '.', .. })
372        ));
373        // The pattern is unanchored in the schema; we anchor it, so a valid prefix with
374        // an invalid tail is rejected rather than silently accepted (E1).
375        assert!(Id::parse("valid-then-\u{1F600}").is_err());
376    }
377
378    #[test]
379    fn longest_legal_identifier_round_trips() {
380        let s = "x".repeat(64);
381        let id = Id::parse(&s).unwrap();
382        assert_eq!(id.as_str(), s);
383        assert_eq!(id.len(), 64);
384    }
385
386    #[test]
387    fn ordering_and_hashing_follow_the_string() {
388        let a = Id::parse("aa").unwrap();
389        let b = Id::parse("ab").unwrap();
390        assert!(a < b);
391        assert_eq!(a, Id::parse("aa").unwrap());
392        assert_ne!(a, b);
393    }
394
395    #[test]
396    fn json_is_a_bare_string() {
397        let id = Id::parse("actuator1").unwrap();
398        let json = serde_json::to_string(&id).unwrap();
399        assert_eq!(json, "\"actuator1\"");
400        assert_eq!(serde_json::from_str::<Id>(&json).unwrap(), id);
401        assert!(serde_json::from_str::<Id>("\"a b\"").is_err());
402    }
403
404    #[cfg(feature = "uuid")]
405    #[test]
406    fn generated_identifiers_are_valid_and_unique() {
407        let a = Id::generate();
408        let b = Id::generate();
409        assert_ne!(a, b);
410        assert_eq!(a.len(), 36);
411        assert!(a.as_uuid().is_some());
412        assert!(Id::parse("actuator1").unwrap().as_uuid().is_none());
413    }
414
415    #[test]
416    fn is_copy_and_small() {
417        // 65 bytes, no allocation, no destructor: the property the whole design rests on.
418        assert_eq!(core::mem::size_of::<Id>(), 65);
419        let a = Id::parse("actuator1").unwrap();
420        let b = a; // moves nothing
421        assert_eq!(a, b);
422    }
423}