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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//! ASN.1 `NULL` support.

use crate::{
    asn1::AnyRef, ord::OrdIsValueOrd, ByteSlice, DecodeValue, EncodeValue, Error, ErrorKind,
    FixedTag, Header, Length, Reader, Result, Tag, Writer,
};

/// ASN.1 `NULL` type.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct Null;

impl<'a> DecodeValue<'a> for Null {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
        if header.length.is_zero() {
            Ok(Null)
        } else {
            Err(reader.error(ErrorKind::Length { tag: Self::TAG }))
        }
    }
}

impl EncodeValue for Null {
    fn value_len(&self) -> Result<Length> {
        Ok(Length::ZERO)
    }

    fn encode_value(&self, _writer: &mut dyn Writer) -> Result<()> {
        Ok(())
    }
}

impl FixedTag for Null {
    const TAG: Tag = Tag::Null;
}

impl OrdIsValueOrd for Null {}

impl<'a> From<Null> for AnyRef<'a> {
    fn from(_: Null) -> AnyRef<'a> {
        AnyRef::from_tag_and_value(Tag::Null, ByteSlice::default())
    }
}

impl TryFrom<AnyRef<'_>> for Null {
    type Error = Error;

    fn try_from(any: AnyRef<'_>) -> Result<Null> {
        any.decode_into()
    }
}

impl TryFrom<AnyRef<'_>> for () {
    type Error = Error;

    fn try_from(any: AnyRef<'_>) -> Result<()> {
        Null::try_from(any).map(|_| ())
    }
}

impl<'a> From<()> for AnyRef<'a> {
    fn from(_: ()) -> AnyRef<'a> {
        Null.into()
    }
}

impl<'a> DecodeValue<'a> for () {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
        Null::decode_value(reader, header)?;
        Ok(())
    }
}

impl EncodeValue for () {
    fn value_len(&self) -> Result<Length> {
        Ok(Length::ZERO)
    }

    fn encode_value(&self, _writer: &mut dyn Writer) -> Result<()> {
        Ok(())
    }
}

impl FixedTag for () {
    const TAG: Tag = Tag::Null;
}

#[cfg(test)]
mod tests {
    use super::Null;
    use crate::{Decode, Encode};

    #[test]
    fn decode() {
        Null::from_der(&[0x05, 0x00]).unwrap();
    }

    #[test]
    fn encode() {
        let mut buffer = [0u8; 2];
        assert_eq!(&[0x05, 0x00], Null.encode_to_slice(&mut buffer).unwrap());
        assert_eq!(&[0x05, 0x00], ().encode_to_slice(&mut buffer).unwrap());
    }

    #[test]
    fn reject_non_canonical() {
        assert!(Null::from_der(&[0x05, 0x81, 0x00]).is_err());
    }
}