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