use std::borrow::Cow;
use std::fmt;
#[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 {
#[must_use]
pub const fn new(path: &'static str) -> Self {
Self(Cow::Borrowed(path))
}
#[must_use]
pub fn nested(outer: &str, inner: &VariantPath) -> Self {
Self(Cow::Owned(format!("{outer}::{}", inner.0)))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
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
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` does not implement `Messages`",
note = "add `#[derive(icedwright_probe::Messages)]` to the message enum"
)]
pub trait Messages {
fn variants() -> &'static [VariantPath];
fn variant(&self) -> VariantPath;
fn variant_index(&self) -> usize;
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::LazyLock;
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,
}
}
}
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"));
}
}