Skip to main content

xtce_decode/
charset.rs

1//! Text decoding for the character sets XTCE permits.
2//!
3//! Implemented directly rather than via an encoding crate: XTCE allows exactly six families,
4//! four of which are trivial, and a decoder for spacecraft telemetry should not pull in a
5//! table of every legacy code page to read a UTF-8 status string.
6
7use std::borrow::Cow;
8
9use xtce_model::{ByteOrder, Charset};
10
11/// The bytes are not valid text in the requested character set.
12#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13pub struct InvalidText;
14
15/// Decodes `bytes` as `charset`.
16///
17/// Single-byte ASCII-compatible input is returned borrowed; anything needing transcoding
18/// allocates.
19///
20/// # Errors
21///
22/// Returns [`InvalidText`] if the bytes are not a valid encoding of text in `charset`.
23/// Latin-1 and Windows-1252 have no invalid sequences except the five undefined
24/// Windows-1252 code points, which are rejected — matching Python's `bytes.decode`, and for
25/// the same reason: silently substituting a replacement character would turn a corrupt field
26/// into a plausible-looking string.
27pub fn decode(
28    bytes: &[u8],
29    charset: Charset,
30    byte_order: ByteOrder,
31) -> Result<Cow<'_, str>, InvalidText> {
32    match charset {
33        Charset::Utf8 => std::str::from_utf8(bytes)
34            .map(Cow::Borrowed)
35            .map_err(|_| InvalidText),
36        Charset::UsAscii => {
37            if bytes.is_ascii() {
38                std::str::from_utf8(bytes)
39                    .map(Cow::Borrowed)
40                    .map_err(|_| InvalidText)
41            } else {
42                Err(InvalidText)
43            }
44        }
45        Charset::Iso8859_1 => Ok(if bytes.is_ascii() {
46            std::str::from_utf8(bytes)
47                .map(Cow::Borrowed)
48                .map_err(|_| InvalidText)?
49        } else {
50            Cow::Owned(bytes.iter().map(|&byte| char::from(byte)).collect())
51        }),
52        Charset::Windows1252 => decode_windows_1252(bytes),
53        Charset::Utf16 => decode_utf16(bytes, byte_order),
54        Charset::Utf32 => decode_utf32(bytes, byte_order),
55    }
56}
57
58/// A human-readable name, for error messages.
59#[must_use]
60pub const fn name(charset: Charset) -> &'static str {
61    match charset {
62        Charset::Utf8 => "UTF-8",
63        Charset::UsAscii => "US-ASCII",
64        Charset::Iso8859_1 => "ISO-8859-1",
65        Charset::Windows1252 => "Windows-1252",
66        Charset::Utf16 => "UTF-16",
67        Charset::Utf32 => "UTF-32",
68    }
69}
70
71/// Windows-1252 differs from Latin-1 only in `0x80..=0x9F`. `None` marks the five code
72/// points the standard leaves undefined.
73const CP1252_HIGH: [Option<char>; 32] = [
74    Some('\u{20AC}'), // 80 EURO SIGN
75    None,             // 81
76    Some('\u{201A}'), // 82
77    Some('\u{0192}'), // 83
78    Some('\u{201E}'), // 84
79    Some('\u{2026}'), // 85
80    Some('\u{2020}'), // 86
81    Some('\u{2021}'), // 87
82    Some('\u{02C6}'), // 88
83    Some('\u{2030}'), // 89
84    Some('\u{0160}'), // 8A
85    Some('\u{2039}'), // 8B
86    Some('\u{0152}'), // 8C
87    None,             // 8D
88    Some('\u{017D}'), // 8E
89    None,             // 8F
90    None,             // 90
91    Some('\u{2018}'), // 91
92    Some('\u{2019}'), // 92
93    Some('\u{201C}'), // 93
94    Some('\u{201D}'), // 94
95    Some('\u{2022}'), // 95
96    Some('\u{2013}'), // 96
97    Some('\u{2014}'), // 97
98    Some('\u{02DC}'), // 98
99    Some('\u{2122}'), // 99
100    Some('\u{0161}'), // 9A
101    Some('\u{203A}'), // 9B
102    Some('\u{0153}'), // 9C
103    None,             // 9D
104    Some('\u{017E}'), // 9E
105    Some('\u{0178}'), // 9F
106];
107
108fn decode_windows_1252(bytes: &[u8]) -> Result<Cow<'_, str>, InvalidText> {
109    if bytes.is_ascii() {
110        return std::str::from_utf8(bytes)
111            .map(Cow::Borrowed)
112            .map_err(|_| InvalidText);
113    }
114    let mut out = String::with_capacity(bytes.len());
115    for &byte in bytes {
116        let ch = match byte {
117            0x80..=0x9F => *CP1252_HIGH
118                .get(usize::from(byte - 0x80))
119                .ok_or(InvalidText)?
120                .as_ref()
121                .ok_or(InvalidText)?,
122            other => char::from(other),
123        };
124        out.push(ch);
125    }
126    Ok(Cow::Owned(out))
127}
128
129fn decode_utf16(bytes: &[u8], byte_order: ByteOrder) -> Result<Cow<'_, str>, InvalidText> {
130    if bytes.len() % 2 != 0 {
131        return Err(InvalidText);
132    }
133    let units: Vec<u16> = bytes
134        .chunks_exact(2)
135        .map(|pair| {
136            let hi = pair.first().copied().unwrap_or(0);
137            let lo = pair.get(1).copied().unwrap_or(0);
138            match byte_order {
139                ByteOrder::MostSignificantFirst => u16::from_be_bytes([hi, lo]),
140                ByteOrder::LeastSignificantFirst => u16::from_le_bytes([hi, lo]),
141            }
142        })
143        .collect();
144    String::from_utf16(&units)
145        .map(Cow::Owned)
146        .map_err(|_| InvalidText)
147}
148
149fn decode_utf32(bytes: &[u8], byte_order: ByteOrder) -> Result<Cow<'_, str>, InvalidText> {
150    if bytes.len() % 4 != 0 {
151        return Err(InvalidText);
152    }
153    let mut out = String::with_capacity(bytes.len() / 4);
154    for chunk in bytes.chunks_exact(4) {
155        let mut word = [0u8; 4];
156        word.copy_from_slice(chunk);
157        let scalar = match byte_order {
158            ByteOrder::MostSignificantFirst => u32::from_be_bytes(word),
159            ByteOrder::LeastSignificantFirst => u32::from_le_bytes(word),
160        };
161        out.push(char::from_u32(scalar).ok_or(InvalidText)?);
162    }
163    Ok(Cow::Owned(out))
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn ascii_is_borrowed_in_every_single_byte_charset() {
172        for charset in [
173            Charset::Utf8,
174            Charset::UsAscii,
175            Charset::Iso8859_1,
176            Charset::Windows1252,
177        ] {
178            let decoded = decode(b"STATUS OK", charset, ByteOrder::MostSignificantFirst)
179                .expect("ascii decodes");
180            assert!(matches!(decoded, Cow::Borrowed(_)), "{charset:?} allocated");
181            assert_eq!(decoded, "STATUS OK");
182        }
183    }
184
185    #[test]
186    fn latin1_maps_every_byte() {
187        let decoded = decode(
188            &[0xE9, 0xF1],
189            Charset::Iso8859_1,
190            ByteOrder::MostSignificantFirst,
191        )
192        .expect("latin-1 has no invalid bytes");
193        assert_eq!(decoded, "éñ");
194    }
195
196    #[test]
197    fn windows_1252_rejects_undefined_code_points() {
198        assert_eq!(
199            decode(
200                &[0x80],
201                Charset::Windows1252,
202                ByteOrder::MostSignificantFirst
203            )
204            .as_deref(),
205            Ok("€")
206        );
207        assert_eq!(
208            decode(
209                &[0x81],
210                Charset::Windows1252,
211                ByteOrder::MostSignificantFirst
212            ),
213            Err(InvalidText)
214        );
215    }
216
217    #[test]
218    fn invalid_utf8_is_an_error_not_a_replacement_character() {
219        assert_eq!(
220            decode(
221                &[0xFF, 0xFE],
222                Charset::Utf8,
223                ByteOrder::MostSignificantFirst
224            ),
225            Err(InvalidText)
226        );
227        assert_eq!(
228            decode(&[0x80], Charset::UsAscii, ByteOrder::MostSignificantFirst),
229            Err(InvalidText)
230        );
231    }
232
233    #[test]
234    fn utf16_honours_byte_order() {
235        assert_eq!(
236            decode(
237                &[0x00, 0x21],
238                Charset::Utf16,
239                ByteOrder::MostSignificantFirst
240            )
241            .as_deref(),
242            Ok("!")
243        );
244        assert_eq!(
245            decode(
246                &[0x21, 0x00],
247                Charset::Utf16,
248                ByteOrder::LeastSignificantFirst
249            )
250            .as_deref(),
251            Ok("!")
252        );
253        assert_eq!(
254            decode(&[0x00], Charset::Utf16, ByteOrder::MostSignificantFirst),
255            Err(InvalidText)
256        );
257        // Lone surrogate.
258        assert_eq!(
259            decode(
260                &[0xD8, 0x00],
261                Charset::Utf16,
262                ByteOrder::MostSignificantFirst
263            ),
264            Err(InvalidText)
265        );
266    }
267
268    #[test]
269    fn utf32_honours_byte_order() {
270        assert_eq!(
271            decode(
272                &[0x00, 0x00, 0x00, 0x41],
273                Charset::Utf32,
274                ByteOrder::MostSignificantFirst
275            )
276            .as_deref(),
277            Ok("A")
278        );
279        assert_eq!(
280            decode(
281                &[0x41, 0x00, 0x00, 0x00],
282                Charset::Utf32,
283                ByteOrder::LeastSignificantFirst
284            )
285            .as_deref(),
286            Ok("A")
287        );
288        assert_eq!(
289            decode(
290                &[0xFF, 0xFF, 0xFF, 0xFF],
291                Charset::Utf32,
292                ByteOrder::MostSignificantFirst
293            ),
294            Err(InvalidText)
295        );
296    }
297}