rasn/types/strings/
numeric.rs1use super::{
2 bytes_to_chars, constrained, AsnType, Constraints, Decode, Decoder, Encode, Encoder,
3 Identifier, StaticPermittedAlphabet, Tag,
4};
5
6use crate::error::strings::PermittedAlphabetError;
7use alloc::vec::Vec;
8use once_cell::race::OnceBox;
9
10#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
12pub struct NumericString(pub(super) 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 NumericString {
17 pub fn from_bytes(bytes: &[u8]) -> Result<Self, PermittedAlphabetError> {
22 Ok(Self(Self::try_from_slice(bytes)?))
23 }
24
25 #[must_use]
27 pub fn as_bytes(&self) -> &[u8] {
28 &self.0
29 }
30}
31
32impl StaticPermittedAlphabet for NumericString {
33 type T = u8;
34 const CHARACTER_SET: &'static [u32] = &bytes_to_chars([
35 b' ', b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9',
36 ]);
37 const CHARACTER_SET_NAME: constrained::CharacterSetName =
38 constrained::CharacterSetName::Numeric;
39
40 fn chars(&self) -> impl Iterator<Item = u32> + '_ {
41 self.0.iter().map(|&byte| byte as u32)
42 }
43
44 fn push_char(&mut self, ch: u32) {
45 self.0.push(ch as u8);
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 NumericString {
58 const TAG: Tag = Tag::NUMERIC_STRING;
59 const IDENTIFIER: Identifier = Identifier::NUMERIC_STRING;
60}
61
62impl Encode for NumericString {
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_numeric_string(tag, constraints, self, identifier)
72 .map(drop)
73 }
74}
75
76impl Decode for NumericString {
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_numeric_string(tag, constraints)
83 }
84}