der/asn1/
utf8_string.rs

1//! ASN.1 `UTF8String` support.
2
3use crate::{
4    asn1::AnyRef, ord::OrdIsValueOrd, ByteSlice, DecodeValue, EncodeValue, Error, FixedTag, Header,
5    Length, Reader, Result, StrSlice, Tag, Writer,
6};
7use core::{fmt, ops::Deref, str};
8
9#[cfg(feature = "alloc")]
10use alloc::{borrow::ToOwned, string::String};
11
12/// ASN.1 `UTF8String` type.
13///
14/// Supports the full UTF-8 encoding.
15///
16/// Note that the [`Decode`][`crate::Decode`] and [`Encode`][`crate::Encode`]
17/// traits are impl'd for Rust's [`str`][`prim@str`] primitive, which
18/// decodes/encodes as a [`Utf8StringRef`].
19///
20/// You are free to use [`str`][`prim@str`] instead of this type, however it's
21/// still provided for explicitness in cases where it might be ambiguous with
22/// other ASN.1 string encodings such as
23/// [`PrintableStringRef`][`crate::asn1::PrintableStringRef`].
24///
25/// This is a zero-copy reference type which borrows from the input data.
26#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
27pub struct Utf8StringRef<'a> {
28    /// Inner value
29    inner: StrSlice<'a>,
30}
31
32impl<'a> Utf8StringRef<'a> {
33    /// Create a new ASN.1 `UTF8String`.
34    pub fn new<T>(input: &'a T) -> Result<Self>
35    where
36        T: AsRef<[u8]> + ?Sized,
37    {
38        StrSlice::from_bytes(input.as_ref()).map(|inner| Self { inner })
39    }
40}
41
42impl<'a> Deref for Utf8StringRef<'a> {
43    type Target = StrSlice<'a>;
44
45    fn deref(&self) -> &Self::Target {
46        &self.inner
47    }
48}
49
50impl AsRef<str> for Utf8StringRef<'_> {
51    fn as_ref(&self) -> &str {
52        self.as_str()
53    }
54}
55
56impl AsRef<[u8]> for Utf8StringRef<'_> {
57    fn as_ref(&self) -> &[u8] {
58        self.as_bytes()
59    }
60}
61
62impl<'a> DecodeValue<'a> for Utf8StringRef<'a> {
63    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
64        Self::new(ByteSlice::decode_value(reader, header)?.as_slice())
65    }
66}
67
68impl EncodeValue for Utf8StringRef<'_> {
69    fn value_len(&self) -> Result<Length> {
70        self.inner.value_len()
71    }
72
73    fn encode_value(&self, writer: &mut dyn Writer) -> Result<()> {
74        self.inner.encode_value(writer)
75    }
76}
77
78impl FixedTag for Utf8StringRef<'_> {
79    const TAG: Tag = Tag::Utf8String;
80}
81
82impl OrdIsValueOrd for Utf8StringRef<'_> {}
83
84impl<'a> From<&Utf8StringRef<'a>> for Utf8StringRef<'a> {
85    fn from(value: &Utf8StringRef<'a>) -> Utf8StringRef<'a> {
86        *value
87    }
88}
89
90impl<'a> TryFrom<AnyRef<'a>> for Utf8StringRef<'a> {
91    type Error = Error;
92
93    fn try_from(any: AnyRef<'a>) -> Result<Utf8StringRef<'a>> {
94        any.decode_into()
95    }
96}
97
98impl<'a> From<Utf8StringRef<'a>> for AnyRef<'a> {
99    fn from(printable_string: Utf8StringRef<'a>) -> AnyRef<'a> {
100        AnyRef::from_tag_and_value(Tag::Utf8String, printable_string.inner.into())
101    }
102}
103
104impl<'a> fmt::Display for Utf8StringRef<'a> {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        f.write_str(self.as_str())
107    }
108}
109
110impl<'a> fmt::Debug for Utf8StringRef<'a> {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "Utf8String({:?})", self.as_str())
113    }
114}
115
116impl<'a> TryFrom<AnyRef<'a>> for &'a str {
117    type Error = Error;
118
119    fn try_from(any: AnyRef<'a>) -> Result<&'a str> {
120        Utf8StringRef::try_from(any).map(|s| s.as_str())
121    }
122}
123
124impl EncodeValue for str {
125    fn value_len(&self) -> Result<Length> {
126        Utf8StringRef::new(self)?.value_len()
127    }
128
129    fn encode_value(&self, writer: &mut dyn Writer) -> Result<()> {
130        Utf8StringRef::new(self)?.encode_value(writer)
131    }
132}
133
134impl FixedTag for str {
135    const TAG: Tag = Tag::Utf8String;
136}
137
138impl OrdIsValueOrd for str {}
139
140#[cfg(feature = "alloc")]
141#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
142impl<'a> From<Utf8StringRef<'a>> for String {
143    fn from(s: Utf8StringRef<'a>) -> String {
144        s.as_str().to_owned()
145    }
146}
147
148#[cfg(feature = "alloc")]
149#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
150impl<'a> TryFrom<AnyRef<'a>> for String {
151    type Error = Error;
152
153    fn try_from(any: AnyRef<'a>) -> Result<String> {
154        Utf8StringRef::try_from(any).map(|s| s.as_str().to_owned())
155    }
156}
157
158#[cfg(feature = "alloc")]
159#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
160impl<'a> DecodeValue<'a> for String {
161    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
162        Ok(String::from_utf8(reader.read_vec(header.length)?)?)
163    }
164}
165
166#[cfg(feature = "alloc")]
167#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
168impl EncodeValue for String {
169    fn value_len(&self) -> Result<Length> {
170        Utf8StringRef::new(self)?.value_len()
171    }
172
173    fn encode_value(&self, writer: &mut dyn Writer) -> Result<()> {
174        Utf8StringRef::new(self)?.encode_value(writer)
175    }
176}
177
178#[cfg(feature = "alloc")]
179#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
180impl FixedTag for String {
181    const TAG: Tag = Tag::Utf8String;
182}
183
184#[cfg(feature = "alloc")]
185#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
186impl OrdIsValueOrd for String {}
187
188#[cfg(test)]
189mod tests {
190    use super::Utf8StringRef;
191    use crate::Decode;
192
193    #[test]
194    fn parse_ascii_bytes() {
195        let example_bytes = &[
196            0x0c, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x20, 0x55, 0x73, 0x65, 0x72, 0x20, 0x31,
197        ];
198
199        let utf8_string = Utf8StringRef::from_der(example_bytes).unwrap();
200        assert_eq!(utf8_string.as_str(), "Test User 1");
201    }
202
203    #[test]
204    fn parse_utf8_bytes() {
205        let example_bytes = &[0x0c, 0x06, 0x48, 0x65, 0x6c, 0x6c, 0xc3, 0xb3];
206        let utf8_string = Utf8StringRef::from_der(example_bytes).unwrap();
207        assert_eq!(utf8_string.as_str(), "Helló");
208    }
209}