Skip to main content

parsec_xml/
bytes.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Bytes in: the encoding from the byte order mark, else the first bytes'
5//! pattern and the XML declaration (XML 1.0, appendix F), decoded with
6//! encoding_rs, strictly, since bytes that aren't the encoding are a
7//! fatal error in XML.
8
9use std::borrow::Cow;
10
11use encoding_rs::{DecoderResult, Encoding, UTF_8, UTF_16BE, UTF_16LE};
12use parsec_base::{Diagnostic, LineCol, Span};
13
14use crate::{Document, Error, Options, parse_with};
15
16/// A document parsed from bytes, and the text it was decoded to.
17#[derive(Debug)]
18pub struct Parsed<'b> {
19    pub document: Document,
20    /// The encoding the bytes were decoded from.
21    pub encoding: &'static Encoding,
22    /// The decoded text, without a byte order mark: the document's spans
23    /// are offsets into it. Borrowed from the bytes when they're UTF-8.
24    pub text: Cow<'b, str>,
25}
26
27fn fail(code: &'static str, message: String) -> Error {
28    Error {
29        diagnostic: Diagnostic::error(code, Span::at(0), message),
30        position: LineCol { line: 1, column: 1 },
31    }
32}
33
34/// The encoding an XML declaration in ASCII names, if there is one.
35fn declared(bytes: &[u8]) -> Option<&[u8]> {
36    let end = bytes.iter().take(1024).position(|&b| b == b'>')?;
37    let decl = bytes[..end].strip_prefix(b"<?xml")?;
38    let at = decl.windows(8).position(|w| w == b"encoding")?;
39    let rest = &decl[at + 8..];
40    let rest = rest
41        .trim_ascii_start()
42        .strip_prefix(b"=")?
43        .trim_ascii_start();
44    let (&q, rest) = rest.split_first()?;
45    if q != b'"' && q != b'\'' {
46        return None;
47    }
48    Some(&rest[..rest.iter().position(|&b| b == q)?])
49}
50
51/// The encoding of `bytes` and the length of its byte order mark.
52fn sniff(bytes: &[u8]) -> Result<(&'static Encoding, usize), Error> {
53    if let Some(found) = Encoding::for_bom(bytes) {
54        return Ok(found);
55    }
56    match bytes.get(..4) {
57        Some([0x3C, 0, 0x3F, 0]) => return Ok((UTF_16LE, 0)),
58        Some([0, 0x3C, 0, 0x3F]) => return Ok((UTF_16BE, 0)),
59        Some([0, 0, 0, 0x3C] | [0x3C, 0, 0, 0] | [0, 0, 0x3C, 0] | [0, 0x3C, 0, 0])
60        | Some([0, 0, 0xFE, 0xFF] | [0xFF, 0xFE, 0, 0]) => {
61            return Err(fail(
62                "unsupported-encoding",
63                "the document is in UCS-4, which Parsec doesn't decode".into(),
64            ));
65        }
66        Some([0x4C, 0x6F, 0xA7, 0x94]) => {
67            return Err(fail(
68                "unsupported-encoding",
69                "the document is in EBCDIC, which Parsec doesn't decode".into(),
70            ));
71        }
72        _ => {}
73    }
74    let Some(label) = declared(bytes) else {
75        return Ok((UTF_8, 0));
76    };
77    let name = String::from_utf8_lossy(label);
78    match Encoding::for_label_no_replacement(label) {
79        // The bytes so far were ASCII, so a document in UTF-16 would have
80        // started with a byte order mark.
81        Some(e) if e == UTF_16LE || e == UTF_16BE => Err(fail(
82            "encoding-mismatch",
83            format!("the document says it's in {name}, but it has no byte order mark"),
84        )),
85        Some(e) => Ok((e, 0)),
86        None => Err(fail(
87            "unsupported-encoding",
88            format!("`{name}` isn't an encoding Parsec knows"),
89        )),
90    }
91}
92
93/// Parses a document given as bytes.
94///
95/// ```
96/// let latin1 = b"<?xml version='1.0' encoding='ISO-8859-1'?><p>caf\xe9</p>";
97/// let parsed = parsec_xml::parse_bytes(latin1, &Default::default()).unwrap();
98/// assert_eq!(parsed.encoding.name(), "windows-1252");
99/// assert_eq!(parsed.document.text(parsed.document.root()), "café");
100/// ```
101pub fn parse_bytes<'b>(bytes: &'b [u8], options: &Options) -> Result<Parsed<'b>, Error> {
102    options.limits.check_input(bytes.len()).map_err(|d| Error {
103        diagnostic: d,
104        position: LineCol { line: 1, column: 1 },
105    })?;
106    let (encoding, bom) = sniff(bytes)?;
107    let body = &bytes[bom..];
108    let text: Cow<'b, str> = if encoding == UTF_8 {
109        match std::str::from_utf8(body) {
110            Ok(s) => Cow::Borrowed(s),
111            Err(e) => {
112                let good = std::str::from_utf8(&body[..e.valid_up_to()]).unwrap_or("");
113                return Err(malformed(good, encoding));
114            }
115        }
116    } else {
117        let mut decoder = encoding.new_decoder_without_bom_handling();
118        let mut out = String::with_capacity(
119            decoder
120                .max_utf8_buffer_length_without_replacement(body.len())
121                .unwrap_or(body.len()),
122        );
123        let (result, _) = decoder.decode_to_string_without_replacement(body, &mut out, true);
124        match result {
125            DecoderResult::InputEmpty => Cow::Owned(out),
126            DecoderResult::Malformed(..) | DecoderResult::OutputFull => {
127                return Err(malformed(&out, encoding));
128            }
129        }
130    };
131    let document = parse_with(&text, options)?;
132    // A declaration can't contradict the byte order mark or the bytes'
133    // pattern that the encoding was found from.
134    if let Some(decl) = document.xml_decl()
135        && let Some(label) = &decl.encoding
136        && (bom > 0 || encoding == UTF_16LE || encoding == UTF_16BE)
137    {
138        let utf16 = |e: &'static Encoding| e == UTF_16LE || e == UTF_16BE;
139        let agrees = Encoding::for_label(label.as_bytes())
140            .is_some_and(|d| d == encoding || utf16(d) && utf16(encoding));
141        if !agrees {
142            return Err(Error::new(
143                Diagnostic::error(
144                    "encoding-mismatch",
145                    decl.span,
146                    format!(
147                        "the document says it's in {label}, but its first bytes say {}",
148                        encoding.name()
149                    ),
150                ),
151                &text,
152            ));
153        }
154    }
155    Ok(Parsed {
156        document,
157        encoding,
158        text,
159    })
160}
161
162/// An error for bytes that aren't `encoding`, after the text `good`.
163fn malformed(good: &str, encoding: &'static Encoding) -> Error {
164    let at = good.len() as u32;
165    Error::new(
166        Diagnostic::error(
167            "invalid-byte-sequence",
168            Span::at(at),
169            format!("the bytes here aren't {}", encoding.name()),
170        ),
171        good,
172    )
173}