1#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Confidence {
45 Tentative,
49 Certain,
52}
53
54#[cfg(feature = "parse")]
55#[derive(Debug, Clone, Copy)]
57pub struct Options {
58 pub html: parsec::Options,
60 pub transport: Option<&'static Encoding>,
64 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")]
83pub struct Parsed {
85 pub document: Document,
86 pub encoding: &'static Encoding,
89 pub confidence: Confidence,
90}
91
92pub 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
116pub(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
137fn 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 Err(e) => !complete && e.error_len().is_none(),
147 }
148}
149
150#[cfg(feature = "parse")]
151pub fn parse_bytes(bytes: &[u8], options: Options) -> Result<Parsed, ParseError> {
168 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 let (text, _) = encoding.decode_with_bom_removal(bytes);
201 parsec::parse_with(&text, options)
202}
203
204#[cfg(feature = "parse")]
205fn 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")]
232fn 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
242pub 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 "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 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 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 assert_eq!(parse(b"<p>caf\xe9").encoding, WINDOWS_1252);
395 assert_eq!(parse(b"<p>cafe").encoding, WINDOWS_1252);
396 assert_eq!(parse(b"<p>\xe6\x97").encoding, WINDOWS_1252);
398 let page = "<meta charset=windows-1251><p>\u{e9}".as_bytes();
400 assert_eq!(parse(page).encoding, WINDOWS_1251);
401 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#[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 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 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}