bytes_kman/core/
option.rs

1use crate::{TBuffer, TBytes};
2
3impl<T: TBytes> TBytes for Option<T> {
4    fn size(&self) -> usize {
5        match self {
6            Some(d) => 1 + d.size(),
7            None => 1,
8        }
9    }
10
11    fn to_bytes(&self) -> Vec<u8> {
12        let mut buffer = Vec::with_capacity(self.size());
13
14        match self {
15            Some(data) => {
16                buffer.push(1);
17                buffer.append(&mut data.to_bytes())
18            }
19            None => buffer.push(0),
20        }
21
22        buffer
23    }
24
25    fn from_bytes(buffer: &mut TBuffer) -> Option<Self>
26    where
27        Self: Sized,
28    {
29        if buffer.len() < Self::default().size() {
30            return None;
31        }
32        let mut iter = buffer.drain(0..Self::default().size());
33        let has = iter.next()?;
34
35        drop(iter);
36
37        if has > 0 {
38            if let Some(value) = T::from_bytes(buffer) {
39                Some(Some(value))
40            } else {
41                buffer.insert(0, has);
42                None
43            }
44        } else {
45            Some(None)
46        }
47    }
48}
49
50#[cfg(test)]
51mod test {
52    use crate::TBytes;
53
54    #[test]
55    fn option_string() {
56        let a = Some(String::from("Hello There"));
57
58        let mut bytes = a.to_bytes();
59
60        let other = <Option<String>>::from_bytes(&mut bytes).unwrap();
61
62        assert_eq!(a, other);
63
64        let b: Option<String> = None;
65
66        let mut bytes = b.to_bytes();
67
68        let other = <Option<String>>::from_bytes(&mut bytes).unwrap();
69
70        assert_eq!(b, other)
71    }
72
73    #[test]
74    fn option_incomplite() {
75        let mut buffer = Vec::new();
76        buffer.push(1);
77        buffer.push(21);
78
79        let clone_buffer = buffer.clone();
80
81        let other_buffer = Option::<u16>::from_bytes(&mut buffer);
82        if let Some(other_buffer) = other_buffer {
83            panic!("This should be possible! Other buffer: {other_buffer:?}");
84        }
85
86        assert_eq!(buffer, clone_buffer);
87        buffer.push(0);
88
89        assert_eq!(buffer, Some(21u16).to_bytes());
90        let value = Option::<u16>::from_bytes(&mut buffer).unwrap();
91        assert_eq!(value, Some(21u16))
92    }
93}