1use std::{fmt, str::FromStr};
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Deserializer, Serialize, de};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum IdentifierKind {
9 Module,
10 ExecuteEntry,
11 ClockType,
12 ClockInstance,
13 ClockErrorCode,
14 SystemErrorCode,
15 System,
16 Backend,
17 Capability,
18}
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum InvalidIdentifierReason {
23 Empty,
24 TooLong { max_bytes: usize },
25 NonGraphicAscii,
26}
27
28#[derive(Clone, Debug, thiserror::Error)]
29#[error("invalid {kind:?} identifier: {reason:?}")]
30pub struct InvalidIdentifier {
31 pub kind: IdentifierKind,
32 pub reason: InvalidIdentifierReason,
33}
34
35fn validate_identifier(value: &str, kind: IdentifierKind) -> Result<(), InvalidIdentifier> {
36 let reason = if value.is_empty() {
37 Some(InvalidIdentifierReason::Empty)
38 } else if value.len() > 255 {
39 Some(InvalidIdentifierReason::TooLong { max_bytes: 255 })
40 } else if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
41 Some(InvalidIdentifierReason::NonGraphicAscii)
42 } else {
43 None
44 };
45
46 match reason {
47 Some(reason) => Err(InvalidIdentifier { kind, reason }),
48 None => Ok(()),
49 }
50}
51
52macro_rules! define_identifier {
53 ($name:ident, $kind:expr) => {
54 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, JsonSchema)]
55 #[serde(transparent)]
56 #[schemars(transparent)]
57 pub struct $name(
58 #[schemars(length(min = 1, max = 255), regex(pattern = r"^[!-~]+$"))] String,
59 );
60
61 impl $name {
62 pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
63 let value = value.into();
64 validate_identifier(&value, $kind)?;
65 Ok(Self(value))
66 }
67
68 pub fn as_str(&self) -> &str {
69 &self.0
70 }
71
72 pub fn into_inner(self) -> String {
73 self.0
74 }
75 }
76
77 impl AsRef<str> for $name {
78 fn as_ref(&self) -> &str {
79 self.as_str()
80 }
81 }
82
83 impl fmt::Display for $name {
84 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
85 formatter.write_str(self.as_str())
86 }
87 }
88
89 impl FromStr for $name {
90 type Err = InvalidIdentifier;
91
92 fn from_str(value: &str) -> Result<Self, Self::Err> {
93 Self::new(value)
94 }
95 }
96
97 impl<'de> Deserialize<'de> for $name {
98 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
99 where
100 D: Deserializer<'de>,
101 {
102 let value = String::deserialize(deserializer)?;
103 Self::new(value).map_err(de::Error::custom)
104 }
105 }
106 };
107}
108
109define_identifier!(ModuleId, IdentifierKind::Module);
110define_identifier!(ExecuteEntryId, IdentifierKind::ExecuteEntry);
111define_identifier!(ClockTypeId, IdentifierKind::ClockType);
112define_identifier!(ClockInstanceId, IdentifierKind::ClockInstance);
113define_identifier!(ClockErrorCode, IdentifierKind::ClockErrorCode);
114define_identifier!(SystemErrorCode, IdentifierKind::SystemErrorCode);
115define_identifier!(SystemId, IdentifierKind::System);
116define_identifier!(BackendId, IdentifierKind::Backend);
117define_identifier!(CapabilityId, IdentifierKind::Capability);