1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use super::*;

use crate::error::strings::InvalidBmpString;
use alloc::{boxed::Box, string::String, vec::Vec};

/// A Basic Multilingual Plane (BMP) string, which is a subtype of [`UniversalString`]
/// containing only the BMP set of characters.
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct BmpString(Vec<u16>);

impl BmpString {
    /// Converts the string into a set of big endian bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.0.iter().flat_map(|ch| ch.to_be_bytes()).collect()
    }
}

impl StaticPermittedAlphabet for BmpString {
    const CHARACTER_SET: &'static [u32] = &{
        let mut array = [0u32; 0xFFFE];
        let mut i = 0;
        while i < 0xFFFE {
            array[i as usize] = i;
            i += 1;
        }
        array
    };

    fn push_char(&mut self, ch: u32) {
        debug_assert!(
            Self::CHARACTER_SET.contains(&ch),
            "{} not in character set",
            ch
        );
        self.0.push(ch as u16);
    }

    fn chars(&self) -> Box<dyn Iterator<Item = u32> + '_> {
        Box::from(self.0.iter().map(|ch| *ch as u32))
    }
}

impl TryFrom<String> for BmpString {
    type Error = InvalidBmpString;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(&*value)
    }
}

impl TryFrom<&'_ str> for BmpString {
    type Error = InvalidBmpString;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let mut vec = Vec::with_capacity(value.len());
        for ch in value.chars() {
            if matches!(ch as u16, 0x0..=0xFFFF) {
                vec.push(ch as u16);
            } else {
                return Err(InvalidBmpString {
                    character: ch as u16,
                });
            }
        }

        Ok(Self(vec))
    }
}

impl AsnType for BmpString {
    const TAG: Tag = Tag::BMP_STRING;
}

impl Encode for BmpString {
    fn encode_with_tag_and_constraints<E: Encoder>(
        &self,
        encoder: &mut E,
        tag: Tag,
        constraints: Constraints,
    ) -> Result<(), E::Error> {
        encoder.encode_bmp_string(tag, constraints, self).map(drop)
    }
}

impl Decode for BmpString {
    fn decode_with_tag_and_constraints<D: Decoder>(
        decoder: &mut D,
        tag: Tag,
        constraints: Constraints,
    ) -> Result<Self, D::Error> {
        decoder.decode_bmp_string(tag, constraints)
    }
}