cubic_protocol/
packet_enum.rs

1#[macro_export]
2macro_rules! packet_enum {
3    ($(#[$meta:meta])* $name: ident, $type: ty => {
4        $($var_name: ident = $var_value: expr$(,)*)*
5    }) => {
6        $(#[$meta])*
7        pub enum $name {
8            $($var_name,)*
9        }
10
11        #[async_trait::async_trait]
12        impl $crate::packet::PacketReadable for $name {
13            async fn read(input: &mut impl $crate::packet::InputPacketBytes) ->
14                $crate::packet::PacketReadableResult<Self> {
15                let value = <$type>::read(input).await?.into();
16                Ok(match value {
17                    $($var_value => Self::$var_name,)*
18                    #[allow(unreachable_code)]
19                    _ => return Err($crate::packet::CustomError::StaticStr("Bad enum value").into())
20                })
21            }
22        }
23
24        #[async_trait::async_trait]
25        impl $crate::packet::PacketWritable for $name {
26            async fn write(self, output: &mut impl $crate::packet::OutputPacketBytes) ->
27                $crate::packet::PacketWritableResult {
28                <$type>::from(match self {
29                    $(Self::$var_name => $var_value,)*
30                }).write(output).await
31            }
32        }
33    }
34}