Skip to main content

bus_contract/
ids.rs

1//! Validated ids: [`PointId`] and [`ListenerId`], checked when they are
2//! made, in `const` as well as at run time.
3//!
4//! The idea of ids as newtypes checked at construction comes from
5//! eventbus-contract's `Topic::new` and `ConsumerGroup::new`
6//! (<https://github.com/mapseekai/eventbus-contract>), and the `const`
7//! form that fails at compile time from qubit-event-bus's
8//! `Topic::new_static` (<https://github.com/qubit-ltd/rs-event-bus>).
9
10use std::borrow::Cow;
11use std::fmt;
12use std::ops::Deref;
13
14/// Why an id was refused ([`check_id`]).
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum IdError {
18    /// The id is empty.
19    Empty,
20    /// The id has no `<crate>.` prefix: it has one segment only.
21    NoPrefix,
22    /// A segment between two dots, or at either end, is empty
23    /// (`a..b`, `a.`, `.a`); `at` is the byte where it is.
24    EmptySegment {
25        /// The byte offset of the empty segment.
26        at: usize,
27    },
28    /// The byte at `at` is not allowed there.
29    BadChar {
30        /// The byte offset of the character.
31        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
53/// Checks `id` against the naming rule of point and listener ids,
54/// `<crate>.<subject>.<moment>` (the README's "Naming points"):
55///
56/// - at least two segments separated by dots, none empty;
57/// - the first segment, the crate's prefix, is a lowercase ASCII letter
58///   followed by lowercase ASCII letters, digits, `_` or `-`;
59/// - the other segments are ASCII letters (either case), digits, `_` or
60///   `-`.
61///
62/// A `const fn`, so a table checks its ids at compile time.
63pub 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
99/// Panics with the error's message: a `const` caller turns it into a
100/// compile error.
101const 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/// A point's id ([`Point::ID`](crate::Point::ID)), checked when made
115/// against the naming rule ([`check_id`]): `<crate>.<subject>.<moment>`.
116///
117/// Made in a `const`, an invalid id is a compile error:
118///
119/// ```
120/// use bus_contract::PointId;
121/// const ID: PointId = PointId::new("doc.close");
122/// assert_eq!(ID, "doc.close");
123/// ```
124///
125/// ```compile_fail
126/// use bus_contract::PointId;
127/// const ID: PointId = PointId::new("close"); // no `<crate>.` prefix
128/// ```
129///
130/// It reads as a `&str` ([`Deref`], [`PointId::as_str`], comparisons
131/// with `str`). Newtype ids checked at construction follow
132/// eventbus-contract (<https://github.com/mapseekai/eventbus-contract>);
133/// the `const` constructor follows qubit-event-bus's `Topic::new_static`
134/// (<https://github.com/qubit-ltd/rs-event-bus>).
135#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
136pub struct PointId(&'static str);
137
138impl PointId {
139    /// The id `id`, checked; panics when it breaks the naming rule, so a
140    /// `const` with a bad id does not compile. [`PointId::try_new`]
141    /// returns the error instead.
142    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    /// The id `id`, or why it breaks the naming rule.
150    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    /// The id as a string.
158    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/// A listener's id, checked when made against the naming rule
238/// ([`check_id`]): `<crate>.<what>` (`docs.autosave`), so the order
239/// dump of a point shows who each listener belongs to.
240///
241/// [`ListenerId::new`] is `const` and panics on a bad id, so a `const`
242/// with one does not compile; [`ListenerId::try_new`] checks an id made
243/// at run time. The typed `listen` calls still take any
244/// `impl Into<String>`, a `ListenerId` or a `&str`: the bus checks the id
245/// when the listener registers and refuses a bad one
246/// ([`Refused::BadId`](crate::Refused::BadId)).
247///
248/// ```
249/// use bus_contract::ListenerId;
250/// const SAVE: ListenerId = ListenerId::new("docs.autosave");
251/// assert!(ListenerId::try_new(format!("docs.{}", "draft")).is_ok());
252/// assert!(ListenerId::try_new("autosave").is_err());
253/// assert_eq!(SAVE, "docs.autosave");
254/// ```
255///
256/// Newtype ids checked at construction follow eventbus-contract
257/// (<https://github.com/mapseekai/eventbus-contract>); the `const`
258/// constructor follows qubit-event-bus's `Topic::new_static`
259/// (<https://github.com/qubit-ltd/rs-event-bus>).
260#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
261pub struct ListenerId(Cow<'static, str>);
262
263impl ListenerId {
264    /// The id `id`, checked; panics when it breaks the naming rule, so a
265    /// `const` with a bad id does not compile.
266    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    /// The id `id`, made at run time, or why it breaks the naming rule.
274    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    /// The id as a string.
281    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}