macro_rules! code_enum {
(
$(#[$meta:meta])*
$name:ident {
$( $(#[$vmeta:meta])* $variant:ident = $code:literal => $text:literal ),* $(,)?
}
) => {
$(#[$meta])*
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(u8)]
pub enum $name {
$( $(#[$vmeta])* $variant = $code ),*
}
impl $name {
pub const ALL: &'static [$name] = &[ $( $name::$variant ),* ];
#[must_use]
pub const fn from_code(code: u8) -> Option<Self> {
match code {
$( $code => Some($name::$variant), )*
_ => None,
}
}
#[must_use]
pub const fn code(self) -> u8 {
self as u8
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
$( $name::$variant => $text, )*
}
}
}
impl core::fmt::Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.name())
}
}
};
}
macro_rules! index_type {
(
$(#[$meta:meta])*
$name:ident($inner:ty) => $prefix:literal
) => {
$(#[$meta])*
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
pub struct $name(pub $inner);
impl $name {
#[must_use]
#[inline]
pub const fn index(self) -> usize {
self.0 as usize
}
}
impl core::fmt::Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, concat!($prefix, "{}"), self.0)
}
}
};
}