Skip to main content

icedwright_types/
messages.rs

1//! The [`Messages`] trait, which `#[derive(Messages)]` implements on an app's message enum so
2//! that coverage knows every variant that could have been received.
3
4use std::borrow::Cow;
5use std::fmt;
6
7/// A message variant's path, such as `Save` or, for a nested enum, `Editor::Bold`.
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10#[cfg_attr(feature = "serde", serde(transparent))]
11pub struct VariantPath(Cow<'static, str>);
12
13impl VariantPath {
14    /// A path from a static name, usable in a `static` table.
15    #[must_use]
16    pub const fn new(path: &'static str) -> Self {
17        Self(Cow::Borrowed(path))
18    }
19
20    /// `outer::inner`, for a variant of a nested message enum.
21    #[must_use]
22    pub fn nested(outer: &str, inner: &VariantPath) -> Self {
23        Self(Cow::Owned(format!("{outer}::{}", inner.0)))
24    }
25
26    /// The path as written, segments joined by `::`.
27    #[must_use]
28    pub fn as_str(&self) -> &str {
29        &self.0
30    }
31
32    /// The segments from the outermost variant inwards.
33    pub fn segments(&self) -> impl Iterator<Item = &str> {
34        self.0.split("::")
35    }
36}
37
38impl fmt::Display for VariantPath {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(&self.0)
41    }
42}
43
44impl AsRef<str> for VariantPath {
45    fn as_ref(&self) -> &str {
46        &self.0
47    }
48}
49
50/// Every variant of a message type, known at compile time.
51///
52/// Implemented by `#[derive(Messages)]` from `icedwright-probe`, which is applied in production
53/// code: it adds a table of variant names and a `match` from each variant to its index.
54#[diagnostic::on_unimplemented(
55    message = "`{Self}` does not implement `Messages`",
56    note = "add `#[derive(icedwright_probe::Messages)]` to the message enum"
57)]
58pub trait Messages {
59    /// Every variant, nested ones as `Editor::Bold`, in declaration order.
60    fn variants() -> &'static [VariantPath];
61
62    /// This value's variant.
63    fn variant(&self) -> VariantPath;
64
65    /// The position of [`Messages::variant`] in [`Messages::variants`], for dense coverage
66    /// tables.
67    fn variant_index(&self) -> usize;
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use std::sync::LazyLock;
74
75    /// What the derive generates for a flat enum.
76    enum Inner {
77        Bold,
78        Italic,
79    }
80
81    static INNER: [VariantPath; 2] = [VariantPath::new("Bold"), VariantPath::new("Italic")];
82
83    impl Messages for Inner {
84        fn variants() -> &'static [VariantPath] {
85            &INNER
86        }
87
88        fn variant(&self) -> VariantPath {
89            INNER[self.variant_index()].clone()
90        }
91
92        fn variant_index(&self) -> usize {
93            match self {
94                Inner::Bold => 0,
95                Inner::Italic => 1,
96            }
97        }
98    }
99
100    /// What the derive generates for an enum with a nested variant.
101    enum Outer {
102        Save,
103        Editor(Inner),
104    }
105
106    static OUTER: LazyLock<Vec<VariantPath>> = LazyLock::new(|| {
107        let mut all = vec![VariantPath::new("Save")];
108        all.extend(
109            Inner::variants()
110                .iter()
111                .map(|inner| VariantPath::nested("Editor", inner)),
112        );
113        all
114    });
115
116    impl Messages for Outer {
117        fn variants() -> &'static [VariantPath] {
118            &OUTER
119        }
120
121        fn variant(&self) -> VariantPath {
122            match self {
123                Outer::Save => VariantPath::new("Save"),
124                Outer::Editor(inner) => VariantPath::nested("Editor", &inner.variant()),
125            }
126        }
127
128        fn variant_index(&self) -> usize {
129            match self {
130                Outer::Save => 0,
131                Outer::Editor(inner) => 1 + inner.variant_index(),
132            }
133        }
134    }
135
136    #[test]
137    fn flat_and_nested_variants() {
138        let names: Vec<&str> = Outer::variants().iter().map(VariantPath::as_str).collect();
139        assert_eq!(names, ["Save", "Editor::Bold", "Editor::Italic"]);
140        let message = Outer::Editor(Inner::Italic);
141        assert_eq!(message.variant().as_str(), "Editor::Italic");
142        assert_eq!(
143            Outer::variants()[message.variant_index()],
144            message.variant()
145        );
146        assert_eq!(Outer::Save.variant_index(), 0);
147        assert_eq!(Inner::Bold.variant(), VariantPath::new("Bold"));
148    }
149
150    #[test]
151    fn paths_split_into_segments_and_print() {
152        let path = VariantPath::nested("Editor", &VariantPath::new("Bold"));
153        assert_eq!(path.segments().collect::<Vec<_>>(), ["Editor", "Bold"]);
154        assert_eq!(path.to_string(), "Editor::Bold");
155        assert_eq!(path.as_ref(), "Editor::Bold");
156        assert!(VariantPath::new("A") < VariantPath::new("B"));
157    }
158}