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
//! ASN.1 `OPTIONAL` as mapped to Rust's `Option` type

use crate::{Choice, Decode, DerOrd, Encode, Length, Reader, Result, Tag, Writer};
use core::cmp::Ordering;

impl<'a, T> Decode<'a> for Option<T>
where
    T: Choice<'a>, // NOTE: all `Decode + Tagged` types receive a blanket `Choice` impl
{
    fn decode<R: Reader<'a>>(reader: &mut R) -> Result<Option<T>> {
        if let Some(byte) = reader.peek_byte() {
            if T::can_decode(Tag::try_from(byte)?) {
                return T::decode(reader).map(Some);
            }
        }

        Ok(None)
    }
}

impl<T> DerOrd for Option<T>
where
    T: DerOrd,
{
    fn der_cmp(&self, other: &Self) -> Result<Ordering> {
        match self {
            Some(a) => match other {
                Some(b) => a.der_cmp(b),
                None => Ok(Ordering::Greater),
            },
            None => Ok(Ordering::Less),
        }
    }
}

impl<T> Encode for Option<T>
where
    T: Encode,
{
    fn encoded_len(&self) -> Result<Length> {
        (&self).encoded_len()
    }

    fn encode(&self, writer: &mut dyn Writer) -> Result<()> {
        (&self).encode(writer)
    }
}

impl<T> Encode for &Option<T>
where
    T: Encode,
{
    fn encoded_len(&self) -> Result<Length> {
        match self {
            Some(encodable) => encodable.encoded_len(),
            None => Ok(0u8.into()),
        }
    }

    fn encode(&self, encoder: &mut dyn Writer) -> Result<()> {
        match self {
            Some(encodable) => encodable.encode(encoder),
            None => Ok(()),
        }
    }
}