rasn/types/strings/
printable.rs

1use super::*;
2
3use crate::error::strings::InvalidPrintableString;
4use alloc::{borrow::ToOwned, boxed::Box, string::String, vec::Vec};
5use once_cell::race::OnceBox;
6
7/// A string, which contains the characters defined in X.680 41.4 Section, Table 10.
8///
9/// You must use `try_from` or `from_*` to construct a `PrintableString`.
10#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
11#[allow(clippy::module_name_repetitions)]
12pub struct PrintableString(Vec<u8>);
13static CHARACTER_MAP: OnceBox<alloc::collections::BTreeMap<u32, u32>> = OnceBox::new();
14static INDEX_MAP: OnceBox<alloc::collections::BTreeMap<u32, u32>> = OnceBox::new();
15
16impl StaticPermittedAlphabet for PrintableString {
17    /// `PrintableString` contains only "printable" characters.
18    /// Latin letters, digits, (space) '()+,-./:=?
19    const CHARACTER_SET: &'static [u32] = &bytes_to_chars([
20        b'A', b'B', b'C', b'D', b'E', b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
21        b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', b'Z', b'a', b'b', b'c', b'd',
22        b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's',
23        b't', b'u', b'v', b'w', b'x', b'y', b'z', b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
24        b'8', b'9', b' ', b'\'', b'(', b')', b'+', b',', b'-', b'.', b'/', b':', b'=', b'?',
25    ]);
26
27    fn push_char(&mut self, ch: u32) {
28        debug_assert!(
29            Self::CHARACTER_SET.contains(&ch),
30            "{ch} not in character set"
31        );
32        self.0.push(ch as u8);
33    }
34
35    fn chars(&self) -> Box<dyn Iterator<Item = u32> + '_> {
36        Box::from(self.0.iter().map(|byte| *byte as u32))
37    }
38
39    fn index_map() -> &'static alloc::collections::BTreeMap<u32, u32> {
40        INDEX_MAP.get_or_init(Self::build_index_map)
41    }
42
43    fn character_map() -> &'static alloc::collections::BTreeMap<u32, u32> {
44        CHARACTER_MAP.get_or_init(Self::build_character_map)
45    }
46}
47
48impl PrintableString {
49    /// Construct a new `PrintableString` from a byte array.
50    ///
51    /// # Errors
52    /// Raises `InvalidPrintableString` if the byte array contains invalid characters,
53    /// other than in `CHARACTER_SET`.
54    pub fn from_bytes(bytes: &[u8]) -> Result<Self, InvalidPrintableString> {
55        bytes.iter().copied().map(u32::from).try_for_each(|byte| {
56            if Self::CHARACTER_SET.contains(&byte) {
57                Ok(())
58            } else {
59                Err(InvalidPrintableString { character: byte })
60            }
61        })?;
62
63        Ok(Self(bytes.to_owned()))
64    }
65
66    #[must_use]
67    pub fn as_bytes(&self) -> &[u8] {
68        &self.0
69    }
70}
71
72impl TryFrom<String> for PrintableString {
73    type Error = InvalidPrintableString;
74
75    fn try_from(value: String) -> Result<Self, Self::Error> {
76        Self::from_bytes(value.as_bytes())
77    }
78}
79
80impl TryFrom<alloc::vec::Vec<u8>> for PrintableString {
81    type Error = InvalidPrintableString;
82
83    fn try_from(value: alloc::vec::Vec<u8>) -> Result<Self, Self::Error> {
84        Self::from_bytes(&value)
85    }
86}
87
88impl TryFrom<&'_ [u8]> for PrintableString {
89    type Error = InvalidPrintableString;
90
91    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
92        Self::from_bytes(value)
93    }
94}
95impl TryFrom<&'_ str> for PrintableString {
96    type Error = InvalidPrintableString;
97    fn try_from(value: &str) -> Result<Self, Self::Error> {
98        Self::from_bytes(value.as_bytes())
99    }
100}
101
102impl AsnType for PrintableString {
103    const TAG: Tag = Tag::PRINTABLE_STRING;
104}
105
106impl Encode for PrintableString {
107    fn encode_with_tag_and_constraints<E: Encoder>(
108        &self,
109        encoder: &mut E,
110        tag: Tag,
111        constraints: Constraints,
112    ) -> Result<(), E::Error> {
113        encoder
114            .encode_printable_string(tag, constraints, self)
115            .map(drop)
116    }
117}
118
119impl Decode for PrintableString {
120    fn decode_with_tag_and_constraints<D: Decoder>(
121        decoder: &mut D,
122        tag: Tag,
123        constraints: Constraints,
124    ) -> Result<Self, D::Error> {
125        decoder.decode_printable_string(tag, constraints)
126    }
127}