Skip to main content

nifty_runtime/
coded.rs

1//! Enums compiled apps store by number.
2
3/// Declares a fieldless enum whose variants have stable numeric codes, numbered in
4/// declaration order, which is how compiled apps store styles.
5macro_rules! coded_enum {
6    (
7        $(#[$meta:meta])*
8        pub enum $name:ident {
9            $($(#[$variant_meta:meta])* $variant:ident,)+
10        }
11    ) => {
12        $(#[$meta])*
13        #[repr(u8)]
14        pub enum $name {
15            $($(#[$variant_meta])* $variant,)+
16        }
17
18        impl $name {
19            pub const ALL: &[Self] = &[$(Self::$variant,)+];
20
21            #[must_use]
22            pub fn code(self) -> u8 {
23                self as u8
24            }
25
26            #[must_use]
27            pub fn from_code(code: u8) -> Option<Self> {
28                Self::ALL.get(usize::from(code)).copied()
29            }
30        }
31    };
32}