aboutsummaryrefslogtreecommitdiff
path: root/src/test_macros.rs
blob: cc573a70bea0b78f4d117db7078de2d51f2ade42 (plain)
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
use crate::{Serializer, SerializeResult};
#[cfg(test)]
#[macro_export]
macro_rules! packet_test_cases {
    ($pnam: ident, $varnam: ident, $bodnam: ident, $testnam: ident, $benchnams: ident, $benchnamd: ident) => {
        #[test]
        fn $testnam() {
            for _ in 0..10 {
                let packet = $pnam::$varnam($bodnam::test_gen_random());
                let mut out = BytesSerializer::default();
                packet.mc_serialize(&mut out).expect("serialize succeeds");
                let bytes = out.into_bytes();

                let raw_packet = RawPacket{
                    id: packet.id(),
                    data: bytes,
                };

                let deserialized = <$pnam>::mc_deserialize(raw_packet).expect("deserialize succeeds");
                assert_eq!(packet, deserialized);
            }
        }

        #[bench]
        fn $benchnams(b: &mut Bencher) {
            let packet = $pnam::$varnam($bodnam::test_gen_random());
            let mut serializer = BenchSerializer::default();
            packet.mc_serialize(&mut serializer).expect("serialize succeeds");
            b.bytes = serializer.len() as u64;
            serializer.reset();

            b.iter(|| {
                packet.mc_serialize(&mut serializer).expect("serialize succeeds");
                serializer.reset();
            })
        }

        #[bench]
        fn $benchnamd(b: &mut Bencher) {
            let packet = $pnam::$varnam($bodnam::test_gen_random());
            let mut serializer = BytesSerializer::default();
            packet.mc_serialize(&mut serializer).expect("serialize succeeds");

            let bytes = serializer.into_bytes();
            b.bytes = bytes.len() as u64;
            let raw_packet = RawPacket{
                id: packet.id(),
                data: bytes,
            };
            b.iter(|| {
                $pnam::mc_deserialize(raw_packet.clone()).expect("deserialize succeeds");
            })
        }
    }
}

#[cfg(test)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BenchSerializer {
    data: Vec<u8>
}

#[cfg(test)]
impl Serializer for BenchSerializer {
    fn serialize_bytes(&mut self, data: &[u8]) -> SerializeResult {
        self.data.extend_from_slice(data);
        Ok(())
    }
}

#[cfg(test)]
impl BenchSerializer {
    pub fn reset(&mut self) {
        self.data.clear();
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }
}