Skip to main content

capsid_protocol/
names.rs

1// Declares a fieldless enum whose serde names, `as_str`, `from_name`, and
2// `Display` come from one table, so the wire names and the text cannot drift
3// apart. The enum must derive `Serialize` and `Deserialize`.
4#[macro_export]
5macro_rules! named_enum {
6    (
7        $(#[$meta:meta])*
8        $vis:vis enum $name:ident {
9            $(
10                $(#[$variant_meta:meta])*
11                $variant:ident = $text:literal
12            ),+ $(,)?
13        }
14    ) => {
15        $(#[$meta])*
16        $vis enum $name {
17            $(
18                $(#[$variant_meta])*
19                #[serde(rename = $text)]
20                $variant,
21            )+
22        }
23
24        impl $name {
25            pub fn as_str(self) -> &'static str {
26                match self {
27                    $(Self::$variant => $text,)+
28                }
29            }
30
31            pub fn from_name(name: &str) -> Option<Self> {
32                match name {
33                    $($text => Some(Self::$variant),)+
34                    _ => None,
35                }
36            }
37        }
38
39        impl ::std::fmt::Display for $name {
40            fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
41                formatter.write_str(self.as_str())
42            }
43        }
44    };
45}