Skip to main content

der/
encoding_rules.rs

1use crate::{Error, ErrorKind};
2use core::{fmt, str::FromStr};
3
4/// ASN.1 encoding rules.
5///
6/// This enum identifies the specific encoding rules which are applied at the time a given document
7/// is decoded from a byte/octet serialization.
8///
9/// In addition to the Distinguished Encoding Rules (DER), this crate also supports a strict subset
10/// of the Basic Encoding Rules (BER) which supports the minimum amount of additional productions
11/// beyond DER needed to interoperate with other implementations of cryptography-oriented formats
12/// which utilize BER, e.g. CMS, PKCS#8.
13#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
14pub enum EncodingRules {
15    /// Basic Encoding Rules.
16    #[cfg(feature = "ber")]
17    Ber,
18
19    /// Distinguished Encoding Rules.
20    #[default]
21    Der,
22}
23
24impl EncodingRules {
25    /// Are we using Basic Encoding Rules?
26    #[cfg(feature = "ber")]
27    #[must_use]
28    pub const fn is_ber(self) -> bool {
29        matches!(self, EncodingRules::Ber)
30    }
31
32    /// Are we using Distinguished Encoding Rules?
33    #[must_use]
34    pub const fn is_der(self) -> bool {
35        matches!(self, EncodingRules::Der)
36    }
37}
38
39impl FromStr for EncodingRules {
40    type Err = Error;
41
42    fn from_str(s: &str) -> Result<Self, Error> {
43        match s {
44            #[cfg(feature = "ber")]
45            "ber" | "BER" => Ok(EncodingRules::Ber),
46            "der" | "DER" => Ok(EncodingRules::Der),
47            _ => Err(ErrorKind::EncodingRules.into()),
48        }
49    }
50}
51
52impl fmt::Display for EncodingRules {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.write_str(match self {
55            #[cfg(feature = "ber")]
56            Self::Ber => "BER",
57            Self::Der => "DER",
58        })
59    }
60}
61
62#[cfg(test)]
63#[allow(clippy::unwrap_used)]
64mod tests {
65    use super::EncodingRules;
66
67    #[cfg(feature = "alloc")]
68    #[test]
69    fn display() {
70        use alloc::string::ToString;
71        #[cfg(feature = "ber")]
72        assert_eq!(EncodingRules::Ber.to_string(), "BER");
73        assert_eq!(EncodingRules::Der.to_string(), "DER");
74    }
75
76    #[test]
77    fn parse() {
78        #[cfg(feature = "ber")]
79        assert_eq!(EncodingRules::Ber, "ber".parse().unwrap());
80        #[cfg(feature = "ber")]
81        assert_eq!(EncodingRules::Ber, "BER".parse().unwrap());
82        assert_eq!(EncodingRules::Der, "der".parse().unwrap());
83        assert_eq!(EncodingRules::Der, "DER".parse().unwrap());
84
85        assert!("CER".parse::<EncodingRules>().is_err());
86    }
87}