veecle_os_data_support_someip/
parse_impl.rs

1//! Implementation of [`Parse`] for various data types.
2
3use super::parse::{Parse, ParseError};
4use crate::parse::ByteReader;
5
6impl<'a> Parse<'a> for bool {
7    fn parse_partial(reader: &mut ByteReader<'a>) -> Result<Self, ParseError> {
8        let byte = reader.read_byte()?;
9
10        // Only 0 and 1 are valid values for a boolean.
11        if byte > 1 {
12            return Err(ParseError::MalformedMessage {
13                failed_at: core::any::type_name::<Self>(),
14            });
15        }
16
17        Ok(byte == 1)
18    }
19}
20
21macro_rules! impl_for_numeric {
22    ($ty:ident) => {
23        impl<'a> Parse<'a> for $ty {
24            fn parse_partial(reader: &mut ByteReader<'a>) -> Result<Self, ParseError> {
25                Ok($ty::from_be_bytes(reader.read_array()?))
26            }
27        }
28    };
29}
30
31impl_for_numeric!(u8);
32impl_for_numeric!(u16);
33impl_for_numeric!(u32);
34impl_for_numeric!(u64);
35
36impl_for_numeric!(i8);
37impl_for_numeric!(i16);
38impl_for_numeric!(i32);
39impl_for_numeric!(i64);
40
41impl_for_numeric!(f32);
42impl_for_numeric!(f64);
43
44#[cfg(test)]
45#[cfg_attr(coverage_nightly, coverage(off))]
46mod parse {
47    use crate::parse::{ParseError, ParseExt};
48
49    #[test]
50    fn bool() {
51        test_round_trip!(bool, true, &[1]);
52        test_round_trip!(bool, false, &[0]);
53    }
54
55    #[test]
56    fn malformed_bool() {
57        assert_eq!(
58            bool::parse(&[2]),
59            Err(ParseError::MalformedMessage { failed_at: "bool" })
60        );
61    }
62
63    #[test]
64    fn u8() {
65        test_round_trip!(u8, 99, &[99]);
66    }
67
68    #[test]
69    fn u16() {
70        test_round_trip!(u16, 0x40A, &[0x4, 0xA]);
71    }
72
73    #[test]
74    fn u32() {
75        test_round_trip!(u32, 0x40A0834, &[0x4, 0xA, 0x8, 0x34]);
76    }
77
78    #[test]
79    fn u64() {
80        test_round_trip!(
81            u64,
82            0x40A083410090807,
83            &[0x4, 0xA, 0x8, 0x34, 0x10, 0x9, 0x8, 0x7]
84        );
85    }
86
87    #[test]
88    fn i8() {
89        test_round_trip!(i8, -1, &[0xFF]);
90    }
91
92    #[test]
93    fn i16() {
94        test_round_trip!(i16, -246, &[0xFF, 0xA]);
95    }
96
97    #[test]
98    fn i32() {
99        test_round_trip!(i32, -16119756, &[0xFF, 0xA, 0x8, 0x34]);
100    }
101
102    #[test]
103    fn i64() {
104        test_round_trip!(
105            i64,
106            -69233824570472441,
107            &[0xFF, 0xA, 0x8, 0x34, 0x10, 0x9, 0x8, 0x7]
108        );
109    }
110
111    #[test]
112    fn f32() {
113        test_round_trip!(f32, 9.21298e-40, &[0x0, 0xA, 0x8, 0x34]);
114    }
115
116    #[test]
117    fn f64() {
118        test_round_trip!(
119            f64,
120            1.395127485645192e-308,
121            &[0x0, 0xA, 0x8, 0x34, 0x10, 0x9, 0x8, 0x7]
122        );
123    }
124}