rustls/msgs/
macros.rs

1/// A macro which defines an enum type.
2macro_rules! enum_builder {
3    (
4    $(#[$comment:meta])*
5    @U8
6        EnumName: $enum_name: ident;
7        EnumVal { $( $enum_var: ident => $enum_val: expr ),* }
8    ) => {
9        $(#[$comment])*
10        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
11        pub enum $enum_name {
12            $( $enum_var),*
13            ,Unknown(u8)
14        }
15        impl $enum_name {
16            pub fn get_u8(&self) -> u8 {
17                let x = self.clone();
18                match x {
19                    $( $enum_name::$enum_var => $enum_val),*
20                    ,$enum_name::Unknown(x) => x
21                }
22            }
23        }
24        impl Codec for $enum_name {
25            fn encode(&self, bytes: &mut Vec<u8>) {
26                self.get_u8().encode(bytes);
27            }
28
29            fn read(r: &mut Reader) -> Option<Self> {
30                Some(match u8::read(r) {
31                    None => return None,
32                    $( Some($enum_val) => $enum_name::$enum_var),*
33                    ,Some(x) => $enum_name::Unknown(x)
34                })
35            }
36        }
37    };
38    (
39    $(#[$comment:meta])*
40    @U16
41        EnumName: $enum_name: ident;
42        EnumVal { $( $enum_var: ident => $enum_val: expr ),* }
43    ) => {
44        $(#[$comment])*
45        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
46        pub enum $enum_name {
47            $( $enum_var),*
48            ,Unknown(u16)
49        }
50        impl $enum_name {
51            pub fn get_u16(&self) -> u16 {
52                let x = self.clone();
53                match x {
54                    $( $enum_name::$enum_var => $enum_val),*
55                    ,$enum_name::Unknown(x) => x
56                }
57            }
58        }
59        impl Codec for $enum_name {
60            fn encode(&self, bytes: &mut Vec<u8>) {
61                self.get_u16().encode(bytes);
62            }
63
64            fn read(r: &mut Reader) -> Option<Self> {
65                Some(match u16::read(r) {
66                    None => return None,
67                    $( Some($enum_val) => $enum_name::$enum_var),*
68                    ,Some(x) => $enum_name::Unknown(x)
69                })
70            }
71        }
72    };
73}