artnet_protocol/
macros.rs

1macro_rules! data_structure {
2    (
3        $(#[$outer:meta])*
4        pub struct $name:ident {
5            $(
6                $(#[$field_meta:meta])*
7                pub $field:ident : $ty:ty,
8            )*
9        }
10    ) => {
11        $(#[$outer])*
12        pub struct $name {
13            $(
14                $(#[$field_meta])*
15                pub $field: $ty,
16            )*
17        }
18
19        impl $name {
20            /// Convert this struct to a byte array.
21            pub fn to_bytes(&self) -> crate::Result<Vec<u8>> {
22                use crate::convert::Convertable;
23                use crate::Error;
24
25                let mut result = Vec::new();
26                $(
27                    self.$field.write_to_buffer(&mut result, &self)
28                        .map_err(|e| Error::SerializeError(concat!("Could not serialize field ", stringify!($name), "::", stringify!($field)), Box::new(e)))?;
29                )*
30                Ok(result)
31            }
32
33            /// Convert a byte array to an instance of this struct.
34            pub fn from(data: &[u8]) -> crate::Result<$name> {
35                use crate::convert::Convertable;
36                use crate::Error;
37
38                let mut cursor = ::std::io::Cursor::new(data);
39                $(
40                    let $field: $ty = Convertable::<$name>::from_cursor(&mut cursor)
41                        .map_err(|e| Error::DeserializeError(concat!("Could not deserialize field ", stringify!($name), "::", stringify!($field)), Box::new(e)))?;
42                )*
43                Ok($name {
44                    $($field, )*
45                })
46            }
47        }
48
49
50        #[test]
51        fn test_encode_decode() {
52            let start = $name {
53                $(
54                    $field: crate::convert::Convertable::<$name>::get_test_value(),
55                )*
56            };
57            let bytes = start.to_bytes().expect("Could not serialize");
58            let end = $name::from(&bytes).expect("Could not deserialize");
59            $(
60                assert!(crate::convert::Convertable::<$name>::is_equal(&start.$field, &end.$field));
61            )*
62        }
63    };
64}