codeq/codec/impls/
bool_impl.rs1use std::io;
2
3use byteorder::ReadBytesExt;
4use byteorder::WriteBytesExt;
5
6use crate::Decode;
7use crate::Encode;
8use crate::FixedSize;
9
10impl FixedSize for bool {
11 fn encoded_size() -> usize {
12 1
13 }
14}
15
16impl Encode for bool {
17 fn encode<W: io::Write>(&self, mut w: W) -> Result<usize, io::Error> {
18 w.write_u8(if *self { 1 } else { 0 })?;
19 Ok(1)
20 }
21}
22
23impl Decode for bool {
24 fn decode<R: io::Read>(mut r: R) -> Result<Self, io::Error> {
25 let b = r.read_u8()?;
26 if b > 1 {
27 return Err(io::Error::new(
28 io::ErrorKind::InvalidData,
29 format!("Invalid bool value: {}", b),
30 ));
31 }
32 Ok(b != 0)
33 }
34}
35
36#[cfg(test)]
37mod tests {
38
39 use std::io;
40
41 use crate::Decode;
42 use crate::Encode;
43 use crate::FixedSize;
44
45 #[test]
46 fn test_bool_codec() -> Result<(), io::Error> {
47 let b = true;
48
49 assert_eq!(1, bool::encoded_size());
50
51 let mut buf = Vec::new();
52 let n = b.encode(&mut buf)?;
53 assert_eq!(n, buf.len());
54 assert_eq!(buf.len(), 1);
55
56 let b2 = bool::decode(&mut buf.as_slice())?;
57 assert_eq!(b, b2);
58
59 Ok(())
60 }
61}