1use std::borrow::Cow;
23use std::fmt;
24
25pub const MAX_ID_LEN: usize = 128;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct IdError {
31 pub kind: &'static str,
33 pub text: String,
34 pub reason: &'static str,
35}
36
37impl fmt::Display for IdError {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 write!(f, "`{}` is not a {}: {}", self.text, self.kind, self.reason)
40 }
41}
42
43impl std::error::Error for IdError {}
44
45pub const fn check(text: &str) -> Result<(), &'static str> {
48 let b = text.as_bytes();
49 if b.is_empty() {
50 return Err("it is empty");
51 }
52 if b.len() > MAX_ID_LEN {
53 return Err("it is longer than 128 bytes");
54 }
55 let mut i = 0;
56 while i < b.len() {
57 let c = b[i];
58 let ok = c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-' | b'/' | b':');
59 if !ok {
60 return Err("only ASCII letters, digits and `. _ - / :` are allowed");
61 }
62 i += 1;
63 }
64 Ok(())
65}
66
67pub const fn check_panel(text: &str) -> Result<(), &'static str> {
71 let b = text.as_bytes();
72 let mut hash = b.len();
73 let mut i = 0;
74 while i < b.len() {
75 if b[i] == b'#' {
76 hash = i;
77 break;
78 }
79 i += 1;
80 }
81 if hash == b.len() {
82 return check(text);
83 }
84 if b.len() > MAX_ID_LEN {
85 return Err("it is longer than 128 bytes");
86 }
87 if hash == 0 {
88 return Err("an instance's `#<n>` follows a panel's id");
89 }
90 let digits = b.len() - hash - 1;
91 if digits == 0 || digits > 9 || b[hash + 1] == b'0' {
92 return Err("an instance's `#<n>` is a number from 2, without leading zeros");
93 }
94 let mut j = hash + 1;
95 while j < b.len() {
96 if !b[j].is_ascii_digit() {
97 return Err("an instance's `#<n>` is a number from 2, without leading zeros");
98 }
99 j += 1;
100 }
101 if digits == 1 && b[hash + 1] == b'1' {
102 return Err("instance 1 is the panel itself: its id has no `#1`");
103 }
104 let mut k = 0;
106 while k < hash {
107 let c = b[k];
108 let ok = c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-' | b'/' | b':');
109 if !ok {
110 return Err("only ASCII letters, digits and `. _ - / :` are allowed");
111 }
112 k += 1;
113 }
114 Ok(())
115}
116
117macro_rules! typed_id {
118 ($(#[$doc:meta])* $name:ident) => {
119 typed_id!($(#[$doc])* $name, check);
120 };
121 ($(#[$doc:meta])* $name:ident, $check:ident) => {
122 $(#[$doc])*
123 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
124 pub struct $name(Cow<'static, str>);
125
126 impl $name {
127 pub const fn from_static(text: &'static str) -> Self {
130 match $check(text) {
131 Ok(()) => $name(Cow::Borrowed(text)),
132 Err(_) => panic!(concat!("invalid ", stringify!($name), " literal")),
133 }
134 }
135
136 pub fn new(text: impl Into<String>) -> Result<Self, IdError> {
138 let text = text.into();
139 match $check(&text) {
140 Ok(()) => Ok($name(Cow::Owned(text))),
141 Err(reason) => Err(IdError {
142 kind: stringify!($name),
143 text,
144 reason,
145 }),
146 }
147 }
148
149 pub fn as_str(&self) -> &str {
150 &self.0
151 }
152
153 pub fn join(&self, suffix: &str) -> Result<Self, IdError> {
156 Self::new(format!("{}.{suffix}", self.0))
157 }
158 }
159
160 impl fmt::Debug for $name {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 write!(f, "{}({:?})", stringify!($name), &*self.0)
163 }
164 }
165
166 impl fmt::Display for $name {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.write_str(&self.0)
169 }
170 }
171
172 impl AsRef<str> for $name {
173 fn as_ref(&self) -> &str {
174 &self.0
175 }
176 }
177
178 impl std::str::FromStr for $name {
179 type Err = IdError;
180
181 fn from_str(s: &str) -> Result<Self, IdError> {
182 Self::new(s)
183 }
184 }
185
186 impl TryFrom<&str> for $name {
187 type Error = IdError;
188
189 fn try_from(s: &str) -> Result<Self, IdError> {
190 Self::new(s)
191 }
192 }
193
194 impl TryFrom<String> for $name {
195 type Error = IdError;
196
197 fn try_from(s: String) -> Result<Self, IdError> {
198 Self::new(s)
199 }
200 }
201
202 impl serde::Serialize for $name {
203 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
204 s.serialize_str(&self.0)
205 }
206 }
207
208 impl<'de> serde::Deserialize<'de> for $name {
209 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
210 let text = String::deserialize(d)?;
211 Self::new(text).map_err(serde::de::Error::custom)
212 }
213 }
214 };
215}
216
217typed_id!(
218 CommandId
220);
221typed_id!(
222 MenuId
224);
225typed_id!(
226 PanelId,
229 check_panel
230);
231
232impl PanelId {
233 pub fn kind(&self) -> PanelId {
247 match self.0.split_once('#') {
248 Some((kind, _)) => PanelId(Cow::Owned(kind.to_string())),
249 None => self.clone(),
250 }
251 }
252
253 pub fn instance_number(&self) -> u32 {
255 self.0
256 .split_once('#')
257 .and_then(|(_, n)| n.parse().ok())
258 .unwrap_or(1)
259 }
260
261 pub fn is_instance(&self) -> bool {
264 self.0.contains('#')
265 }
266
267 pub fn instance(&self, n: u32) -> Result<PanelId, IdError> {
270 let kind = self.kind();
271 if n <= 1 {
272 return Ok(kind);
273 }
274 PanelId::new(format!("{kind}#{n}"))
275 }
276}
277typed_id!(
278 ZoneId
280);
281typed_id!(
282 BlockId
284);
285typed_id!(
286 PluginId
288);
289typed_id!(
290 OwnerId
292);
293typed_id!(
294 SettingId
296);
297
298pub const SETTINGS_PREFIX: &str = "settings/";
301
302impl SettingId {
303 pub fn path(&self) -> String {
311 format!("{SETTINGS_PREFIX}{}", self.0)
312 }
313}
314typed_id!(
315 ServiceId
317);
318typed_id!(
319 HookId
321);
322typed_id!(
323 StoryId
325);
326typed_id!(
327 StepId
330);
331
332typed_id!(
333 FrameId
336);
337typed_id!(
338 GroupId
341);
342typed_id!(
343 ScopeId
346);
347
348impl OwnerId {
349 pub const FRAMEWORK: OwnerId = OwnerId::from_static("framework");
351 pub const USER: OwnerId = OwnerId::from_static("user");
353}
354
355impl From<&PluginId> for OwnerId {
356 fn from(p: &PluginId) -> OwnerId {
357 OwnerId(p.0.clone())
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 #[test]
366 fn ids_check_their_syntax_and_round_trip_as_strings() {
367 for good in ["a", "view.palette", "app/sidebar", "x:y-z_1"] {
368 assert!(CommandId::new(good).is_ok(), "{good}");
369 }
370 for bad in ["", "a b", "é", &"x".repeat(129)] {
371 let e = CommandId::new(bad).unwrap_err();
372 assert_eq!(e.kind, "CommandId");
373 assert!(e.to_string().contains("is not a CommandId"), "{e}");
374 }
375 const Z: ZoneId = ZoneId::from_static("app.main");
376 let json = serde_json::to_string(&Z).unwrap();
377 assert_eq!(json, "\"app.main\"");
378 assert_eq!(serde_json::from_str::<ZoneId>(&json).unwrap(), Z);
379 assert!(serde_json::from_str::<ZoneId>("\"a b\"").is_err());
380 assert_eq!(format!("{Z:?}"), "ZoneId(\"app.main\")");
381 assert_eq!(Z.join("focus").unwrap().as_str(), "app.main.focus");
382 assert_eq!(
383 OwnerId::from(&PluginId::from_static("p")),
384 OwnerId::new("p").unwrap()
385 );
386 }
387}