icedwright-types 0.1.0

Shared types for icedwright: roles and capabilities, pixel units, virtual time, frames, key chords and the Messages trait
Documentation
//! The [`Messages`] trait, which `#[derive(Messages)]` implements on an app's message enum so
//! that coverage knows every variant that could have been received.

use std::borrow::Cow;
use std::fmt;

/// A message variant's path, such as `Save` or, for a nested enum, `Editor::Bold`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct VariantPath(Cow<'static, str>);

impl VariantPath {
    /// A path from a static name, usable in a `static` table.
    #[must_use]
    pub const fn new(path: &'static str) -> Self {
        Self(Cow::Borrowed(path))
    }

    /// `outer::inner`, for a variant of a nested message enum.
    #[must_use]
    pub fn nested(outer: &str, inner: &VariantPath) -> Self {
        Self(Cow::Owned(format!("{outer}::{}", inner.0)))
    }

    /// The path as written, segments joined by `::`.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The segments from the outermost variant inwards.
    pub fn segments(&self) -> impl Iterator<Item = &str> {
        self.0.split("::")
    }
}

impl fmt::Display for VariantPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for VariantPath {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Every variant of a message type, known at compile time.
///
/// Implemented by `#[derive(Messages)]` from `icedwright-probe`, which is applied in production
/// code: it adds a table of variant names and a `match` from each variant to its index.
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not implement `Messages`",
    note = "add `#[derive(icedwright_probe::Messages)]` to the message enum"
)]
pub trait Messages {
    /// Every variant, nested ones as `Editor::Bold`, in declaration order.
    fn variants() -> &'static [VariantPath];

    /// This value's variant.
    fn variant(&self) -> VariantPath;

    /// The position of [`Messages::variant`] in [`Messages::variants`], for dense coverage
    /// tables.
    fn variant_index(&self) -> usize;
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::LazyLock;

    /// What the derive generates for a flat enum.
    enum Inner {
        Bold,
        Italic,
    }

    static INNER: [VariantPath; 2] = [VariantPath::new("Bold"), VariantPath::new("Italic")];

    impl Messages for Inner {
        fn variants() -> &'static [VariantPath] {
            &INNER
        }

        fn variant(&self) -> VariantPath {
            INNER[self.variant_index()].clone()
        }

        fn variant_index(&self) -> usize {
            match self {
                Inner::Bold => 0,
                Inner::Italic => 1,
            }
        }
    }

    /// What the derive generates for an enum with a nested variant.
    enum Outer {
        Save,
        Editor(Inner),
    }

    static OUTER: LazyLock<Vec<VariantPath>> = LazyLock::new(|| {
        let mut all = vec![VariantPath::new("Save")];
        all.extend(
            Inner::variants()
                .iter()
                .map(|inner| VariantPath::nested("Editor", inner)),
        );
        all
    });

    impl Messages for Outer {
        fn variants() -> &'static [VariantPath] {
            &OUTER
        }

        fn variant(&self) -> VariantPath {
            match self {
                Outer::Save => VariantPath::new("Save"),
                Outer::Editor(inner) => VariantPath::nested("Editor", &inner.variant()),
            }
        }

        fn variant_index(&self) -> usize {
            match self {
                Outer::Save => 0,
                Outer::Editor(inner) => 1 + inner.variant_index(),
            }
        }
    }

    #[test]
    fn flat_and_nested_variants() {
        let names: Vec<&str> = Outer::variants().iter().map(VariantPath::as_str).collect();
        assert_eq!(names, ["Save", "Editor::Bold", "Editor::Italic"]);
        let message = Outer::Editor(Inner::Italic);
        assert_eq!(message.variant().as_str(), "Editor::Italic");
        assert_eq!(
            Outer::variants()[message.variant_index()],
            message.variant()
        );
        assert_eq!(Outer::Save.variant_index(), 0);
        assert_eq!(Inner::Bold.variant(), VariantPath::new("Bold"));
    }

    #[test]
    fn paths_split_into_segments_and_print() {
        let path = VariantPath::nested("Editor", &VariantPath::new("Bold"));
        assert_eq!(path.segments().collect::<Vec<_>>(), ["Editor", "Bold"]);
        assert_eq!(path.to_string(), "Editor::Bold");
        assert_eq!(path.as_ref(), "Editor::Bold");
        assert!(VariantPath::new("A") < VariantPath::new("B"));
    }
}