1use core::fmt;
18use core::hash::{Hash, Hasher};
19use core::str::FromStr;
20
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22
23#[derive(Clone, Copy)]
41pub struct Id {
42 bytes: [u8; Id::MAX_LEN],
43 len: u8,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
48pub enum InvalidId {
49 #[error("an S2 identifier must be at least {} characters", Id::MIN_LEN)]
51 TooShort,
52 #[error("an S2 identifier must be at most {} characters", Id::MAX_LEN)]
54 TooLong,
55 #[error("an S2 identifier may only contain [a-zA-Z0-9-_:], found {found:?} at byte {index}")]
57 IllegalCharacter {
58 found: char,
60 index: usize,
62 },
63}
64
65impl Id {
66 pub const MAX_LEN: usize = 64;
68 pub const MIN_LEN: usize = 2;
70
71 #[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 #[allow(clippy::cast_possible_truncation)] 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 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)] Ok(Self {
105 bytes,
106 len: raw.len() as u8,
107 })
108 }
109
110 #[must_use]
116 #[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 #[must_use]
144 pub fn as_str(&self) -> &str {
145 let used = self.bytes.get(..self.len as usize).unwrap_or(&[]);
146 core::str::from_utf8(used).unwrap_or("")
149 }
150
151 #[must_use]
153 pub fn len(&self) -> usize {
154 self.len as usize
155 }
156
157 #[must_use]
159 pub fn is_empty(&self) -> bool {
160 false
161 }
162
163 #[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 #[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 #[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 #[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 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 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 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 assert_eq!(core::mem::size_of::<Id>(), 65);
419 let a = Id::parse("actuator1").unwrap();
420 let b = a; assert_eq!(a, b);
422 }
423}