summaryrefslogtreecommitdiff
path: root/system/gd/rust/packets/test_lib.rs
blob: 960178c81db2c3394d63c08ea30d4d0a40817714 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//! reimport of generated packets (to go away once rust_genrule exists)

#![allow(clippy::all)]
#![allow(unused)]
#![allow(missing_docs)]

use std::convert::TryFrom;
use std::fmt;

pub mod test_packets {

    // Custom boolean type
    #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd, Debug)]
    pub struct Boolean {
        pub value: u8,
    }

    impl fmt::Display for Boolean {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{:02x}", self.value)
        }
    }

    #[derive(Debug, Clone)]
    pub struct InvalidBooleanError;

    impl TryFrom<&[u8]> for Boolean {
        type Error = InvalidBooleanError;

        fn try_from(slice: &[u8]) -> std::result::Result<Self, Self::Error> {
            if slice.len() != 1 || slice[0] > 1 {
                Err(InvalidBooleanError)
            } else {
                Ok(Boolean { value: slice[0] })
            }
        }
    }

    impl From<Boolean> for [u8; 1] {
        fn from(b: Boolean) -> [u8; 1] {
            [b.value]
        }
    }

    include!(concat!(env!("OUT_DIR"), "/rust_test_packets.rs"));
}

#[cfg(test)]
pub mod test {
    use crate::test_packets::*;

    #[test]
    fn test_invalid_enum_field_value() {
        // 0x0 is not a recognized Enum value.
        let input = [0x0];
        let res = TestEnumPacket::parse(&input);
        assert!(res.is_err());
    }

    #[test]
    fn test_invalid_custom_field_value() {
        // 0x2 is not a recognized Boolean value.
        let input = [0x2];
        let res = TestCustomFieldPacket::parse(&input);
        assert!(res.is_err());
    }

    #[test]
    fn test_invalid_array_size() {
        // Size 4, have 2.
        let input = [0x4, 0x0, 0x0];
        let res = TestArraySizePacket::parse(&input);
        assert!(res.is_err());
    }

    #[test]
    fn test_invalid_array_count() {
        // Count 2, have 1.
        let input = [0x2, 0x0, 0x0];
        let res = TestArrayCountPacket::parse(&input);
        assert!(res.is_err());
    }

    #[test]
    fn test_invalid_payload_size() {
        // Size 2, have 1.
        let input = [0x2, 0x0];
        let res = TestPayloadSizePacket::parse(&input);
        assert!(res.is_err());
    }

    #[test]
    fn test_invalid_body_size() {
        // Size 2, have 1.
        // Body does not have a concrete representation,
        // the size and payload are both discarded.
        let input = [0x2, 0x0];
        let res = TestBodySizePacket::parse(&input);
        assert!(res.is_ok());
    }
}