rasn/types/strings/
teletex.rs

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