1use std::borrow::Cow;
11use std::fmt;
12use std::ops::Deref;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum IdError {
18 Empty,
20 NoPrefix,
22 EmptySegment {
25 at: usize,
27 },
28 BadChar {
30 at: usize,
32 },
33}
34
35impl fmt::Display for IdError {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 match self {
38 IdError::Empty => f.write_str("the id is empty"),
39 IdError::NoPrefix => {
40 f.write_str("the id has no `<crate>.` prefix (`<crate>.<subject>.<moment>`)")
41 }
42 IdError::EmptySegment { at } => write!(f, "the id has an empty segment at byte {at}"),
43 IdError::BadChar { at } => write!(
44 f,
45 "the id has a character not allowed at byte {at}: the prefix is `[a-z][a-z0-9_-]*`, the other segments `[A-Za-z0-9_-]+`"
46 ),
47 }
48 }
49}
50
51impl std::error::Error for IdError {}
52
53pub const fn check_id(id: &str) -> Result<(), IdError> {
64 let b = id.as_bytes();
65 if b.is_empty() {
66 return Err(IdError::Empty);
67 }
68 let mut i = 0;
69 let mut start = 0;
70 let mut segments = 1;
71 while i < b.len() {
72 let c = b[i];
73 if c == b'.' {
74 if i == start {
75 return Err(IdError::EmptySegment { at: i });
76 }
77 segments += 1;
78 start = i + 1;
79 } else if segments == 1 {
80 let ok =
81 c.is_ascii_lowercase() || (i > 0 && (c.is_ascii_digit() || c == b'_' || c == b'-'));
82 if !ok {
83 return Err(IdError::BadChar { at: i });
84 }
85 } else if !(c.is_ascii_alphanumeric() || c == b'_' || c == b'-') {
86 return Err(IdError::BadChar { at: i });
87 }
88 i += 1;
89 }
90 if segments < 2 {
91 return Err(IdError::NoPrefix);
92 }
93 if start == b.len() {
94 return Err(IdError::EmptySegment { at: b.len() });
95 }
96 Ok(())
97}
98
99const fn refuse(error: IdError) -> ! {
102 match error {
103 IdError::Empty => panic!("invalid bus id: the id is empty"),
104 IdError::NoPrefix => {
105 panic!("invalid bus id: no `<crate>.` prefix (`<crate>.<subject>.<moment>`)")
106 }
107 IdError::EmptySegment { .. } => panic!("invalid bus id: an empty segment"),
108 IdError::BadChar { .. } => panic!(
109 "invalid bus id: a character not allowed (prefix `[a-z][a-z0-9_-]*`, then `[A-Za-z0-9_-]+`)"
110 ),
111 }
112}
113
114#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
136pub struct PointId(&'static str);
137
138impl PointId {
139 pub const fn new(id: &'static str) -> PointId {
143 match check_id(id) {
144 Ok(()) => PointId(id),
145 Err(e) => refuse(e),
146 }
147 }
148
149 pub const fn try_new(id: &'static str) -> Result<PointId, IdError> {
151 match check_id(id) {
152 Ok(()) => Ok(PointId(id)),
153 Err(e) => Err(e),
154 }
155 }
156
157 pub const fn as_str(&self) -> &'static str {
159 self.0
160 }
161}
162
163impl Deref for PointId {
164 type Target = str;
165 fn deref(&self) -> &str {
166 self.0
167 }
168}
169
170impl AsRef<str> for PointId {
171 fn as_ref(&self) -> &str {
172 self.0
173 }
174}
175
176impl fmt::Display for PointId {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.write_str(self.0)
179 }
180}
181
182impl fmt::Debug for PointId {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 fmt::Debug::fmt(self.0, f)
185 }
186}
187
188impl TryFrom<&'static str> for PointId {
189 type Error = IdError;
190 fn try_from(id: &'static str) -> Result<PointId, IdError> {
191 PointId::try_new(id)
192 }
193}
194
195impl From<PointId> for &'static str {
196 fn from(id: PointId) -> &'static str {
197 id.0
198 }
199}
200
201impl From<PointId> for String {
202 fn from(id: PointId) -> String {
203 id.0.to_owned()
204 }
205}
206
207impl PartialEq<str> for PointId {
208 fn eq(&self, other: &str) -> bool {
209 self.0 == other
210 }
211}
212
213impl PartialEq<&str> for PointId {
214 fn eq(&self, other: &&str) -> bool {
215 self.0 == *other
216 }
217}
218
219impl PartialEq<PointId> for str {
220 fn eq(&self, other: &PointId) -> bool {
221 self == other.0
222 }
223}
224
225impl PartialEq<PointId> for &str {
226 fn eq(&self, other: &PointId) -> bool {
227 *self == other.0
228 }
229}
230
231impl PartialEq<PointId> for String {
232 fn eq(&self, other: &PointId) -> bool {
233 self == other.0
234 }
235}
236
237#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
261pub struct ListenerId(Cow<'static, str>);
262
263impl ListenerId {
264 pub const fn new(id: &'static str) -> ListenerId {
267 match check_id(id) {
268 Ok(()) => ListenerId(Cow::Borrowed(id)),
269 Err(e) => refuse(e),
270 }
271 }
272
273 pub fn try_new(id: impl Into<String>) -> Result<ListenerId, IdError> {
275 let id = id.into();
276 check_id(&id)?;
277 Ok(ListenerId(Cow::Owned(id)))
278 }
279
280 pub fn as_str(&self) -> &str {
282 &self.0
283 }
284}
285
286impl Deref for ListenerId {
287 type Target = str;
288 fn deref(&self) -> &str {
289 &self.0
290 }
291}
292
293impl AsRef<str> for ListenerId {
294 fn as_ref(&self) -> &str {
295 &self.0
296 }
297}
298
299impl fmt::Display for ListenerId {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301 f.write_str(&self.0)
302 }
303}
304
305impl fmt::Debug for ListenerId {
306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 fmt::Debug::fmt(&*self.0, f)
308 }
309}
310
311impl TryFrom<&str> for ListenerId {
312 type Error = IdError;
313 fn try_from(id: &str) -> Result<ListenerId, IdError> {
314 ListenerId::try_new(id)
315 }
316}
317
318impl TryFrom<String> for ListenerId {
319 type Error = IdError;
320 fn try_from(id: String) -> Result<ListenerId, IdError> {
321 ListenerId::try_new(id)
322 }
323}
324
325impl From<ListenerId> for String {
326 fn from(id: ListenerId) -> String {
327 id.0.into_owned()
328 }
329}
330
331impl From<&ListenerId> for String {
332 fn from(id: &ListenerId) -> String {
333 id.0.clone().into_owned()
334 }
335}
336
337impl PartialEq<str> for ListenerId {
338 fn eq(&self, other: &str) -> bool {
339 *self.0 == *other
340 }
341}
342
343impl PartialEq<&str> for ListenerId {
344 fn eq(&self, other: &&str) -> bool {
345 *self.0 == **other
346 }
347}
348
349impl PartialEq<ListenerId> for str {
350 fn eq(&self, other: &ListenerId) -> bool {
351 *self == *other.0
352 }
353}
354
355impl PartialEq<ListenerId> for String {
356 fn eq(&self, other: &ListenerId) -> bool {
357 **self == *other.0
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 #[test]
366 fn the_naming_rule() {
367 for ok in [
368 "doc.close",
369 "stack.layout.changed",
370 "bus.overBudget",
371 "egui_pop.a-b.c_d9",
372 "a1.x",
373 ] {
374 assert_eq!(check_id(ok), Ok(()), "{ok}");
375 }
376 assert_eq!(check_id(""), Err(IdError::Empty));
377 assert_eq!(check_id("close"), Err(IdError::NoPrefix));
378 assert_eq!(check_id("a..b"), Err(IdError::EmptySegment { at: 2 }));
379 assert_eq!(check_id(".a"), Err(IdError::EmptySegment { at: 0 }));
380 assert_eq!(check_id("a."), Err(IdError::EmptySegment { at: 2 }));
381 assert_eq!(check_id("Doc.close"), Err(IdError::BadChar { at: 0 }));
382 assert_eq!(check_id("1doc.close"), Err(IdError::BadChar { at: 0 }));
383 assert_eq!(check_id("doc.cl ose"), Err(IdError::BadChar { at: 6 }));
384 assert_eq!(check_id("doc.*"), Err(IdError::BadChar { at: 4 }));
385 assert_eq!(check_id("doc.é"), Err(IdError::BadChar { at: 4 }));
386 }
387
388 #[test]
389 fn newtypes_read_as_str() {
390 const P: PointId = PointId::new("doc.close");
391 assert_eq!(P, "doc.close");
392 assert_eq!(&*P, "doc.close");
393 assert_eq!(P.to_string(), "doc.close");
394 assert!(PointId::try_new("close").is_err());
395 let l = ListenerId::try_new("doc.save").unwrap();
396 assert_eq!(String::from(l.clone()), "doc.save");
397 assert_eq!(l, "doc.save");
398 }
399
400 #[test]
401 #[should_panic(expected = "invalid bus id")]
402 fn new_panics_at_run_time() {
403 let id = String::from("x");
404 let _ = ListenerId::new(Box::leak(id.into_boxed_str()));
405 }
406}