1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#[macro_export]
macro_rules! implement_composite_type {
($ty:ident { $( $field_name:ident ),+ }) => {
impl $crate::Parcel for $ty
{
fn read(read: &mut ::std::io::Read) -> Result<Self, $crate::Error> {
Ok($ty {
$( $field_name: $crate::Parcel::read(read)? ),+
})
}
fn write(&self, write: &mut ::std::io::Write) -> Result<(), $crate::Error> {
$( self.$field_name.write(write)?; )+
Ok(())
}
}
}
}
#[macro_export]
macro_rules! define_composite_type {
($ty:ident { $( $field_name:ident : $field_ty:ty ),+ }) => {
#[derive(Clone, Debug, PartialEq)]
pub struct $ty
{
$( pub $field_name : $field_ty ),+
}
implement_composite_type!($ty {
$( $field_name ),+
});
}
}
#[cfg(test)]
#[allow(unused_variables)]
mod test
{
pub use Parcel;
pub use std::io::Cursor;
#[derive(Clone, Debug, PartialEq)]
pub struct Foo
{
baz: String,
bing: i64,
}
implement_composite_type!(Foo { baz, bing });
define_composite_type!(Bar {
baz: String,
bing: i64
});
define_composite_type!(Bing {
a: u8,
b: u8,
c: u8
});
describe! composite_primitives {
before_each {
let foo = Foo { baz: "baz".to_string(), bing: 32 };
let bar = Bar { baz: "baz".to_string(), bing: 32 };
let bing = Bing { a: 3, b: 2, c: 1 };
}
describe! macros {
it "is consistent when using the different macros" {
assert_eq!(foo.raw_bytes().unwrap(), bar.raw_bytes().unwrap());
}
}
describe! writing {
it "matches the expected output" {
assert_eq!(&bing.raw_bytes().unwrap(), &[bing.a, bing.b, bing.c]);
}
}
describe! reading {
it "reads the expected value" {
let mut buffer = Cursor::new([bing.a, bing.b, bing.c]);
let read = Bing::read(&mut buffer).unwrap();
assert_eq!(read, bing);
}
}
}
}