Skip to main content

parsec_encoding/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Bytes into Parsec. [`parse_bytes`] finds a page's encoding the way the
5//! HTML Standard says a browser does, decodes it and parses it.
6//! [`ByteParser`] does the same with the bytes as they arrive.
7//!
8//! The decoding is [`encoding_rs`], Firefox's implementation of the WHATWG
9//! Encoding Standard, re-exported here. It has every encoding the web
10//! uses, decoding and encoding, whole or streamed:
11//!
12//! ```
13//! use parsec_encoding::Encoding;
14//!
15//! let sjis = Encoding::for_label(b"sjis").unwrap();
16//! assert_eq!(sjis.name(), "Shift_JIS");
17//! let (text, _, had_errors) = sjis.decode(b"\x93\xfa\x96\x7b");
18//! assert_eq!((&*text, had_errors), ("日本", false));
19//! let (bytes, _, _) = sjis.encode("日本");
20//! assert_eq!(&*bytes, b"\x93\xfa\x96\x7b");
21//! ```
22
23#[cfg(feature = "parse")]
24use std::time::Instant;
25
26use encoding_rs::UTF_8;
27pub use encoding_rs::{self, Encoding};
28#[cfg(feature = "parse")]
29use encoding_rs::{UTF_16BE, UTF_16LE};
30#[cfg(feature = "parse")]
31use parsec::{AttrNs, Document, Kind, NodeId, Ns, ParseError};
32
33mod prescan;
34pub use prescan::prescan;
35#[cfg(feature = "parse")]
36mod stream;
37#[cfg(feature = "parse")]
38pub use stream::ByteParser;
39mod offsets;
40pub use offsets::Offsets;
41
42/// How sure the parser is of an encoding, in the HTML Standard's terms.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Confidence {
45    /// A guess: from the prescan, the UTF-8 autodetection or the
46    /// fallback. A `<meta>` the parser
47    /// meets can still change it.
48    Tentative,
49    /// From a byte order mark, the transport layer, or a `<meta>` that
50    /// agreed with the guess or replaced it.
51    Certain,
52}
53
54#[cfg(feature = "parse")]
55/// How to turn bytes into a document.
56#[derive(Debug, Clone, Copy)]
57pub struct Options {
58    /// The parse itself.
59    pub html: parsec::Options,
60    /// The encoding the transport layer gave, such as the `charset` in an
61    /// HTTP `Content-Type`: look it up with [`Encoding::for_label`]. A byte
62    /// order mark still wins over it, as in browsers.
63    pub transport: Option<&'static Encoding>,
64    /// The encoding when nothing in or around the page names one and its
65    /// bytes aren't valid UTF-8: windows-1252 by default, as in browsers set to English.
66    /// [`locale_default`] gives the one a browser in another language
67    /// would use.
68    pub fallback: &'static Encoding,
69}
70
71#[cfg(feature = "parse")]
72impl Default for Options {
73    fn default() -> Self {
74        Options {
75            html: parsec::Options::default(),
76            transport: None,
77            fallback: encoding_rs::WINDOWS_1252,
78        }
79    }
80}
81
82#[cfg(feature = "parse")]
83/// A document parsed from bytes, and how its encoding was decided.
84pub struct Parsed {
85    pub document: Document,
86    /// The encoding the document was decoded with: what JavaScript's
87    /// `document.characterSet` would say.
88    pub encoding: &'static Encoding,
89    pub confidence: Confidence,
90}
91
92/// The HTML Standard's encoding sniffing algorithm, for a parser that has
93/// every byte: the byte order mark, then `transport`, then the prescan of
94/// the first 1,024 bytes, then autodetection, then `fallback`.
95///
96/// The spec lets a browser guess from the bytes before falling back, and
97/// browsers do: Firefox's chardetng and Chrome's CED both recognise
98/// UTF-8. Parsec's guess is that one only, and deterministic: bytes with
99/// something beyond ASCII that are all valid UTF-8 are UTF-8, tentative,
100/// so a later `<meta>` can still change it. Anything else falls back.
101///
102/// ```
103/// use parsec_encoding::{Confidence, sniff};
104/// let page = b"<meta charset=windows-1251><p>\xcf\xf0\xe8\xe2\xe5\xf2";
105/// let found = sniff(page, None, encoding_rs::WINDOWS_1252);
106/// assert_eq!(found, (encoding_rs::WINDOWS_1251, Confidence::Tentative));
107/// ```
108pub fn sniff(
109    bytes: &[u8],
110    transport: Option<&'static Encoding>,
111    fallback: &'static Encoding,
112) -> (&'static Encoding, Confidence) {
113    guess(bytes, transport, fallback, true)
114}
115
116/// [`sniff`] for `bytes` that are the whole input when `complete`, or
117/// only its start, where a UTF-8 sequence cut off at the end still counts.
118pub(crate) fn guess(
119    bytes: &[u8],
120    transport: Option<&'static Encoding>,
121    fallback: &'static Encoding,
122    complete: bool,
123) -> (&'static Encoding, Confidence) {
124    if let Some((bom, _)) = Encoding::for_bom(bytes) {
125        return (bom, Confidence::Certain);
126    }
127    if let Some(given) = transport {
128        return (given, Confidence::Certain);
129    }
130    match prescan(&bytes[..bytes.len().min(1024)]) {
131        Some(declared) => (declared, Confidence::Tentative),
132        None if looks_like_utf8(bytes, complete) => (UTF_8, Confidence::Tentative),
133        None => (fallback, Confidence::Tentative),
134    }
135}
136
137/// The autodetection step: something beyond ASCII, and every byte valid
138/// UTF-8. Pure ASCII says nothing, so it's left to the fallback.
139fn looks_like_utf8(bytes: &[u8], complete: bool) -> bool {
140    if bytes.is_ascii() {
141        return false;
142    }
143    match std::str::from_utf8(bytes) {
144        Ok(_) => true,
145        // `error_len` is None for a sequence the end cut short.
146        Err(e) => !complete && e.error_len().is_none(),
147    }
148}
149
150#[cfg(feature = "parse")]
151/// Parses a page given as bytes, as a browser would: sniffs its encoding
152/// ([`sniff`]), decodes it and parses it.
153///
154/// When the encoding was only a guess and the parser meets a `<meta>`
155/// declaring another one (past the first 1,024 bytes, say), the spec has
156/// the browser start again in the declared encoding. Here that's a second
157/// decode and parse of the same bytes, once at most, since the encoding
158/// is certain after it. The time budget covers both parses together.
159///
160/// ```
161/// use parsec_encoding::{Options, parse_bytes};
162/// let page = b"<meta charset=shift_jis><title>\x93\xfa\x96\x7b</title>";
163/// let parsed = parse_bytes(page, Options::default()).unwrap();
164/// assert_eq!(parsed.encoding, encoding_rs::SHIFT_JIS);
165/// assert_eq!(parsed.document.text(parsed.document.root()), "日本");
166/// ```
167pub fn parse_bytes(bytes: &[u8], options: Options) -> Result<Parsed, ParseError> {
168    // The clock is read only for a budget, so that WebAssembly, which has
169    // none, still works.
170    let start = options.html.budget.map(|_| Instant::now());
171    let (mut encoding, mut confidence) = sniff(bytes, options.transport, options.fallback);
172    let mut document = decode_and_parse(bytes, encoding, options.html)?;
173    if confidence == Confidence::Tentative
174        && let Some(declared) = declared(&document)
175    {
176        confidence = Confidence::Certain;
177        if let Some(new) = changed(encoding, declared) {
178            encoding = new;
179            let mut html = options.html;
180            let spent = start.map_or(Default::default(), |t| t.elapsed());
181            html.budget = html.budget.map(|b| b.saturating_sub(spent));
182            document = decode_and_parse(bytes, encoding, html)?;
183        }
184    }
185    Ok(Parsed {
186        document,
187        encoding,
188        confidence,
189    })
190}
191
192#[cfg(feature = "parse")]
193fn decode_and_parse(
194    bytes: &[u8],
195    encoding: &'static Encoding,
196    options: parsec::Options,
197) -> Result<Document, ParseError> {
198    // Any byte order mark already chose `encoding`, so removing one for
199    // `encoding` is the Encoding Standard's "decode".
200    let (text, _) = encoding.decode_with_bom_removal(bytes);
201    parsec::parse_with(&text, options)
202}
203
204#[cfg(feature = "parse")]
205/// The first encoding a `<meta>` declares as the tree builder sees it: by
206/// `charset`, or by `http-equiv="Content-Type"` with a `content` naming
207/// one. The parser makes elements in the order it meets their tags, so
208/// node order is that order, `<template>` contents included.
209fn declared(doc: &Document) -> Option<&'static Encoding> {
210    (0..doc.len() as NodeId).find_map(|id| {
211        if !matches!(doc.kind(id), Kind::Element { ns: Ns::Html, .. })
212            || doc.lower_name(id) != Some("meta")
213        {
214            return None;
215        }
216        let attr = |want: &str| {
217            doc.attrs(id)
218                .find(|&(ns, name, _)| ns == AttrNs::None && name == want)
219                .map(|(_, _, value)| value)
220        };
221        if let Some(found) = attr("charset").and_then(|v| Encoding::for_label(v.as_bytes())) {
222            return Some(found);
223        }
224        attr("http-equiv")
225            .filter(|v| v.eq_ignore_ascii_case("content-type"))
226            .and(attr("content"))
227            .and_then(|v| prescan::charset_in_content(v.as_bytes()))
228    })
229}
230
231#[cfg(feature = "parse")]
232/// "Change the encoding": the encoding to parse again in, or `None` when
233/// the one in use stands.
234fn changed(current: &'static Encoding, declared: &'static Encoding) -> Option<&'static Encoding> {
235    if current == UTF_16BE || current == UTF_16LE {
236        return None;
237    }
238    let new = prescan::as_declared(declared);
239    (new != current).then_some(new)
240}
241
242/// The fallback encoding a browser uses for a user whose language is
243/// `locale` (a BCP 47 tag such as `ja`, `ru-RU` or `zh-Hant`), from the
244/// HTML Standard's table of suggested defaults. Pass it as
245/// [`Options::fallback`] when you know your users' language, or a site's.
246///
247/// ```
248/// use parsec_encoding::locale_default;
249/// assert_eq!(locale_default("ja-JP"), encoding_rs::SHIFT_JIS);
250/// assert_eq!(locale_default("zh-TW"), encoding_rs::BIG5);
251/// assert_eq!(locale_default("en-GB"), encoding_rs::WINDOWS_1252);
252/// ```
253pub fn locale_default(locale: &str) -> &'static Encoding {
254    use encoding_rs::*;
255    let locale = locale.to_ascii_lowercase();
256    let mut tags = locale.split(['-', '_']);
257    match tags.next().unwrap_or("") {
258        "ar" | "fa" => WINDOWS_1256,
259        "az" | "ku" | "tr" => WINDOWS_1254,
260        "ba" | "be" | "bg" | "kk" | "ky" | "mk" | "ru" | "sah" | "sr" | "tg" | "tt" | "uk" => {
261            WINDOWS_1251
262        }
263        "cs" | "hr" | "sk" => WINDOWS_1250,
264        "el" => ISO_8859_7,
265        "et" | "lt" | "lv" => WINDOWS_1257,
266        "he" => WINDOWS_1255,
267        "hu" | "pl" | "sl" => ISO_8859_2,
268        "ja" => SHIFT_JIS,
269        "ko" => EUC_KR,
270        "th" => WINDOWS_874,
271        "vi" => WINDOWS_1258,
272        // The script subtag comes before the region, so it decides first.
273        "zh" => tags
274            .find_map(|t| match t {
275                "hans" | "cn" | "sg" => Some(GBK),
276                "hant" | "hk" | "mo" | "tw" => Some(BIG5),
277                _ => None,
278            })
279            .unwrap_or(WINDOWS_1252),
280        _ => WINDOWS_1252,
281    }
282}
283
284#[cfg(feature = "parse")]
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use encoding_rs::{EUC_JP, SHIFT_JIS, UTF_8, WINDOWS_1251, WINDOWS_1252};
289
290    fn parse(bytes: &[u8]) -> Parsed {
291        parse_bytes(bytes, Options::default()).unwrap()
292    }
293
294    #[test]
295    fn bom_beats_transport_and_meta() {
296        let page = b"\xef\xbb\xbf<meta charset=euc-jp>\xc3\xa9";
297        let options = Options {
298            transport: Some(SHIFT_JIS),
299            ..Options::default()
300        };
301        let p = parse_bytes(page, options).unwrap();
302        assert_eq!((p.encoding, p.confidence), (UTF_8, Confidence::Certain));
303        assert_eq!(p.document.text(p.document.root()), "é");
304    }
305
306    #[test]
307    fn utf16_bom_is_removed() {
308        let p = parse(b"\xff\xfe<\0p\0>\0h\0i\0");
309        assert_eq!(p.encoding, UTF_16LE);
310        assert_eq!(p.document.text(p.document.root()), "hi");
311    }
312
313    #[test]
314    fn transport_is_certain() {
315        let options = Options {
316            transport: Some(WINDOWS_1251),
317            ..Options::default()
318        };
319        let p = parse_bytes(b"<meta charset=euc-jp>\xcf", options).unwrap();
320        assert_eq!(
321            (p.encoding, p.confidence),
322            (WINDOWS_1251, Confidence::Certain)
323        );
324        assert_eq!(p.document.text(p.document.root()), "П");
325    }
326
327    #[test]
328    fn late_meta_reparses() {
329        let mut page = b"<!doctype html><title>".to_vec();
330        page.extend(std::iter::repeat_n(b'x', 1100));
331        page.extend(b"</title><meta charset=windows-1251><p>\xcf");
332        let p = parse(&page);
333        assert_eq!(
334            (p.encoding, p.confidence),
335            (WINDOWS_1251, Confidence::Certain)
336        );
337        assert!(p.document.text(p.document.root()).ends_with('П'));
338    }
339
340    #[test]
341    fn agreeing_meta_makes_it_certain() {
342        let p = parse(b"<meta charset=euc-jp>");
343        assert_eq!((p.encoding, p.confidence), (EUC_JP, Confidence::Certain));
344        let p = parse(b"<p>no declaration");
345        assert_eq!(
346            (p.encoding, p.confidence),
347            (WINDOWS_1252, Confidence::Tentative)
348        );
349    }
350
351    #[test]
352    fn late_http_equiv_and_svg_meta() {
353        let mut page = b"<!-- ".to_vec();
354        page.extend(std::iter::repeat_n(b'x', 1100));
355        page.extend(b" --><svg><meta charset=euc-jp></svg>");
356        // An SVG <meta> breaks out of foreign content, so it's HTML's.
357        assert_eq!(parse(&page).encoding, EUC_JP);
358        let mut page = b"<!-- ".to_vec();
359        page.extend(std::iter::repeat_n(b'x', 1100));
360        page.extend(b" --><meta http-equiv=content-type content='text/html;charset=sjis'>");
361        assert_eq!(parse(&page).encoding, SHIFT_JIS);
362    }
363
364    #[test]
365    fn later_metas_and_utf16_declarations() {
366        let mut page = b"<!-- ".to_vec();
367        page.extend(std::iter::repeat_n(b'x', 1100));
368        page.extend(b" --><meta charset=bogus><meta charset=utf-16><meta charset=sjis>");
369        // The first that names an encoding decides; UTF-16 means UTF-8.
370        assert_eq!(parse(&page).encoding, UTF_8);
371    }
372
373    #[test]
374    fn budget_covers_both_parses() {
375        let mut page = b"<title>".to_vec();
376        page.extend(std::iter::repeat_n(b'x', 1100));
377        page.extend(b"</title><meta charset=windows-1251>");
378        let options = Options {
379            html: parsec::Options {
380                budget: Some(std::time::Duration::from_secs(60)),
381                ..parsec::Options::default()
382            },
383            ..Options::default()
384        };
385        assert_eq!(parse_bytes(&page, options).unwrap().encoding, WINDOWS_1251);
386    }
387
388    #[test]
389    fn valid_utf8_is_detected() {
390        let p = parse("<p>caf\u{e9}".as_bytes());
391        assert_eq!((p.encoding, p.confidence), (UTF_8, Confidence::Tentative));
392        assert_eq!(p.document.text(p.document.root()), "caf\u{e9}");
393        // Not valid UTF-8, or nothing but ASCII: the fallback.
394        assert_eq!(parse(b"<p>caf\xe9").encoding, WINDOWS_1252);
395        assert_eq!(parse(b"<p>cafe").encoding, WINDOWS_1252);
396        // Cut off at the end of the whole input isn't valid.
397        assert_eq!(parse(b"<p>\xe6\x97").encoding, WINDOWS_1252);
398        // A transport encoding or a <meta> comes first.
399        let page = "<meta charset=windows-1251><p>\u{e9}".as_bytes();
400        assert_eq!(parse(page).encoding, WINDOWS_1251);
401        // And a late <meta> can still change the guess.
402        let mut page = "<title>\u{e9}".as_bytes().to_vec();
403        page.extend(std::iter::repeat_n(b'x', 1100));
404        page.extend(b"</title><meta charset=windows-1251>");
405        let p = parse(&page);
406        assert_eq!(
407            (p.encoding, p.confidence),
408            (WINDOWS_1251, Confidence::Certain)
409        );
410    }
411}
412
413// What the crate is without `parse`: sniffing and the locale defaults.
414#[cfg(test)]
415mod sniff_tests {
416    use super::*;
417    use encoding_rs::{SHIFT_JIS, UTF_8, WINDOWS_1251, WINDOWS_1252};
418
419    #[test]
420    fn locales() {
421        assert_eq!(locale_default("RU"), WINDOWS_1251);
422        assert_eq!(locale_default("zh-Hans-HK"), encoding_rs::GBK);
423        assert_eq!(locale_default("zh"), WINDOWS_1252);
424        assert_eq!(locale_default(""), WINDOWS_1252);
425    }
426
427    #[test]
428    fn sniff_order() {
429        let meta = b"<meta charset=euc-jp>";
430        // A byte order mark beats the transport encoding, and that beats <meta>.
431        let mut bom = b"\xef\xbb\xbf".to_vec();
432        bom.extend(meta);
433        assert_eq!(
434            sniff(&bom, Some(SHIFT_JIS), WINDOWS_1252),
435            (UTF_8, Confidence::Certain)
436        );
437        assert_eq!(
438            sniff(meta, Some(SHIFT_JIS), WINDOWS_1252),
439            (SHIFT_JIS, Confidence::Certain)
440        );
441        assert_eq!(
442            sniff(meta, None, WINDOWS_1252),
443            (encoding_rs::EUC_JP, Confidence::Tentative)
444        );
445        // Valid non-ASCII UTF-8, then the fallback.
446        assert_eq!(
447            sniff("<p>caf\u{e9}".as_bytes(), None, WINDOWS_1252),
448            (UTF_8, Confidence::Tentative)
449        );
450        assert_eq!(
451            sniff(b"<p>cafe", None, WINDOWS_1251),
452            (WINDOWS_1251, Confidence::Tentative)
453        );
454    }
455}