rasn/types/strings/
teletex.rs

1use super::*;
2
3use alloc::vec::Vec;
4use once_cell::race::OnceBox;
5
6/// A string, which contains the characters defined in T.61 standard.
7#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
8pub struct TeletexString(pub(super) Vec<u32>);
9static CHARACTER_MAP: OnceBox<alloc::collections::BTreeMap<u32, u32>> = OnceBox::new();
10static INDEX_MAP: OnceBox<alloc::collections::BTreeMap<u32, u32>> = OnceBox::new();
11
12impl TeletexString {
13    /// Converts the string into a set of big endian bytes.
14    #[must_use]
15    pub fn to_bytes(&self) -> Vec<u8> {
16        self.0.iter().flat_map(|ch| ch.to_be_bytes()).collect()
17    }
18
19    /// Attempts to convert the provided bytes into [Self].
20    ///
21    /// # Errors
22    /// If any of the provided bytes does not match the allowed character set.
23    pub fn from_bytes(bytes: &[u8]) -> Result<Self, PermittedAlphabetError> {
24        Ok(Self(Self::try_from_slice(bytes)?))
25    }
26}
27impl StaticPermittedAlphabet for TeletexString {
28    type T = u32;
29    // TODO add correct character set, see https://github.com/mouse07410/asn1c/blob/84d3a59c1bb89c59be6ca0625bb14ebea9084ba5/skeletons/TeletexString.c
30    const CHARACTER_SET: &'static [u32] = &[0];
31    const CHARACTER_SET_NAME: constrained::CharacterSetName =
32        constrained::CharacterSetName::Teletex;
33    // TODO remove once correct character set is added
34    fn contains_char(_: u32) -> bool {
35        true
36    }
37
38    fn push_char(&mut self, ch: u32) {
39        self.0.push(ch);
40    }
41    fn chars(&self) -> impl Iterator<Item = u32> + '_ {
42        self.0.iter().copied()
43    }
44
45    fn index_map() -> &'static alloc::collections::BTreeMap<u32, u32> {
46        INDEX_MAP.get_or_init(Self::build_index_map)
47    }
48
49    fn character_map() -> &'static alloc::collections::BTreeMap<u32, u32> {
50        CHARACTER_MAP.get_or_init(Self::build_character_map)
51    }
52}
53
54impl AsnType for TeletexString {
55    const TAG: Tag = Tag::TELETEX_STRING;
56    const IDENTIFIER: Identifier = Identifier::TELETEX_STRING;
57}
58
59impl Encode for TeletexString {
60    fn encode_with_tag_and_constraints<'b, E: Encoder<'b>>(
61        &self,
62        encoder: &mut E,
63        tag: Tag,
64        constraints: Constraints,
65        identifier: Identifier,
66    ) -> Result<(), E::Error> {
67        encoder
68            .encode_teletex_string(tag, constraints, self, identifier)
69            .map(drop)
70    }
71}
72
73impl Decode for TeletexString {
74    fn decode_with_tag_and_constraints<D: Decoder>(
75        decoder: &mut D,
76        tag: Tag,
77        constraints: Constraints,
78    ) -> Result<Self, D::Error> {
79        decoder.decode_teletex_string(tag, constraints)
80    }
81}