Skip to main content

tabnas_xml/
bom.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Byte-order-mark handling: the port of `decodeBOM` in `ts/src/xml.ts`.
4
5/// Decode a byte sequence into text, transcoding from whichever of UTF-8,
6/// UTF-16 LE/BE or UTF-32 LE/BE its byte-order mark indicates. UTF-8 is
7/// the default when there is no mark, so BOM-less UTF-8 files with
8/// non-ASCII tag names round-trip. The mark itself is dropped.
9///
10/// Use this when reading XML files of unknown encoding:
11///
12/// ```no_run
13/// let body = tabnas_xml::decode_bom(&std::fs::read("doc.xml")?);
14/// let doc = tabnas_xml::parse(&body)?;
15/// # Ok::<(), Box<dyn std::error::Error>>(())
16/// ```
17///
18/// A malformed UTF-8 sequence is not an error here: each of its bytes
19/// becomes the character with that code, as the canonical decoder does,
20/// so a stray control byte is still reported as an illegal XML character
21/// by the parser rather than vanishing in transcoding. A unit that is not
22/// a Unicode scalar value, in any of the encodings, becomes U+FFFF rather
23/// than U+FFFD, because U+FFFD is a legal `NameChar` and folding to it
24/// would turn ill-formed documents into well-formed ones, while U+FFFF is
25/// excluded from `NameChar` as a surrogate is.
26///
27/// What that buys is narrower than "the document is rejected", and the
28/// difference matters to a caller. This parser checks character data for
29/// the illegal C0 controls (`check_chars`), not for the whole of `Char`,
30/// which the package states it does not implement. Writing the
31/// substitute as `U`, every context measured on this port rather than
32/// reasoned about:
33///
34/// ```text
35/// U<a/>                         ERROR text_at_top_level
36/// <a/>U                         ERROR text_at_top_level
37/// <dU/>                         ERROR xml_invalid_tag
38/// <d>U</d>                      parses
39/// <d a="U"/>                    parses
40/// <d><!-- U --></d>             parses
41/// <d><![CDATA[U]]></d>          parses
42/// <d><?pi U?></d>               parses
43/// <!DOCTYPE d [<!ELEMENT U ANY>]><d/>   parses
44/// ```
45///
46/// So it is refused in an ELEMENT OR ATTRIBUTE name, and accepted in
47/// text, attribute values, comments, CDATA, processing instructions and
48/// DTD declaration names. The first two rows are not a `Char` check at
49/// all: any character data outside the root is `text_at_top_level`, and
50/// the substitute is rejected there for the same reason a letter is. The
51/// last row is a NAME that is not refused, because declaration syntax is
52/// not validated -- so "refused in a name" would be wrong in both
53/// directions, which is how an earlier draft of this comment put it.
54///
55/// So `decode_bom` followed by `parse` is not full XML `Char` validation,
56/// and a caller who needs that has to add it. The `not_a_scalar` function
57/// in this module carries the full reasoning for the choice of U+FFFF.
58pub fn decode_bom(bytes: &[u8]) -> String {
59    match bytes {
60        [0x00, 0x00, 0xfe, 0xff, rest @ ..] => decode_utf32(rest, true),
61        [0xff, 0xfe, 0x00, 0x00, rest @ ..] => decode_utf32(rest, false),
62        [0xfe, 0xff, rest @ ..] => decode_utf16(rest, true),
63        [0xff, 0xfe, rest @ ..] => decode_utf16(rest, false),
64        [0xef, 0xbb, 0xbf, rest @ ..] => decode_utf8(rest),
65        rest => decode_utf8(rest),
66    }
67}
68
69/// Strip a leading U+FEFF from text that is already decoded: the string
70/// arm of the canonical `decodeBOM`.
71pub fn strip_bom(src: &str) -> &str {
72    src.strip_prefix('\u{FEFF}').unwrap_or(src)
73}
74
75/// The stand-in for a code point Rust cannot hold in a `String`: an
76/// unpaired surrogate (and, from UTF-32, a value above U+10FFFF).
77///
78/// TypeScript keeps an unpaired surrogate as it is, because JavaScript
79/// strings are UTF-16, and Go keeps the raw bytes, because Go strings are
80/// byte sequences. Both then let the XML checks downstream reject it: a
81/// surrogate is neither an XML `Char` (2.2 [2]) nor a `NameChar`
82/// (2.3 [4a]), so a document carrying one is not well formed, and all
83/// three runtimes must say so.
84///
85/// A Rust `String` holds Unicode scalar values only, so the surrogate
86/// cannot survive decoding. Folding it to U+FFFD would be worse than
87/// lossy: U+FFFD IS a valid `NameStartChar` (it closes the
88/// `[#xFDF0-#xFFFD]` range), so an ill-formed document would become well
89/// formed and the port would accept what TypeScript and Go reject. That
90/// happened here: eight `eduni/errata-4e` conformance documents with
91/// surrogates in element names were accepted until this mapping changed.
92///
93/// U+FFFF is the faithful substitute. Like a surrogate it is excluded
94/// from `Char` and from `NameChar`, so every XML check reaches the same
95/// verdict on it that it reaches on the surrogate it replaces. The two
96/// are distinguishable only by a caller inspecting the decoded text
97/// directly, never by the well-formedness of the document.
98///
99/// This is narrower than the engine-wide rule in the parser's
100/// `DIVERGENCE.md` ("lone surrogates -> U+FFFD"), and deliberately so:
101/// that rule governs a character VALUE parsed out of a document, such as
102/// `&#xD800;`, where Go and Rust agree on U+FFFD and only the stored
103/// value differs. This function governs SOURCE TEXT, where the same fold
104/// would change the verdict rather than the value.
105fn not_a_scalar(code: u32) -> char {
106    debug_assert!(
107        char::from_u32(code).is_none(),
108        "{code:#x} is a scalar value"
109    );
110    '\u{FFFF}'
111}
112
113fn decode_utf8(bytes: &[u8]) -> String {
114    let mut out = String::with_capacity(bytes.len());
115    let mut i = 0;
116    while i < bytes.len() {
117        let lead = bytes[i];
118        if lead < 0x80 {
119            out.push(lead as char);
120            i += 1;
121            continue;
122        }
123        let tail = |offset: usize| u32::from(bytes[i + offset] & 0x3f);
124        let (code, advance) = if lead & 0xe0 == 0xc0 && i + 1 < bytes.len() {
125            ((u32::from(lead & 0x1f) << 6) | tail(1), 2)
126        } else if lead & 0xf0 == 0xe0 && i + 2 < bytes.len() {
127            ((u32::from(lead & 0x0f) << 12) | (tail(1) << 6) | tail(2), 3)
128        } else if lead & 0xf8 == 0xf0 && i + 3 < bytes.len() {
129            (
130                (u32::from(lead & 0x07) << 18) | (tail(1) << 12) | (tail(2) << 6) | tail(3),
131                4,
132            )
133        } else {
134            (u32::MAX, 1)
135        };
136        // A malformed sequence (an invalid lead byte, a truncated tail, or
137        // a code point out of range) emits the raw byte and moves on one
138        // position, so the downstream XML check can flag it.
139        if code > 0x10ffff {
140            out.push(char::from(lead));
141            i += 1;
142        } else {
143            out.push(char::from_u32(code).unwrap_or_else(|| not_a_scalar(code)));
144            i += advance;
145        }
146    }
147    out
148}
149
150fn decode_utf16(bytes: &[u8], big: bool) -> String {
151    let units = bytes.chunks_exact(2).map(|pair| {
152        if big {
153            u16::from_be_bytes([pair[0], pair[1]])
154        } else {
155            u16::from_le_bytes([pair[0], pair[1]])
156        }
157    });
158    char::decode_utf16(units)
159        .map(|unit| match unit {
160            Ok(c) => c,
161            Err(unpaired) => not_a_scalar(u32::from(unpaired.unpaired_surrogate())),
162        })
163        .collect()
164}
165
166fn decode_utf32(bytes: &[u8], big: bool) -> String {
167    bytes
168        .chunks_exact(4)
169        .map(|quad| {
170            let quad = [quad[0], quad[1], quad[2], quad[3]];
171            let code = if big {
172                u32::from_be_bytes(quad)
173            } else {
174                u32::from_le_bytes(quad)
175            };
176            char::from_u32(code).unwrap_or_else(|| not_a_scalar(code))
177        })
178        .collect()
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn every_encoding_signature_is_honoured() {
187        assert_eq!(decode_bom(b"\xef\xbb\xbf<a/>"), "<a/>");
188        assert_eq!(decode_bom(b"<\xc3\xa9/>"), "<é/>");
189        assert_eq!(decode_bom(b"\xfe\xff\x00<\x00a\x00/\x00>"), "<a/>");
190        assert_eq!(decode_bom(b"\xff\xfe<\x00a\x00/\x00>\x00"), "<a/>");
191        assert_eq!(
192            decode_bom(b"\x00\x00\xfe\xff\x00\x00\x00<\x00\x00\x00a\x00\x00\x00/\x00\x00\x00>"),
193            "<a/>"
194        );
195        assert_eq!(
196            decode_bom(b"\xff\xfe\x00\x00<\x00\x00\x00a\x00\x00\x00/\x00\x00\x00>\x00\x00\x00"),
197            "<a/>"
198        );
199        assert_eq!(decode_bom(b""), "");
200    }
201
202    #[test]
203    fn malformed_utf8_keeps_the_raw_byte() {
204        assert_eq!(decode_bom(b"a\x01\xffb"), "a\u{1}\u{ff}b");
205        assert_eq!(decode_bom(b"\xf0\x9f\x98\x80"), "\u{1F600}");
206        assert_eq!(decode_bom(b"\xe2\x82"), "\u{e2}\u{82}");
207    }
208
209    #[test]
210    fn an_unpaired_surrogate_stays_invalid() {
211        // U+D800 as CESU-8 style bytes, as eight `eduni/errata-4e`
212        // conformance documents spell it. The decoded character must not
213        // be a NameStartChar, or those documents parse as well formed.
214        assert_eq!(decode_bom(b"\xed\xa0\x80"), "\u{FFFF}");
215        assert!(!crate::entity::is_name_start('\u{FFFF}'));
216        assert!(!crate::entity::is_name_char('\u{FFFF}'));
217        // U+FFFD would be, which is why it is not used here.
218        assert!(crate::entity::is_name_start('\u{FFFD}'));
219
220        // The same in UTF-16 (an unpaired high surrogate) and UTF-32.
221        assert_eq!(decode_bom(b"\xfe\xff\xd8\x00"), "\u{FFFF}");
222        assert_eq!(decode_bom(b"\x00\x00\xfe\xff\x00\x00\xd8\x00"), "\u{FFFF}");
223
224        // A surrogate PAIR is a scalar value and is unaffected.
225        assert_eq!(decode_bom(b"\xfe\xff\xd8\x3d\xde\x00"), "\u{1F600}");
226    }
227
228    #[test]
229    fn a_decoded_string_only_loses_its_mark() {
230        assert_eq!(strip_bom("\u{FEFF}<a/>"), "<a/>");
231        assert_eq!(strip_bom("<a>\u{FEFF}</a>"), "<a>\u{FEFF}</a>");
232    }
233}