Cotton code
39 lines · 1.3 KB · RustRaw
/// A closed set of words as an enum: `as_str`, `ALL` in declared order,/// `parse`, `Display`, serde by the words. The caller has serde's/// `Serialize` and `Deserialize` in scope.#[macro_export]macro_rules! string_enum {    (@unit $variant:ident) => { () };    (        $(#[$meta:meta])*        $name:ident {            $( $(#[$variant_meta:meta])* $variant:ident => $text:literal ),+ $(,)?        }    ) => {        $(#[$meta])*        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]        pub enum $name {            $( $(#[$variant_meta])* #[serde(rename = $text)] $variant ),+        }        impl $name {            pub const fn as_str(self) -> &'static str {                match self { $( $name::$variant => $text ),+ }            }            /// In the TypeScript's declared order.            pub const ALL: [$name; [$($crate::string_enum!(@unit $variant)),+].len()] =                [$( $name::$variant ),+];            pub fn parse(value: &str) -> Option<Self> {                Self::ALL.into_iter().find(|kind| kind.as_str() == value)            }        }        impl std::fmt::Display for $name {            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {                f.write_str(self.as_str())            }        }    };}