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. The count is the number of code units; characters outside the BMP take a surrogate pair.
235///
236/// `String` and `str` have the same encoding, so plain Rust strings can be used wherever the datatype is
237/// `HLAunicodeString`. Decoding rejects unpaired surrogates.
238#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
239pub struct HLAunicodeString(pub String);
240
241impl HLAunicodeString {
242    /// Wraps `text`.
243    pub fn new(text: impl Into<String>) -> Self {
244        Self(text.into())
245    }
246
247    /// The text.
248    pub fn as_str(&self) -> &str {
249        &self.0
250    }
251
252    /// Unwraps the text.
253    pub fn into_string(self) -> String {
254        self.0
255    }
256}
257
258impl From<String> for HLAunicodeString {
259    fn from(text: String) -> Self {
260        Self(text)
261    }
262}
263
264impl From<&str> for HLAunicodeString {
265    fn from(text: &str) -> Self {
266        Self(text.to_owned())
267    }
268}
269
270impl From<HLAunicodeString> for String {
271    fn from(value: HLAunicodeString) -> Self {
272        value.0
273    }
274}
275
276impl AsRef<str> for HLAunicodeString {
277    fn as_ref(&self) -> &str {
278        &self.0
279    }
280}
281
282impl fmt::Display for HLAunicodeString {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        f.write_str(&self.0)
285    }
286}
287
288impl Encode for HLAunicodeString {
289    const OCTET_BOUNDARY: usize = 4;
290
291    fn encode(&self, writer: &mut ByteWriter<'_>) {
292        encode_utf16(&self.0, writer);
293    }
294}
295
296impl Decode for HLAunicodeString {
297    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
298        decode_utf16(reader).map(Self)
299    }
300}
301
302impl Representation<String> for HLAunicodeString {
303    const BOUNDARY: usize = 4;
304
305    fn encode_value(value: &String, writer: &mut ByteWriter<'_>) {
306        encode_utf16(value, writer);
307    }
308
309    fn decode_value(reader: &mut ByteReader<'_>) -> Result<String, DecoderError> {
310        decode_utf16(reader)
311    }
312}
313
314/// Encoded as `HLAunicodeString`.
315impl Encode for str {
316    const OCTET_BOUNDARY: usize = 4;
317
318    fn encode(&self, writer: &mut ByteWriter<'_>) {
319        encode_utf16(self, writer);
320    }
321}
322
323/// Encoded as `HLAunicodeString`.
324impl Encode for String {
325    const OCTET_BOUNDARY: usize = 4;
326
327    fn encode(&self, writer: &mut ByteWriter<'_>) {
328        encode_utf16(self, writer);
329    }
330}
331
332impl Decode for String {
333    fn decode(reader: &mut ByteReader<'_>) -> Result<Self, DecoderError> {
334        decode_utf16(reader)
335    }
336}