Skip to main content

reda_lib/
macros.rs

1#[macro_export]
2macro_rules! lib_enum {
3    (
4        $(#[$meta:meta])*
5        $name:ident, $first:ident $(, $rest:ident)* $(,)?
6    ) => {
7        paste::paste! {
8            $(#[$meta])*
9            #[derive(Debug, Clone, PartialEq, Eq, Hash)]
10            pub enum $name {
11                [<$first:camel>],
12                $([<$rest:camel>]),*
13            }
14
15            impl Default for $name {
16                fn default() -> Self {
17                    Self::[<$first:camel>]
18                }
19            }
20
21            impl std::str::FromStr for $name {
22                type Err = crate::error::LibError;
23                fn from_str(s: &str) -> Result<Self, Self::Err> {
24                    match s {
25                        stringify!($first) => Ok(Self::[<$first:camel>]),
26                        $(stringify!($rest) => Ok(Self::[<$rest:camel>])),*,
27                        _ => Err(crate::error::LibError::UnsupportEnumValue(stringify!($name), s.to_string())),
28                    }
29                }
30            }
31
32            impl std::fmt::Display for $name {
33                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34                    match self {
35                        Self::[<$first:camel>] => write!(f, stringify!($first)),
36                        $(Self::[<$rest:camel>] => write!(f, stringify!($rest))),*,
37                    }
38                }
39            }
40        }
41    };
42}
43