Skip to main content

microrti_encoding/
strings.rs

1//! Strings and opaque data: the MIM variable arrays of characters and bytes.
2
3use std::fmt;
4
5use crate::buffer::{ByteReader, ByteWriter, COUNT_BOUNDARY};
6use crate::error::{DecoderError, EncoderError};
7use crate::typed::{Decode, Encode, Representation};
8
9/// Encodes a variable array of single-octet elements: count, then the octets.
10pub(crate) fn encode_octets(octets: &[u8], writer: &mut ByteWriter<'_>) {
11    writer.align(COUNT_BOUNDARY);
12    writer.put_count(octets.len());
13    writer.put_slice(octets);
14}
15
16/// Decodes a variable array of single-octet elements without copying.
17pub(crate) fn decode_octets<'a>(reader: &mut ByteReader<'a>) -> Result<&'a [u8], DecoderError> {
18    reader.align(COUNT_BOUNDARY)?;
19    let count = reader.read_count()?;
20    reader.take(count)
21}
22
23fn encode_utf16(text: &str, writer: &mut ByteWriter<'_>) {
24    writer.align(COUNT_BOUNDARY);
25    writer.put_count(text.encode_utf16().count());
26    for unit in text.encode_utf16() {
27        writer.put_slice(&unit.to_be_bytes());
28    }
29}
30
31fn decode_utf16(reader: &mut ByteReader<'_>) -> Result<String, DecoderError> {
32    reader.align(COUNT_BOUNDARY)?;
33    let count = reader.read_count()?;
34    let octets = reader.take(count.saturating_mul(2))?;
35    let units = octets.as_chunks::<2>().0.iter().map(|pair| u16::from_be_bytes(*pair));
36    char::decode_utf16(units).collect::<Result<String, _>>().map_err(|error| DecoderError::InvalidValue {
37        type_name: "HLAunicodeString",
38        detail: format!("unpaired surrogate {:#06x}", error.unpaired_surrogate()),
39    })
40}
41
42/// Declares an element that is an `HLAvariableArray` of `HLAbyte` holding opaque octets.
43macro_rules! octet_array_element {
44    ($(#[$doc:meta])* $name:ident) => {
45        $(#[$doc])*
46        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
47        pub struct $name(pub Vec<u8>);
48
49        impl $name {
50            /// Wraps the given octets.
51            pub fn new(octets: impl Into<Vec<u8>>) -> Self {
52                Self(octets.into())
53            }
54
55            /// The wrapped octets.
56            pub fn as_bytes(&self) -> &[u8] {
57                &self.0
58            }
59
60            /// Unwraps the octets.
61            pub fn into_bytes(self) -> Vec<u8> {
62                self.0
63            }
64        }
65
66        impl From<Vec<u8>> for $name {
67            fn from(octets: Vec<u8>) -> Self {
68                Self(octets)
69            }
70        }
71
72        impl From<&[u8]> for $name {
73            fn from(octets: &[u8]) -> Self {
74                Self(octets.to_vec())
75            }
76        }
77
78        impl From<$name> for Vec<u8> {
79            fn from(value: $name) -> Self {
80                value.0
81            }
82        }
83
84        impl AsRef<[u8]> for $name {
85            fn as_ref(&self) -> &[u8] {
86                &self.0
87            }
88        }
89
90        impl $crate::typed::Encode for $name {
91            const OCTET_BOUNDARY: usize = 4;
92
93            fn encode(&self, writer: &mut $crate::buffer::ByteWriter<'_>) {
94                $crate::strings::encode_octets(&self.0, writer);
95            }
96
97            fn encoded_len(&self) -> usize {
98                4 + self.0.len()
99            }
100        }
101
102        impl $crate::typed::Decode for $name {
103            fn decode(
104                reader: &mut $crate::buffer::ByteReader<'_>,
105            ) -> Result<Self, $crate::error::DecoderError> {
106                $crate::strings::decode_octets(reader).map(|octets| Self(octets.to_vec()))
107            }
108        }
109    };
110}
111pub(crate) use octet_array_element;
112
113octet_array_element! {
114    /// `HLAopaqueData`: an `HLAvariableArray` of `HLAbyte` (32-bit big-endian count, then the octets).
115    HLAopaqueData
116}
117
118impl Representation<Vec<u8>> for HLAopaqueData {
119    const BOUNDARY: usize = 4;
120
121    fn encode_value(value: &Vec<u8>, writer: &mut ByteWriter<'_>) {
122        encode_octets(value, writer);
123    }
124
125    fn decode_value(reader: &mut ByteReader<'_>) -> Result<Vec<u8>, DecoderError> {
126        decode_octets(reader).map(<[u8]>::to_vec)
127    }
128}
129
130/// `HLAASCIIstring`: an `HLAvariableArray` of `HLAASCIIchar`, one octet per character.
131///
132/// The wrapped text is guaranteed to be ASCII, so encoding cannot fail; decoding rejects octets above
133/// `0x7F`.
134#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
135pub struct HLAASCIIstring(String);
136
137impl HLAASCIIstring {
138    /// Wraps `text`, which must consist of ASCII characters only.
139    pub fn new(text: impl Into<String>) -> Result<Self, EncoderError> {
140        let text = text.into();
141        match text.chars().find(|character| !character.is_ascii()) {
142            None => Ok(Self(text)),
143            Some(character) => Err(EncoderError::InvalidValue {
144                type_name: "HLAASCIIstring",
145                detail: format!("{character:?} is not an ASCII character"),
146            }),
147        }
148    }
149
150    /// The text.
151    pub fn as_str(&self) -> &str {
152        &self.0
153    }
154
155    /// Unwraps the text.
156    pub fn into_string(self) -> String {
157        self.0
158    }
159}
160
161impl TryFrom<&str> for HLAASCIIstring {
162    type Error = EncoderError;
163
164    fn try_from(text: &str) -> Result<Self, EncoderError> {
165        Self::new(text)
166    }
167}
168
169impl TryFrom<String> for HLAASCIIstring {
170    type Error = EncoderError;
171
172    fn try_from(text: String) -> Result<Self, EncoderError> {
173        Self::new(text)
174    }
175}
176
177impl std::str::FromStr for HLAASCIIstring {
178    type Err = EncoderError;
179
180    fn from_str(text: &str) -> Result<Self, EncoderError> {
181        Self::new(text)
182    }
183}
184
185impl From<HLAASCIIstring> for String {
186    fn from(value: HLAASCIIstring) -> Self {
187        value.0
188    }
189}
190
191impl AsRef<str> for HLAASCIIstring {
192    fn as_ref(&self) -> &str {
193        &self.0
194    }
195}
196
197impl fmt::Display for HLAASCIIstring {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.write_str(&self.0)
200    }
201}
202
203impl Encode for HLAASCIIstring {
204    const OCTET_BOUNDARY: usize = 4;
205
206    fn encode(&self, writer: &mut ByteWriter<'_>) {
207        encode_octets(self.0.as_bytes(), writer);
208    }
209
210    fn encoded_len(&self) -> usize {
211        4 + self.0.len()
212    }
213}
214
215impl Decode for HLAASCIIstring {
216    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
217        let octets = decode_octets(reader)?;
218        if let Some(octet) = octets.iter().find(|octet| !octet.is_ascii()) {
219            return Err(DecoderError::InvalidValue {
220                type_name: "HLAASCIIstring",
221                detail: format!("octet {octet:#04x} is not an ASCII character"),
222            });
223        }
224        match std::str::from_utf8(octets) {
225            Ok(text) => Ok(Self(text.to_owned())),
226            Err(error) => {
227                Err(DecoderError::InvalidValue { type_name: "HLAASCIIstring", detail: error.to_string() })
228            }
229        }
230    }
231}
232
233/// `HLAunicodeString`: an `HLAvariableArray` of `HLAunicodeChar`, that is UTF-16 code units in big-endian
234/// order (IEEE 1516.2 4.14.4, 4.14.6). The count is the number of code units; characters outside the BMP
235/// take a surrogate pair.
236///
237/// `String` and `str` have the same encoding, so plain Rust strings can be used wherever the datatype is
238/// `HLAunicodeString`. A byte order mark is an ordinary character (U+FEFF). The standard does not say
239/// what a receiver does with an unpaired surrogate; decoding rejects it.
240#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
241pub struct HLAunicodeString(pub String);
242
243impl HLAunicodeString {
244    /// Wraps `text`.
245    pub fn new(text: impl Into<String>) -> Self {
246        Self(text.into())
247    }
248
249    /// The text.
250    pub fn as_str(&self) -> &str {
251        &self.0
252    }
253
254    /// Unwraps the text.
255    pub fn into_string(self) -> String {
256        self.0
257    }
258}
259
260impl From<String> for HLAunicodeString {
261    fn from(text: String) -> Self {
262        Self(text)
263    }
264}
265
266impl From<&str> for HLAunicodeString {
267    fn from(text: &str) -> Self {
268        Self(text.to_owned())
269    }
270}
271
272impl From<HLAunicodeString> for String {
273    fn from(value: HLAunicodeString) -> Self {
274        value.0
275    }
276}
277
278impl AsRef<str> for HLAunicodeString {
279    fn as_ref(&self) -> &str {
280        &self.0
281    }
282}
283
284impl fmt::Display for HLAunicodeString {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        f.write_str(&self.0)
287    }
288}
289
290impl Encode for HLAunicodeString {
291    const OCTET_BOUNDARY: usize = 4;
292
293    fn encode(&self, writer: &mut ByteWriter<'_>) {
294        encode_utf16(&self.0, writer);
295    }
296}
297
298impl Decode for HLAunicodeString {
299    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
300        decode_utf16(reader).map(Self)
301    }
302}
303
304impl Representation<String> for HLAunicodeString {
305    const BOUNDARY: usize = 4;
306
307    fn encode_value(value: &String, writer: &mut ByteWriter<'_>) {
308        encode_utf16(value, writer);
309    }
310
311    fn decode_value(reader: &mut ByteReader<'_>) -> Result<String, DecoderError> {
312        decode_utf16(reader)
313    }
314}
315
316/// Encoded as `HLAunicodeString`.
317impl Encode for str {
318    const OCTET_BOUNDARY: usize = 4;
319
320    fn encode(&self, writer: &mut ByteWriter<'_>) {
321        encode_utf16(self, writer);
322    }
323}
324
325/// Encoded as `HLAunicodeString`.
326impl Encode for String {
327    const OCTET_BOUNDARY: usize = 4;
328
329    fn encode(&self, writer: &mut ByteWriter<'_>) {
330        encode_utf16(self, writer);
331    }
332}
333
334impl Decode for String {
335    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
336        decode_utf16(reader)
337    }
338}