Skip to main content

einvoice_xml/
encoding.rs

1//! The character encoding of a document given as bytes, and its decoding to UTF-8 before
2//! it is read (XML 1.0, 4.3.3 and Appendix F).
3//!
4//! The encodings read are those that the two reference parsers of e-invoice validation,
5//! libxml2 (`xmllint`) and the XML parser of Saxon-HE (the Xerces of the JDK), both read
6//! the same way, among those found in e-invoices: UTF-8, UTF-16 (either byte order),
7//! US-ASCII, ISO-8859-1, ISO-8859-15 and windows-1252, each under the names both accept.
8//! Any other encoding is refused as unsupported, rather than read differently from them.
9//! The names both accept are those of their reference environment (libxml2 2.9.14 built
10//! with iconv and ICU, on Ubuntu 24.04, and Java 21), where the encoding oracle of the
11//! crate records them: libxml2 looks most names up in iconv and ICU, and the names it
12//! accepts depend on the tables of the system.
13
14use std::borrow::Cow;
15
16use crate::{Error, TextPos};
17
18/// A character encoding that [`decode`] reads.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum Encoding {
22    /// UTF-8, the default.
23    Utf8,
24    /// UTF-16, little-endian.
25    Utf16Le,
26    /// UTF-16, big-endian.
27    Utf16Be,
28    /// US-ASCII: the bytes below 0x80.
29    UsAscii,
30    /// ISO-8859-1 (Latin-1): each byte is the character of that code point.
31    Iso8859_1,
32    /// ISO-8859-15 (Latin-9): ISO-8859-1 with the euro sign and seven other letters.
33    Iso8859_15,
34    /// windows-1252: ISO-8859-1 with printable characters from 0x80 to 0x9F, five of
35    /// which (0x81, 0x8D, 0x8F, 0x90, 0x9D) are no character.
36    Windows1252,
37}
38
39impl Encoding {
40    /// The preferred name of the encoding (IANA).
41    #[must_use]
42    pub const fn name(self) -> &'static str {
43        match self {
44            Self::Utf8 => "UTF-8",
45            Self::Utf16Le => "UTF-16LE",
46            Self::Utf16Be => "UTF-16BE",
47            Self::UsAscii => "US-ASCII",
48            Self::Iso8859_1 => "ISO-8859-1",
49            Self::Iso8859_15 => "ISO-8859-15",
50            Self::Windows1252 => "windows-1252",
51        }
52    }
53}
54
55/// What the `encoding` of an XML declaration names.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum Named {
58    /// One of the encodings read.
59    Is(Encoding),
60    /// `UTF-16`, without a byte order.
61    Utf16,
62    /// A name that is not an encoding name (`EncName`): the reader reports it.
63    Invalid,
64    /// Any other encoding.
65    Other,
66}
67
68/// The names of each encoding read that both reference parsers accept (compared without
69/// regard to case, as both do).
70const NAMES: &[(&str, Named)] = &[
71    ("UTF-8", Named::Is(Encoding::Utf8)),
72    ("UTF8", Named::Is(Encoding::Utf8)),
73    ("unicode-1-1-utf-8", Named::Is(Encoding::Utf8)),
74    ("UTF-16", Named::Utf16),
75    ("UTF-16LE", Named::Is(Encoding::Utf16Le)),
76    ("UTF-16BE", Named::Is(Encoding::Utf16Be)),
77    ("US-ASCII", Named::Is(Encoding::UsAscii)),
78    ("ASCII", Named::Is(Encoding::UsAscii)),
79    ("ANSI_X3.4-1968", Named::Is(Encoding::UsAscii)),
80    ("ANSI_X3.4-1986", Named::Is(Encoding::UsAscii)),
81    ("ISO646-US", Named::Is(Encoding::UsAscii)),
82    ("ISO-IR-6", Named::Is(Encoding::UsAscii)),
83    ("CP367", Named::Is(Encoding::UsAscii)),
84    ("IBM367", Named::Is(Encoding::UsAscii)),
85    ("US", Named::Is(Encoding::UsAscii)),
86    ("csASCII", Named::Is(Encoding::UsAscii)),
87    ("ISO-8859-1", Named::Is(Encoding::Iso8859_1)),
88    ("ISO_8859-1", Named::Is(Encoding::Iso8859_1)),
89    ("ISO8859-1", Named::Is(Encoding::Iso8859_1)),
90    ("ISO-IR-100", Named::Is(Encoding::Iso8859_1)),
91    ("latin1", Named::Is(Encoding::Iso8859_1)),
92    ("l1", Named::Is(Encoding::Iso8859_1)),
93    ("CP819", Named::Is(Encoding::Iso8859_1)),
94    ("IBM819", Named::Is(Encoding::Iso8859_1)),
95    ("csISOLatin1", Named::Is(Encoding::Iso8859_1)),
96    ("ISO8859_1", Named::Is(Encoding::Iso8859_1)),
97    ("ISO_8859_1", Named::Is(Encoding::Iso8859_1)),
98    ("ISO-8859-15", Named::Is(Encoding::Iso8859_15)),
99    ("ISO_8859-15", Named::Is(Encoding::Iso8859_15)),
100    ("ISO8859-15", Named::Is(Encoding::Iso8859_15)),
101    ("LATIN-9", Named::Is(Encoding::Iso8859_15)),
102    ("latin9", Named::Is(Encoding::Iso8859_15)),
103    ("csISOLatin9", Named::Is(Encoding::Iso8859_15)),
104    ("L9", Named::Is(Encoding::Iso8859_15)),
105    ("LATIN0", Named::Is(Encoding::Iso8859_15)),
106    ("windows-1252", Named::Is(Encoding::Windows1252)),
107    ("cp1252", Named::Is(Encoding::Windows1252)),
108];
109
110/// Every name of an encoding read that [`decode`] accepts in an XML declaration, with
111/// the encoding (`None` for `UTF-16`, whose byte order is that of the byte order mark or
112/// of the first bytes).
113pub fn encoding_names() -> impl Iterator<Item = (&'static str, Option<Encoding>)> {
114    NAMES.iter().map(|&(name, named)| {
115        (
116            name,
117            match named {
118                Named::Is(encoding) => Some(encoding),
119                _ => None,
120            },
121        )
122    })
123}
124
125/// What an encoding name names.
126fn named(name: &str) -> Named {
127    let valid = name.bytes().next().is_some_and(|b| b.is_ascii_alphabetic())
128        && name
129            .bytes()
130            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
131    if !valid {
132        return Named::Invalid;
133    }
134    NAMES
135        .iter()
136        .find(|(n, _)| n.eq_ignore_ascii_case(name))
137        .map_or(Named::Other, |&(_, named)| named)
138}
139
140/// What the first bytes of a document say of its encoding (XML 1.0, Appendix F).
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142enum Signature {
143    /// A UTF-8 byte order mark (3 bytes).
144    Utf8Bom,
145    /// A UTF-16 byte order mark (2 bytes).
146    Utf16Bom(Encoding),
147    /// `<?` in UTF-16, without a byte order mark.
148    Utf16(Encoding),
149    /// Nothing: UTF-8 or an encoding the declaration names.
150    None,
151}
152
153/// The signature of `bytes`, or the name of an encoding that is not read: UCS-4 (four
154/// bytes per character, with `<` or a byte order mark in one of its byte orders) or
155/// EBCDIC (`<?xm`).
156fn signature(bytes: &[u8]) -> Result<Signature, Error> {
157    let unsupported = |name: &str| Err(Error::UnsupportedEncoding(name.to_owned()));
158    match bytes {
159        [0xEF, 0xBB, 0xBF, ..] => Ok(Signature::Utf8Bom),
160        [0xFE, 0xFF, ..] => Ok(Signature::Utf16Bom(Encoding::Utf16Be)),
161        [0xFF, 0xFE, ..] => Ok(Signature::Utf16Bom(Encoding::Utf16Le)),
162        [0x00, 0x00, 0xFE, 0xFF, ..]
163        | [0x00, 0x00, 0x00, 0x3C, ..]
164        | [0x3C, 0x00, 0x00, 0x00, ..]
165        | [0x00, 0x00, 0x3C, 0x00, ..]
166        | [0x00, 0x3C, 0x00, 0x00, ..] => unsupported("UCS-4"),
167        [0x4C, 0x6F, 0xA7, 0x94, ..] => unsupported("EBCDIC"),
168        [0x3C, 0x00, 0x3F, 0x00, ..] => Ok(Signature::Utf16(Encoding::Utf16Le)),
169        [0x00, 0x3C, 0x00, 0x3F, ..] => Ok(Signature::Utf16(Encoding::Utf16Be)),
170        _ => Ok(Signature::None),
171    }
172}
173
174/// XML whitespace (`S`).
175const fn is_space(b: u8) -> bool {
176    matches!(b, b' ' | b'\t' | b'\r' | b'\n')
177}
178
179/// The value of the `encoding` pseudo-attribute of the XML declaration at the start of
180/// `text` (ASCII-compatible bytes, after the byte order mark), as XML 1.0 writes it:
181/// `<?xml`, whitespace, `version`, `=` and a quoted value, whitespace, `encoding`, `=`
182/// and a quoted value. `None` when the text does not start so: without an encoding
183/// declaration, or with a malformed declaration, which the reader reports.
184fn declared_encoding(text: &[u8]) -> Option<&[u8]> {
185    let rest = text.strip_prefix(b"<?xml")?;
186    let rest = spaces(rest)?;
187    let rest = pseudo_attribute(rest, b"version")?.1;
188    let rest = spaces(rest)?;
189    pseudo_attribute(rest, b"encoding").map(|(value, _)| value)
190}
191
192/// What follows one or more whitespace characters, if `bytes` starts with one.
193fn spaces(bytes: &[u8]) -> Option<&[u8]> {
194    let n = bytes.iter().take_while(|&&b| is_space(b)).count();
195    (n > 0).then(|| &bytes[n..])
196}
197
198/// `name`, `=` (with optional whitespace around it) and a quoted value at the start of
199/// `bytes`: the value and what follows.
200fn pseudo_attribute<'b>(bytes: &'b [u8], name: &[u8]) -> Option<(&'b [u8], &'b [u8])> {
201    let rest = bytes.strip_prefix(name)?;
202    let rest = &rest[rest.iter().take_while(|&&b| is_space(b)).count()..];
203    let rest = rest.strip_prefix(b"=")?;
204    let rest = &rest[rest.iter().take_while(|&&b| is_space(b)).count()..];
205    let (&quote, rest) = rest.split_first()?;
206    if quote != b'"' && quote != b'\'' {
207        return None;
208    }
209    let end = rest.iter().position(|&b| b == quote)?;
210    Some((&rest[..end], &rest[end + 1..]))
211}
212
213/// The encoding of a document: the bytes after its byte order mark (if any) and the
214/// encoding they are in.
215fn resolve(bytes: &[u8]) -> Result<(Encoding, usize), Error> {
216    match signature(bytes)? {
217        Signature::Utf16Bom(encoding) => Ok((encoding, 2)),
218        Signature::Utf16(encoding) => Ok((encoding, 0)),
219        Signature::Utf8Bom => Ok((declared(&bytes[3..], "a UTF-8 byte order mark")?, 3)),
220        Signature::None => Ok((declared(bytes, "UTF-8 (no byte order mark)")?, 0)),
221    }
222}
223
224/// The encoding of ASCII-compatible `bytes` (after a UTF-8 byte order mark, if any): the
225/// one its XML declaration names, UTF-8 without one. `found` describes what the first
226/// bytes say, for an XML declaration that names UTF-16.
227fn declared(bytes: &[u8], found: &'static str) -> Result<Encoding, Error> {
228    let Some(name) = declared_encoding(bytes) else {
229        return Ok(Encoding::Utf8);
230    };
231    let name = String::from_utf8_lossy(name);
232    match named(&name) {
233        Named::Is(Encoding::Utf16Le | Encoding::Utf16Be) | Named::Utf16 => {
234            Err(Error::EncodingMismatch {
235                found,
236                declared: name.into_owned(),
237            })
238        }
239        Named::Is(encoding) => Ok(encoding),
240        // The reader reports the invalid name, in the text read as UTF-8.
241        Named::Invalid => Ok(Encoding::Utf8),
242        Named::Other => Err(Error::UnsupportedEncoding(name.into_owned())),
243    }
244}
245
246/// Checks the XML declaration of a document decoded from UTF-16 (`encoding`, given by
247/// the byte order mark or the first bytes): it may name UTF-16, or the same byte order.
248fn check_utf16_declaration(text: &str, encoding: Encoding, bom: bool) -> Result<(), Error> {
249    let Some(name) = declared_encoding(text.as_bytes()) else {
250        return Ok(());
251    };
252    // The declaration is ASCII: decoded from UTF-16, it is valid UTF-8 on its own.
253    let name = String::from_utf8_lossy(name);
254    match named(&name) {
255        Named::Utf16 | Named::Invalid => Ok(()),
256        Named::Is(declared) if declared == encoding => Ok(()),
257        Named::Other => Err(Error::UnsupportedEncoding(name.into_owned())),
258        Named::Is(_) => Err(Error::EncodingMismatch {
259            found: match (bom, encoding) {
260                (true, Encoding::Utf16Le) => "a UTF-16LE byte order mark",
261                (true, _) => "a UTF-16BE byte order mark",
262                (false, Encoding::Utf16Le) => "UTF-16LE (from the first bytes)",
263                (false, _) => "UTF-16BE (from the first bytes)",
264            },
265            declared: name.into_owned(),
266        }),
267    }
268}
269
270/// The text of a document given as bytes, in UTF-8, without its byte order mark: the
271/// bytes themselves when they are UTF-8 (no copy), decoded otherwise.
272///
273/// The encoding is found as XML 1.0 (4.3.3, Appendix F) says and as the reference
274/// parsers find it: a UTF-16 byte order mark, or `<?` in UTF-16 at the start, gives
275/// UTF-16 in that byte order, and the XML declaration may then name `UTF-16` or that byte
276/// order; otherwise the encoding is the one the XML declaration names, UTF-8 without one
277/// (after a UTF-8 byte order mark too, the declaration giving the encoding of what
278/// follows, as both reference parsers read it). See [`Encoding`] for the encodings read,
279/// and [`encoding_names`] for their names.
280///
281/// # Errors
282///
283/// [`Error::UnsupportedEncoding`] for an encoding not read (named by the XML
284/// declaration, or UCS-4 and EBCDIC by the first bytes);
285/// [`Error::EncodingMismatch`] when the XML declaration names UTF-16 in a document that
286/// is not (no UTF-16 byte order mark nor `<?` in UTF-16), or another encoding in a
287/// document that is; [`Error::InvalidEncodedBytes`] for bytes that are not a character
288/// of the encoding (in UTF-16, an unpaired surrogate or an odd number of bytes; in
289/// windows-1252, one of the five bytes that are no character), at the position of the
290/// character they would be in the text; [`Error::UnknownToken`] at 1:1 for a text that
291/// starts with U+FEFF after the byte order mark (a second byte order mark), which the
292/// [`Reader`](crate::Reader) would otherwise skip.
293pub fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, Error> {
294    let (encoding, start) = resolve(bytes)?;
295    let rest = &bytes[start..];
296    let text = match encoding {
297        Encoding::Utf8 => Cow::Borrowed(utf8(rest)?),
298        _ => Cow::Owned(decode_other(rest, encoding, start > 0)?),
299    };
300    no_second_bom(&text)?;
301    Ok(text)
302}
303
304/// [`decode`] on a buffer, which becomes the text without a copy when it is UTF-8 (the
305/// byte order mark, if any, is removed in place).
306///
307/// # Errors
308///
309/// As [`decode`].
310pub fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
311    let (encoding, start) = resolve(&bytes)?;
312    let text = if encoding == Encoding::Utf8 {
313        bytes.drain(..start);
314        String::from_utf8(bytes).map_err(|e| {
315            let valid = &e.as_bytes()[..e.utf8_error().valid_up_to()];
316            // The prefix is UTF-8.
317            invalid(Encoding::Utf8, &String::from_utf8_lossy(valid))
318        })?
319    } else {
320        decode_other(&bytes[start..], encoding, start > 0)?
321    };
322    no_second_bom(&text)?;
323    Ok(text)
324}
325
326/// The encoding [`decode`] reads `bytes` in, without decoding them: what the first
327/// bytes say, and, unless they say UTF-16, what the XML declaration names.
328///
329/// # Errors
330///
331/// As [`decode`], for an encoding not read or an XML declaration naming UTF-16 in a
332/// document that is not; the declaration of a UTF-16 document is only checked when it
333/// is decoded.
334pub fn encoding_of(bytes: &[u8]) -> Result<Encoding, Error> {
335    resolve(bytes).map(|(encoding, _)| encoding)
336}
337
338/// `bytes` as UTF-8, or the error at the first byte that is not.
339fn utf8(bytes: &[u8]) -> Result<&str, Error> {
340    std::str::from_utf8(bytes).map_err(|e| {
341        let valid = &bytes[..e.valid_up_to()];
342        // The prefix is UTF-8.
343        invalid(Encoding::Utf8, &String::from_utf8_lossy(valid))
344    })
345}
346
347/// [`Error::InvalidEncodedBytes`] after the decoded text `before`.
348fn invalid(encoding: Encoding, before: &str) -> Error {
349    Error::InvalidEncodedBytes {
350        encoding: encoding.name(),
351        pos: TextPos::at(before, before.len()),
352    }
353}
354
355/// Refuses a text that starts with U+FEFF once its byte order mark is removed.
356fn no_second_bom(text: &str) -> Result<(), Error> {
357    if text.starts_with('\u{FEFF}') {
358        return Err(Error::UnknownToken(TextPos::new(1, 1)));
359    }
360    Ok(())
361}
362
363/// `bytes` (after the byte order mark) decoded from `encoding`, other than UTF-8.
364fn decode_other(bytes: &[u8], encoding: Encoding, bom: bool) -> Result<String, Error> {
365    let single: fn(u8) -> Option<char> = match encoding {
366        Encoding::Utf16Le | Encoding::Utf16Be => {
367            let text = utf16(bytes, encoding)?;
368            check_utf16_declaration(&text, encoding, bom)?;
369            return Ok(text);
370        }
371        Encoding::Utf8 => return utf8(bytes).map(str::to_owned),
372        Encoding::UsAscii => |b| b.is_ascii().then_some(char::from(b)),
373        Encoding::Iso8859_1 => |b| Some(char::from(b)),
374        Encoding::Iso8859_15 => |b| Some(iso_8859_15(b)),
375        Encoding::Windows1252 => windows_1252,
376    };
377    // Every byte is at most one character, of at most 3 bytes in UTF-8.
378    let mut text = String::with_capacity(bytes.len() + bytes.len() / 2);
379    for &b in bytes {
380        match single(b) {
381            Some(c) => text.push(c),
382            None => return Err(invalid(encoding, &text)),
383        }
384    }
385    Ok(text)
386}
387
388/// UTF-16 in the byte order of `encoding`: an odd number of bytes or an unpaired
389/// surrogate is an error.
390fn utf16(bytes: &[u8], encoding: Encoding) -> Result<String, Error> {
391    let (pairs, odd) = bytes.as_chunks::<2>();
392    let unit = |pair: &[u8; 2]| {
393        if encoding == Encoding::Utf16Le {
394            u16::from_le_bytes(*pair)
395        } else {
396            u16::from_be_bytes(*pair)
397        }
398    };
399    let mut text = String::with_capacity(bytes.len() + bytes.len() / 2);
400    for c in char::decode_utf16(pairs.iter().map(unit)) {
401        match c {
402            Ok(c) => text.push(c),
403            Err(_) => return Err(invalid(encoding, &text)),
404        }
405    }
406    if !odd.is_empty() {
407        return Err(invalid(encoding, &text));
408    }
409    Ok(text)
410}
411
412/// ISO-8859-15: ISO-8859-1 but for eight bytes.
413fn iso_8859_15(b: u8) -> char {
414    match b {
415        0xA4 => '\u{20AC}',
416        0xA6 => '\u{0160}',
417        0xA8 => '\u{0161}',
418        0xB4 => '\u{017D}',
419        0xB8 => '\u{017E}',
420        0xBC => '\u{0152}',
421        0xBD => '\u{0153}',
422        0xBE => '\u{0178}',
423        _ => char::from(b),
424    }
425}
426
427/// windows-1252 from 0x80 to 0x9F (`None`: no character), as Microsoft's table and the
428/// Unicode mapping (`bestfit1252.txt`, `CP1252.TXT`) give it.
429const WINDOWS_1252_80: [Option<char>; 32] = [
430    Some('\u{20AC}'),
431    None,
432    Some('\u{201A}'),
433    Some('\u{0192}'),
434    Some('\u{201E}'),
435    Some('\u{2026}'),
436    Some('\u{2020}'),
437    Some('\u{2021}'),
438    Some('\u{02C6}'),
439    Some('\u{2030}'),
440    Some('\u{0160}'),
441    Some('\u{2039}'),
442    Some('\u{0152}'),
443    None,
444    Some('\u{017D}'),
445    None,
446    None,
447    Some('\u{2018}'),
448    Some('\u{2019}'),
449    Some('\u{201C}'),
450    Some('\u{201D}'),
451    Some('\u{2022}'),
452    Some('\u{2013}'),
453    Some('\u{2014}'),
454    Some('\u{02DC}'),
455    Some('\u{2122}'),
456    Some('\u{0161}'),
457    Some('\u{203A}'),
458    Some('\u{0153}'),
459    None,
460    Some('\u{017E}'),
461    Some('\u{0178}'),
462];
463
464/// windows-1252.
465fn windows_1252(b: u8) -> Option<char> {
466    match b {
467        0x80..=0x9F => WINDOWS_1252_80[usize::from(b - 0x80)],
468        _ => Some(char::from(b)),
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    fn utf16le(text: &str) -> Vec<u8> {
477        text.encode_utf16().flat_map(u16::to_le_bytes).collect()
478    }
479
480    fn utf16be(text: &str) -> Vec<u8> {
481        text.encode_utf16().flat_map(u16::to_be_bytes).collect()
482    }
483
484    #[test]
485    fn utf8_is_borrowed() {
486        assert!(matches!(decode(b"<a/>").unwrap(), Cow::Borrowed("<a/>")));
487        assert!(matches!(
488            decode(b"\xEF\xBB\xBF<a>\xC3\xA9</a>").unwrap(),
489            Cow::Borrowed("<a>\u{e9}</a>")
490        ));
491        let declared = "<?xml version='1.0' encoding='utf8'?><a/>";
492        assert!(matches!(decode(declared.as_bytes()).unwrap(), Cow::Borrowed(t) if t == declared));
493        assert_eq!(decode_owned(b"\xEF\xBB\xBF<a/>".to_vec()).unwrap(), "<a/>");
494    }
495
496    #[test]
497    fn utf16_with_and_without_a_byte_order_mark() {
498        let text = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><a>\u{e9}\u{1F600}</a>";
499        for (bytes, bom) in [
500            ([&[0xFF, 0xFE][..], &utf16le(text)].concat(), true),
501            ([&[0xFE, 0xFF][..], &utf16be(text)].concat(), true),
502            (utf16le(text), false),
503            (utf16be(text), false),
504        ] {
505            assert_eq!(decode(&bytes).unwrap(), text, "{bom}");
506            assert_eq!(decode_owned(bytes).unwrap(), text);
507        }
508        // Without a declaration, after a byte order mark.
509        let bytes = [&[0xFF, 0xFE][..], &utf16le("<a/>")].concat();
510        assert_eq!(decode(&bytes).unwrap(), "<a/>");
511        assert_eq!(encoding_of(&bytes).unwrap(), Encoding::Utf16Le);
512        // The byte order named.
513        let le = "<?xml version='1.0' encoding='utf-16le'?><a/>";
514        assert_eq!(decode(&utf16le(le)).unwrap(), le);
515        // The other byte order, or another encoding: a mismatch.
516        let be = "<?xml version='1.0' encoding='UTF-16BE'?><a/>";
517        assert!(matches!(
518            decode(&utf16le(be)),
519            Err(Error::EncodingMismatch { declared, .. }) if declared == "UTF-16BE"
520        ));
521        let latin = "<?xml version='1.0' encoding='ISO-8859-1'?><a/>";
522        assert!(matches!(
523            decode(&[&[0xFF, 0xFE][..], &utf16le(latin)].concat()),
524            Err(Error::EncodingMismatch { .. })
525        ));
526        for name in ["ISO-10646-UCS-2", "UCS-2"] {
527            let ucs2 = format!("<?xml version='1.0' encoding='{name}'?><a/>");
528            assert_eq!(
529                decode(&[&[0xFE, 0xFF][..], &utf16be(&ucs2)].concat()),
530                Err(Error::UnsupportedEncoding(name.to_owned()))
531            );
532        }
533    }
534
535    #[test]
536    fn malformed_utf16() {
537        let bytes = [&[0xFF, 0xFE][..], &utf16le("<a>\n\u{e9}x")].concat();
538        let mut lone = bytes.clone();
539        lone.extend([0x00, 0xD8, b'<', 0]);
540        assert_eq!(
541            decode(&lone),
542            Err(Error::InvalidEncodedBytes {
543                encoding: "UTF-16LE",
544                pos: TextPos::new(2, 3)
545            })
546        );
547        let mut odd = bytes;
548        odd.push(b'>');
549        assert_eq!(
550            decode(&odd),
551            Err(Error::InvalidEncodedBytes {
552                encoding: "UTF-16LE",
553                pos: TextPos::new(2, 3)
554            })
555        );
556        // A low surrogate first.
557        let low = [&[0xFE, 0xFF][..], &[0xDC, 0x00]].concat();
558        assert!(matches!(
559            decode(&low),
560            Err(Error::InvalidEncodedBytes { pos, .. }) if pos == TextPos::new(1, 1)
561        ));
562    }
563
564    #[test]
565    fn single_byte_encodings() {
566        let decl = |name: &str| format!("<?xml version=\"1.0\" encoding=\"{name}\"?>");
567        let latin1 = [decl("ISO-8859-1").as_bytes(), b"<a>\xE9\x80\xA4</a>"].concat();
568        assert_eq!(
569            decode(&latin1).unwrap(),
570            format!("{}<a>\u{e9}\u{80}\u{a4}</a>", decl("ISO-8859-1"))
571        );
572        for name in ["latin9", "L9", "LATIN0", "csISOLatin9"] {
573            let latin9 = [decl(name).as_bytes(), b"<a>\xA4\xBE\xE9</a>"].concat();
574            assert_eq!(
575                decode(&latin9).unwrap(),
576                format!("{}<a>\u{20AC}\u{178}\u{e9}</a>", decl(name))
577            );
578        }
579        let cp1252 = [decl("Windows-1252").as_bytes(), b"<a>\x80\x9F\xFF</a>"].concat();
580        assert_eq!(
581            decode(&cp1252).unwrap(),
582            format!("{}<a>\u{20AC}\u{178}\u{ff}</a>", decl("Windows-1252"))
583        );
584        for b in [0x81, 0x8D, 0x8F, 0x90, 0x9D] {
585            let bytes = [decl("cp1252").as_bytes(), b"\n<a>x", &[b], b"</a>"].concat();
586            assert_eq!(
587                decode(&bytes),
588                Err(Error::InvalidEncodedBytes {
589                    encoding: "windows-1252",
590                    pos: TextPos::new(2, 5)
591                })
592            );
593        }
594        let ascii = [decl("US-ASCII").as_bytes(), b"<a>\xE9</a>"].concat();
595        assert!(matches!(
596            decode(&ascii),
597            Err(Error::InvalidEncodedBytes {
598                encoding: "US-ASCII",
599                ..
600            })
601        ));
602        // After a UTF-8 byte order mark, the declaration still gives the encoding.
603        let after_bom = [
604            b"\xEF\xBB\xBF",
605            decl("ISO-8859-1").as_bytes(),
606            b"<a>\xC3\xA9</a>",
607        ]
608        .concat();
609        assert_eq!(
610            decode_owned(after_bom).unwrap(),
611            format!("{}<a>\u{c3}\u{a9}</a>", decl("ISO-8859-1"))
612        );
613    }
614
615    #[test]
616    fn declarations() {
617        assert_eq!(
618            declared_encoding(b"<?xml version='1.0' encoding = \"latin1\" ?><a/>"),
619            Some(&b"latin1"[..])
620        );
621        assert_eq!(
622            declared_encoding(b"<?xml\nversion=\"1.0\"\r\n\tencoding='x'?>"),
623            Some(&b"x"[..])
624        );
625        for text in [
626            &b"<?xml version='1.0'?><a/>"[..],
627            b"<?xml version='1.0' standalone='yes'?>",
628            b"<?xml encoding='latin1'?>",
629            b"<?xml version='1.0'encoding='latin1'?>",
630            b"<?xmlversion='1.0' encoding='latin1'?>",
631            b" <?xml version='1.0' encoding='latin1'?>",
632            b"<?xml version='1.0' encoding='latin1",
633            b"<?xml version='1.0' encoding=latin1?>",
634            b"<a/>",
635            b"",
636        ] {
637            assert_eq!(declared_encoding(text), None, "{text:?}");
638        }
639    }
640
641    #[test]
642    fn names() {
643        assert_eq!(named("utf-8"), Named::Is(Encoding::Utf8));
644        assert_eq!(named("Latin1"), Named::Is(Encoding::Iso8859_1));
645        assert_eq!(named("WINDOWS-1252"), Named::Is(Encoding::Windows1252));
646        assert_eq!(named("utf-16"), Named::Utf16);
647        assert_eq!(named("ISO-10646-UCS-2"), Named::Other);
648        assert_eq!(named("UCS-2"), Named::Other);
649        assert_eq!(named("l9"), Named::Is(Encoding::Iso8859_15));
650        assert_eq!(named("iso8859_1"), Named::Is(Encoding::Iso8859_1));
651        assert_eq!(named("UNICODE-1-1-UTF-8"), Named::Is(Encoding::Utf8));
652        assert_eq!(named("UTF_8"), Named::Other);
653        assert_eq!(named("x-cp1252"), Named::Other);
654        assert_eq!(named("Shift_JIS"), Named::Other);
655        assert_eq!(named("ISO-8859-2"), Named::Other);
656        assert_eq!(named(""), Named::Invalid);
657        assert_eq!(named("1SO"), Named::Invalid);
658        assert_eq!(named(" UTF-8"), Named::Invalid);
659        assert_eq!(encoding_names().count(), NAMES.len());
660        for (name, encoding) in encoding_names() {
661            assert_eq!(encoding.is_none(), name == "UTF-16", "{name}");
662        }
663    }
664
665    #[test]
666    fn unsupported_and_mismatched() {
667        let decl = |name: &str| format!("<?xml version=\"1.0\" encoding=\"{name}\"?><a/>");
668        assert_eq!(
669            decode(decl("Shift_JIS").as_bytes()),
670            Err(Error::UnsupportedEncoding("Shift_JIS".to_owned()))
671        );
672        assert!(matches!(
673            decode(decl("UTF-16").as_bytes()),
674            Err(Error::EncodingMismatch { declared, .. }) if declared == "UTF-16"
675        ));
676        // An invalid name: read as UTF-8, the reader reports it.
677        assert!(decode(decl("1SO-8859-1").as_bytes()).is_ok());
678        assert_eq!(
679            decode(&[0x4C, 0x6F, 0xA7, 0x94, 0x40]),
680            Err(Error::UnsupportedEncoding("EBCDIC".to_owned()))
681        );
682        assert_eq!(
683            decode(b"<\0\0\0a\0\0\0"),
684            Err(Error::UnsupportedEncoding("UCS-4".to_owned()))
685        );
686        // A second byte order mark.
687        assert_eq!(
688            decode(b"\xEF\xBB\xBF\xEF\xBB\xBF<a/>"),
689            Err(Error::UnknownToken(TextPos::new(1, 1)))
690        );
691        assert_eq!(
692            decode_owned(b"\xFF\xFE\xFF\xFE<\0a\0/\0>\0".to_vec()),
693            Err(Error::UnknownToken(TextPos::new(1, 1)))
694        );
695        assert_eq!(
696            decode(b"<a>\n  \xC3\xA9\xFF</a>"),
697            Err(Error::InvalidEncodedBytes {
698                encoding: "UTF-8",
699                pos: TextPos::new(2, 4)
700            })
701        );
702        assert_eq!(
703            decode_owned(b"\xEF\xBB\xBF<a>\n\xFF</a>".to_vec()),
704            Err(Error::InvalidEncodedBytes {
705                encoding: "UTF-8",
706                pos: TextPos::new(2, 1)
707            })
708        );
709    }
710}