1use std::borrow::Cow;
8
9use xtce_model::{ByteOrder, Charset};
10
11#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13pub struct InvalidText;
14
15pub 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#[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
71const CP1252_HIGH: [Option<char>; 32] = [
74 Some('\u{20AC}'), None, Some('\u{201A}'), Some('\u{0192}'), Some('\u{201E}'), Some('\u{2026}'), Some('\u{2020}'), Some('\u{2021}'), Some('\u{02C6}'), Some('\u{2030}'), Some('\u{0160}'), Some('\u{2039}'), Some('\u{0152}'), None, Some('\u{017D}'), None, None, Some('\u{2018}'), Some('\u{2019}'), Some('\u{201C}'), Some('\u{201D}'), Some('\u{2022}'), Some('\u{2013}'), Some('\u{2014}'), Some('\u{02DC}'), Some('\u{2122}'), Some('\u{0161}'), Some('\u{203A}'), Some('\u{0153}'), None, Some('\u{017E}'), Some('\u{0178}'), ];
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 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}