1macro_rules! enum_builder {
3 ($(#[$comment:meta])* @U8 $($enum:tt)+) => {
4 enum_builder!(u8: $(#[$comment])* $($enum)+);
5 };
6 ($(#[$comment:meta])* @U16 $($enum:tt)+) => {
7 enum_builder!(u16: $(#[$comment])* $($enum)+);
8 };
9 (
10 $uint:ty:
11 $(#[$comment:meta])*
12 $enum_vis:vis enum $enum_name:ident
13 { $( $enum_var: ident => $enum_val: expr ),* $(,)? }
14 ) => {
15 $(#[$comment])*
16 #[non_exhaustive]
17 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
18 $enum_vis enum $enum_name {
19 $( $enum_var),*
20 ,Unknown($uint)
21 }
22
23 impl $enum_name {
24 #[allow(dead_code)]
26 $enum_vis fn to_array(self) -> [u8; core::mem::size_of::<$uint>()] {
27 <$uint>::from(self).to_be_bytes()
28 }
29
30 #[allow(dead_code)]
32 $enum_vis fn as_str(&self) -> Option<&'static str> {
33 match self {
34 $( $enum_name::$enum_var => Some(stringify!($enum_var))),*
35 ,$enum_name::Unknown(_) => None,
36 }
37 }
38 }
39
40 impl Codec<'_> for $enum_name {
41 #[allow(unused_qualifications)]
43 fn encode(&self, bytes: &mut alloc::vec::Vec<u8>) {
44 <$uint>::from(*self).encode(bytes);
45 }
46
47 fn read(r: &mut Reader<'_>) -> Result<Self, crate::error::InvalidMessage> {
48 match <$uint>::read(r) {
49 Ok(x) => Ok($enum_name::from(x)),
50 Err(_) => Err(crate::error::InvalidMessage::MissingData(stringify!($enum_name))),
51 }
52 }
53 }
54
55 impl From<$uint> for $enum_name {
56 fn from(x: $uint) -> Self {
57 match x {
58 $($enum_val => $enum_name::$enum_var),*
59 , x => $enum_name::Unknown(x),
60 }
61 }
62 }
63
64 impl From<$enum_name> for $uint {
65 fn from(value: $enum_name) -> Self {
66 match value {
67 $( $enum_name::$enum_var => $enum_val),*
68 ,$enum_name::Unknown(x) => x
69 }
70 }
71 }
72 };
73}