1use std::borrow::Cow;
9use std::fmt;
10
11use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
12use serde::de::{self, Deserializer};
13use serde::{Deserialize, Serialize, Serializer};
14
15use super::tls::{base32_lower, lk_identity_for};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct NameError {
20 what: &'static str,
21 grammar: &'static str,
22}
23
24impl fmt::Display for NameError {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 write!(f, "not a valid {} ({})", self.what, self.grammar)
27 }
28}
29
30impl std::error::Error for NameError {}
31
32fn is_b32(s: &str) -> bool {
33 s.bytes()
34 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
35}
36
37fn prefixed_b32(s: &str, prefix: &str) -> bool {
38 s.strip_prefix(prefix)
39 .is_some_and(|rest| rest.len() == 26 && is_b32(rest))
40}
41
42pub const CALL_ID_PATTERN: &str = "^r_[a-z2-7]{26}$";
44pub const JOIN_ID_PATTERN: &str = "^[0-9a-f]{32}$";
46pub const LK_IDENTITY_PATTERN: &str = "^p_[a-z2-7]{26}$";
48
49macro_rules! string_name {
50 ($(#[$m:meta])* $name:ident, $what:literal, $pattern:expr, $check:expr) => {
51 $(#[$m])*
52 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
53 pub struct $name(String);
54
55 impl $name {
56 pub fn parse(s: &str) -> Result<$name, NameError> {
58 let check: fn(&str) -> bool = $check;
59 if check(s) {
60 Ok($name(s.to_owned()))
61 } else {
62 Err(NameError { what: $what, grammar: $pattern })
63 }
64 }
65
66 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70 }
71
72 impl fmt::Debug for $name {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 write!(f, "{}({})", stringify!($name), self.0)
75 }
76 }
77
78 impl fmt::Display for $name {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 f.write_str(&self.0)
81 }
82 }
83
84 impl std::str::FromStr for $name {
85 type Err = NameError;
86 fn from_str(s: &str) -> Result<$name, NameError> {
87 $name::parse(s)
88 }
89 }
90
91 impl Serialize for $name {
92 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
93 s.serialize_str(&self.0)
94 }
95 }
96
97 impl<'de> Deserialize<'de> for $name {
98 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<$name, D::Error> {
99 let s = String::deserialize(d)?;
100 $name::parse(&s).map_err(de::Error::custom)
101 }
102 }
103
104 impl JsonSchema for $name {
105 fn inline_schema() -> bool {
106 true
107 }
108
109 fn schema_name() -> Cow<'static, str> {
110 stringify!($name).into()
111 }
112
113 fn json_schema(_: &mut SchemaGenerator) -> Schema {
114 json_schema!({
115 "type": "string",
116 "pattern": $pattern,
117 "description": concat!("A ", $what, ".")
118 })
119 }
120 }
121 };
122}
123
124string_name!(
125 CallId, "call id", CALL_ID_PATTERN, |s| prefixed_b32(s, "r_")
128);
129string_name!(
130 JoinIdHex, "join id", JOIN_ID_PATTERN, |s| s.len() == 32
132 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
133);
134string_name!(
135 LkIdentity, "engine identity", LK_IDENTITY_PATTERN, |s| prefixed_b32(s, "p_")
137);
138
139impl CallId {
140 pub fn from_random(bytes: [u8; 16]) -> CallId {
142 CallId(format!("r_{}", base32_lower(&bytes)))
143 }
144}
145
146impl JoinIdHex {
147 pub fn from_bytes(bytes: [u8; 16]) -> JoinIdHex {
149 let mut s = String::with_capacity(32);
150 for b in bytes {
151 s.push(char::from(HEX[usize::from(b >> 4)]));
152 s.push(char::from(HEX[usize::from(b & 0x0f)]));
153 }
154 JoinIdHex(s)
155 }
156
157 pub fn bytes(&self) -> [u8; 16] {
159 let mut out = [0u8; 16];
160 let raw = self.0.as_bytes();
161 for (i, o) in out.iter_mut().enumerate() {
162 *o = (nibble(raw[2 * i]) << 4) | nibble(raw[2 * i + 1]);
163 }
164 out
165 }
166
167 pub fn lk_identity(&self) -> LkIdentity {
169 LkIdentity(lk_identity_for(&self.bytes()))
170 }
171}
172
173const HEX: &[u8; 16] = b"0123456789abcdef";
174
175fn nibble(c: u8) -> u8 {
176 match c {
177 b'0'..=b'9' => c - b'0',
178 b'a'..=b'f' => c - b'a' + 10,
179 _ => 0,
180 }
181}
182
183impl LkIdentity {
184 pub fn of(join_id: &JoinIdHex) -> LkIdentity {
186 join_id.lk_identity()
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn join_id_bytes_round_trip_and_identity() {
196 let bytes = [
197 0x5b, 0x0e, 0x00, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0,
198 0xb0, 0xc0,
199 ];
200 let j = JoinIdHex::from_bytes(bytes);
201 assert_eq!(j.as_str(), "5b0e00ff102030405060708090a0b0c0");
202 assert_eq!(j.bytes(), bytes);
203 assert_eq!(JoinIdHex::parse(j.as_str()), Ok(j.clone()));
204 let id = j.lk_identity();
205 assert_eq!(id.as_str(), lk_identity_for(&bytes));
206 assert!(LkIdentity::parse(id.as_str()).is_ok());
207 }
208
209 #[test]
210 fn grammars_refuse() {
211 assert!(JoinIdHex::parse("5B0E00FF102030405060708090A0B0C0").is_err());
212 assert!(JoinIdHex::parse("5b0e").is_err());
213 assert!(CallId::parse("r_ABCDEFGHIJKLMNOPQRSTUVWXYZ").is_err());
214 assert!(CallId::parse(&format!("r_{}", "a".repeat(26))).is_ok());
215 assert!(CallId::parse(&format!("p_{}", "a".repeat(26))).is_err());
216 assert!(LkIdentity::parse(&format!("p_{}", "a".repeat(25))).is_err());
217 assert_eq!(CallId::from_random([0; 16]).as_str().len(), 28);
218 }
219}