#[macro_export] macro_rules! define_enum {
($name:ident: $edoc:expr;
$([$tag:expr] $kind:ident $($kdoc:expr)?),*$(,)?
) => {
#[doc = $edoc]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum $name {$(
$(#[doc = $kdoc])?
$kind,
)*}
impl $name {
pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
use nom::bytes::complete::take;
let (input, ch) = take(1usize)(input)?;
let kind = match ch[0] as char {
$(
$tag => Self::$kind,
)*
_ => return Err(nom::Err::Error(
nom::error::Error::new(
input,
nom::error::ErrorKind::Tag
)
)),
};
Ok((input, kind))
}
pub fn encode(&self) -> [u8; 1] {
match self {$(
$name::$kind => [$tag as u8],
)*}
}
}
};
($name:ident $edoc:expr;
$([$tag:expr] $kind:ident $($kdoc:expr)?),*$(,)?
) => {
#[doc = $edoc]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum $name {$(
$(#[doc = $kdoc])?
$kind,
)*}
impl $name {
pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
let (input, tag) = nom::number::streaming::be_u16(input)?;
let kind = match tag {
$(
$tag => Self::$kind,
)*
_ => return Err(nom::Err::Error(
nom::error::Error::new(
input,
nom::error::ErrorKind::Tag
)
)),
};
Ok((input, kind))
}
pub fn encode(&self) -> [u8; 2] {
match self {$(
$name::$kind => $tag.to_be_bytes(),
)*}
}
}
};
($name:ident [$len:expr] $edoc:expr;
$([$tag:expr] $kind:ident $($kdoc:expr)?),*$(,)?
) => {
#[doc = $edoc]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum $name {$(
$(#[doc = $kdoc])?
$kind,
)*}
impl $name {
pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
use nom::bytes::complete::take;
let (input, chars) = take($len)(input)?;
let kind = match chars {
$(
$tag => Self::$kind,
)*
_ => return Err(nom::Err::Error(
nom::error::Error::new(
input,
nom::error::ErrorKind::Tag
)
)),
};
Ok((input, kind))
}
pub fn encode(&self) -> [u8; $len] {
match self {$(
$name::$kind => *$tag,
)*}
}
}
};
}