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
use crate::{TBuffer, TBytes};

impl<T: TBytes> TBytes for Option<T> {
    fn size(&self) -> usize {
        match self {
            Some(d) => 1 + d.size(),
            None => 1,
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(self.size());

        match self {
            Some(data) => {
                buffer.push(1);
                buffer.append(&mut data.to_bytes())
            }
            None => buffer.push(0),
        }

        buffer
    }

    fn from_bytes(buffer: &mut TBuffer) -> Option<Self>
    where
        Self: Sized,
    {
        let has = buffer.next()?;

        if has > 0 {
            Some(Some(T::from_bytes(buffer)?))
        } else {
            Some(None)
        }
    }
}

#[cfg(test)]
mod test {
    use crate::TBytes;

    #[test]
    fn option_string() {
        let a = Some(String::from("Hello There"));

        let mut bytes = a.to_bytes();

        let other = <Option<String>>::from_bytes(&mut bytes.drain(..)).unwrap();

        assert_eq!(a, other);

        let b: Option<String> = None;

        let mut bytes = b.to_bytes();

        let other = <Option<String>>::from_bytes(&mut bytes.drain(..)).unwrap();

        assert_eq!(b, other)
    }
}