rasn/types/strings/
general.rs

1use super::*;
2
3use crate::error::strings::InvalidGeneralString;
4use alloc::{borrow::ToOwned, string::String, vec::Vec};
5
6/// A "general" string containing the `C0` Controls plane, `SPACE`,
7/// Basic Latin, `DELETE`, and Latin-1 Supplement characters.
8#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
9pub struct GeneralString(Vec<u8>);
10
11impl GeneralString {
12    fn is_valid(bytes: &[u8]) -> Result<(), InvalidGeneralString> {
13        for byte in bytes {
14            let is_in_set = matches!(
15                byte,
16                | 0x00..=0x1F // C0 Controls (C set)
17                | 0x20        // SPACE
18                | 0x21..=0x7E // Basic Latin (G set)
19                | 0x7F        // DELETE
20                | 0xA1..=0xFF // Latin-1 Supplement (G set)
21            );
22
23            if !is_in_set {
24                return Err(InvalidGeneralString { character: *byte });
25            }
26        }
27        Ok(())
28    }
29
30    pub fn from_bytes(bytes: &[u8]) -> Result<Self, InvalidGeneralString> {
31        Self::is_valid(bytes)?;
32        Ok(Self(bytes.to_owned()))
33    }
34}
35
36impl TryFrom<Vec<u8>> for GeneralString {
37    type Error = InvalidGeneralString;
38
39    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
40        Self::is_valid(&value)?;
41        Ok(Self(value))
42    }
43}
44
45impl TryFrom<String> for GeneralString {
46    type Error = InvalidGeneralString;
47
48    fn try_from(value: String) -> Result<Self, Self::Error> {
49        Self::is_valid(value.as_bytes())?;
50        Ok(Self(value.into_bytes()))
51    }
52}
53
54impl core::ops::Deref for GeneralString {
55    type Target = Vec<u8>;
56
57    fn deref(&self) -> &Self::Target {
58        &self.0
59    }
60}
61
62impl core::ops::DerefMut for GeneralString {
63    fn deref_mut(&mut self) -> &mut Self::Target {
64        &mut self.0
65    }
66}
67
68impl AsnType for GeneralString {
69    const TAG: Tag = Tag::GENERAL_STRING;
70}
71
72impl Decode for GeneralString {
73    fn decode_with_tag_and_constraints<D: Decoder>(
74        decoder: &mut D,
75        tag: Tag,
76        constraints: Constraints,
77    ) -> Result<Self, D::Error> {
78        decoder.decode_general_string(tag, constraints)
79    }
80}
81
82impl Encode for GeneralString {
83    fn encode_with_tag_and_constraints<E: Encoder>(
84        &self,
85        encoder: &mut E,
86        tag: Tag,
87        constraints: Constraints,
88    ) -> Result<(), E::Error> {
89        encoder
90            .encode_general_string(tag, constraints, self)
91            .map(drop)
92    }
93}