Skip to main content

der/asn1/
null.rs

1//! ASN.1 `NULL` support.
2
3use crate::{
4    BytesRef, DecodeValue, EncodeValue, Error, ErrorKind, FixedTag, Header, Length, Reader, Result,
5    Tag, Writer, asn1::AnyRef, ord::OrdIsValueOrd,
6};
7
8/// ASN.1 `NULL` type.
9#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
10pub struct Null;
11
12impl_any_conversions!(Null);
13
14impl<'a> DecodeValue<'a> for Null {
15    type Error = Error;
16
17    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
18        if header.length().is_zero() {
19            Ok(Null)
20        } else {
21            Err(reader.error(ErrorKind::Length { tag: Self::TAG }))
22        }
23    }
24}
25
26impl EncodeValue for Null {
27    fn value_len(&self) -> Result<Length> {
28        Ok(Length::ZERO)
29    }
30
31    fn encode_value(&self, _writer: &mut impl Writer) -> Result<()> {
32        Ok(())
33    }
34}
35
36impl FixedTag for Null {
37    const TAG: Tag = Tag::Null;
38}
39
40impl OrdIsValueOrd for Null {}
41
42impl<'a> From<Null> for AnyRef<'a> {
43    fn from(_: Null) -> AnyRef<'a> {
44        AnyRef::from_tag_and_value(Tag::Null, BytesRef::EMPTY)
45    }
46}
47
48impl TryFrom<AnyRef<'_>> for () {
49    type Error = Error;
50
51    fn try_from(any: AnyRef<'_>) -> Result<()> {
52        Null::try_from(any).map(|_| ())
53    }
54}
55
56impl<'a> From<()> for AnyRef<'a> {
57    fn from(_: ()) -> AnyRef<'a> {
58        Null.into()
59    }
60}
61
62impl<'a> DecodeValue<'a> for () {
63    type Error = Error;
64
65    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
66        Null::decode_value(reader, header)?;
67        Ok(())
68    }
69}
70
71impl EncodeValue for () {
72    fn value_len(&self) -> Result<Length> {
73        Ok(Length::ZERO)
74    }
75
76    fn encode_value(&self, _writer: &mut impl Writer) -> Result<()> {
77        Ok(())
78    }
79}
80
81impl FixedTag for () {
82    const TAG: Tag = Tag::Null;
83}
84
85#[cfg(test)]
86#[allow(clippy::unwrap_used)]
87mod tests {
88    use super::Null;
89    use crate::{Decode, Encode};
90
91    #[test]
92    fn decode() {
93        Null::from_der(&[0x05, 0x00]).unwrap();
94    }
95
96    #[test]
97    fn encode() {
98        let mut buffer = [0u8; 2];
99        assert_eq!(&[0x05, 0x00], Null.encode_to_slice(&mut buffer).unwrap());
100        assert_eq!(&[0x05, 0x00], ().encode_to_slice(&mut buffer).unwrap());
101    }
102
103    #[test]
104    fn reject_non_canonical() {
105        assert!(Null::from_der(&[0x05, 0x81, 0x00]).is_err());
106        assert!(Null::from_der(&[0x05, 0x01, 0xAA]).is_err());
107    }
108}