Skip to main content

decode_bom

Function decode_bom 

Source
pub fn decode_bom(bytes: &[u8]) -> String
Expand description

Decode a byte sequence into text, transcoding from whichever of UTF-8, UTF-16 LE/BE or UTF-32 LE/BE its byte-order mark indicates. UTF-8 is the default when there is no mark, so BOM-less UTF-8 files with non-ASCII tag names round-trip. The mark itself is dropped.

Use this when reading XML files of unknown encoding:

let body = tabnas_xml::decode_bom(&std::fs::read("doc.xml")?);
let doc = tabnas_xml::parse(&body)?;

A malformed UTF-8 sequence is not an error here: each of its bytes becomes the character with that code, as the canonical decoder does, so a stray control byte is still reported as an illegal XML character by the parser rather than vanishing in transcoding. A unit that is not a Unicode scalar value, in any of the encodings, becomes U+FFFF rather than U+FFFD, because U+FFFD is a legal NameChar and folding to it would turn ill-formed documents into well-formed ones, while U+FFFF is excluded from NameChar as a surrogate is.

What that buys is narrower than “the document is rejected”, and the difference matters to a caller. This parser checks character data for the illegal C0 controls (check_chars), not for the whole of Char, which the package states it does not implement. Writing the substitute as U, every context measured on this port rather than reasoned about:

U<a/>                         ERROR text_at_top_level
<a/>U                         ERROR text_at_top_level
<dU/>                         ERROR xml_invalid_tag
<d>U</d>                      parses
<d a="U"/>                    parses
<d><!-- U --></d>             parses
<d><![CDATA[U]]></d>          parses
<d><?pi U?></d>               parses
<!DOCTYPE d [<!ELEMENT U ANY>]><d/>   parses

So it is refused in an ELEMENT OR ATTRIBUTE name, and accepted in text, attribute values, comments, CDATA, processing instructions and DTD declaration names. The first two rows are not a Char check at all: any character data outside the root is text_at_top_level, and the substitute is rejected there for the same reason a letter is. The last row is a NAME that is not refused, because declaration syntax is not validated – so “refused in a name” would be wrong in both directions, which is how an earlier draft of this comment put it.

So decode_bom followed by parse is not full XML Char validation, and a caller who needs that has to add it. The not_a_scalar function in this module carries the full reasoning for the choice of U+FFFF.