Skip to main content

der/asn1/
ia5_string.rs

1//! ASN.1 `IA5String` support.
2
3use crate::{FixedTag, Result, StringRef, Tag, asn1::AnyRef};
4use core::{fmt, ops::Deref};
5
6macro_rules! impl_ia5_string {
7    ($type: ty) => {
8        impl_ia5_string!($type,);
9    };
10    ($type: ty, $($li: lifetime)?) => {
11        impl_string_type!($type, $($li),*);
12
13        impl<$($li),*> FixedTag for $type {
14            const TAG: Tag = Tag::Ia5String;
15        }
16
17        impl<$($li),*> fmt::Debug for $type {
18            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19                write!(f, "Ia5String({:?})", self.as_str())
20            }
21        }
22    };
23}
24
25/// ASN.1 `IA5String` type.
26///
27/// Supports the [International Alphabet No. 5 (IA5)] character encoding, i.e.
28/// the lower 128 characters of the ASCII alphabet. (Note: IA5 is now
29/// technically known as the International Reference Alphabet or IRA as
30/// specified in the ITU-T's T.50 recommendation).
31///
32/// For UTF-8, use [`Utf8StringRef`][`crate::asn1::Utf8StringRef`].
33///
34/// This is a zero-copy reference type which borrows from the input data.
35///
36/// [International Alphabet No. 5 (IA5)]: https://en.wikipedia.org/wiki/T.50_%28standard%29
37#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
38pub struct Ia5StringRef<'a> {
39    /// Inner value
40    inner: &'a StringRef,
41}
42
43impl<'a> Ia5StringRef<'a> {
44    /// Create a new `IA5String`.
45    ///
46    /// # Errors
47    /// In the event characters are outside `IA5String`'s allowed set.
48    pub fn new<T>(input: &'a T) -> Result<Self>
49    where
50        T: AsRef<[u8]> + ?Sized,
51    {
52        let input = input.as_ref();
53
54        // Validate all characters are within IA5String's allowed set
55        if input.iter().any(|&c| c > 0x7F) {
56            return Err(Self::TAG.value_error().into());
57        }
58
59        StringRef::from_bytes(input)
60            .map(|inner| Self { inner })
61            .map_err(|_| Self::TAG.value_error().into())
62    }
63
64    /// Borrow the inner `str`.
65    #[must_use]
66    pub fn as_str(&self) -> &'a str {
67        self.inner.as_str()
68    }
69}
70
71impl_ia5_string!(Ia5StringRef<'a>, 'a);
72
73impl<'a> Deref for Ia5StringRef<'a> {
74    type Target = StringRef;
75
76    fn deref(&self) -> &Self::Target {
77        self.inner
78    }
79}
80
81impl<'a> From<&Ia5StringRef<'a>> for Ia5StringRef<'a> {
82    fn from(value: &Ia5StringRef<'a>) -> Ia5StringRef<'a> {
83        *value
84    }
85}
86
87impl<'a> From<Ia5StringRef<'a>> for AnyRef<'a> {
88    fn from(internationalized_string: Ia5StringRef<'a>) -> AnyRef<'a> {
89        AnyRef::from_tag_and_value(Tag::Ia5String, internationalized_string.inner.as_ref())
90    }
91}
92
93#[cfg(feature = "alloc")]
94pub use self::allocation::Ia5String;
95
96#[cfg(feature = "alloc")]
97mod allocation {
98    use super::Ia5StringRef;
99    use crate::{
100        Error, FixedTag, Result, StringOwned, Tag,
101        asn1::AnyRef,
102        referenced::{OwnedToRef, RefToOwned},
103    };
104    use alloc::{borrow::ToOwned, string::String};
105    use core::{fmt, ops::Deref};
106
107    /// ASN.1 `IA5String` type.
108    ///
109    /// Supports the [International Alphabet No. 5 (IA5)] character encoding, i.e.
110    /// the lower 128 characters of the ASCII alphabet. (Note: IA5 is now
111    /// technically known as the International Reference Alphabet or IRA as
112    /// specified in the ITU-T's T.50 recommendation).
113    ///
114    /// For UTF-8, use [`String`][`alloc::string::String`].
115    ///
116    /// [International Alphabet No. 5 (IA5)]: https://en.wikipedia.org/wiki/T.50_%28standard%29
117    #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
118    pub struct Ia5String {
119        /// Inner value
120        inner: StringOwned,
121    }
122
123    impl Ia5String {
124        /// Create a new `IA5String`.
125        ///
126        /// # Errors
127        /// If characters are out of range.
128        pub fn new<T>(input: &T) -> Result<Self>
129        where
130            T: AsRef<[u8]> + ?Sized,
131        {
132            let input = input.as_ref();
133            Ia5StringRef::new(input)?;
134
135            StringOwned::from_bytes(input)
136                .map(|inner| Self { inner })
137                .map_err(|_| Self::TAG.value_error().into())
138        }
139    }
140
141    impl_ia5_string!(Ia5String);
142
143    impl Deref for Ia5String {
144        type Target = StringOwned;
145
146        fn deref(&self) -> &Self::Target {
147            &self.inner
148        }
149    }
150
151    impl<'a> From<Ia5StringRef<'a>> for Ia5String {
152        fn from(ia5_string: Ia5StringRef<'a>) -> Ia5String {
153            Self {
154                inner: ia5_string.inner.to_owned(),
155            }
156        }
157    }
158
159    impl<'a> From<&'a Ia5String> for AnyRef<'a> {
160        fn from(ia5_string: &'a Ia5String) -> AnyRef<'a> {
161            AnyRef::from_tag_and_value(Tag::Ia5String, ia5_string.inner.as_ref())
162        }
163    }
164
165    impl<'a> From<&'a Ia5String> for Ia5StringRef<'a> {
166        fn from(ia5_string: &'a Ia5String) -> Ia5StringRef<'a> {
167            ia5_string.owned_to_ref()
168        }
169    }
170
171    impl<'a> RefToOwned<'a> for Ia5StringRef<'a> {
172        type Owned = Ia5String;
173        fn ref_to_owned(&self) -> Self::Owned {
174            Ia5String {
175                inner: self.inner.to_owned(),
176            }
177        }
178    }
179
180    impl OwnedToRef for Ia5String {
181        type Borrowed<'a> = Ia5StringRef<'a>;
182        fn owned_to_ref(&self) -> Self::Borrowed<'_> {
183            Ia5StringRef {
184                inner: self.inner.as_ref(),
185            }
186        }
187    }
188
189    impl TryFrom<String> for Ia5String {
190        type Error = Error;
191
192        fn try_from(input: String) -> Result<Self> {
193            Ia5StringRef::new(&input)?;
194
195            StringOwned::new(input)
196                .map(|inner| Self { inner })
197                .map_err(|_| Self::TAG.value_error().into())
198        }
199    }
200}
201
202#[cfg(test)]
203#[allow(clippy::unwrap_used)]
204mod tests {
205    use super::Ia5StringRef;
206    use crate::Decode;
207    use hex_literal::hex;
208
209    #[test]
210    fn parse_bytes() {
211        let example_bytes = hex!("16 0d 74 65 73 74 31 40 72 73 61 2e 63 6f 6d");
212        let internationalized_string = Ia5StringRef::from_der(&example_bytes).unwrap();
213        assert_eq!(internationalized_string.as_str(), "test1@rsa.com");
214    }
215}