Skip to main content

feedparser_rs/util/
encoding.rs

1//! Encoding detection and conversion utilities
2//!
3//! This module provides functions for detecting character encoding
4//! and converting to UTF-8.
5//!
6//! Encoding detection follows this priority order:
7//! 1. BOM (Byte Order Mark) - highest priority
8//! 2. HTTP Content-Type charset (if provided)
9//! 3. XML declaration encoding attribute
10//! 4. Default to UTF-8
11//!
12//! The feed parser walks this order as a fallback chain: it skips labels it cannot
13//! use. When the bytes disprove the chosen label or fail to decode with it, UTF-8 and
14//! then the XML declaration are tried strictly before invalid bytes are replaced.
15//!
16//! A UTF-32 byte order mark is decoded here, since `encoding_rs` has no UTF-32.
17
18use std::borrow::Cow;
19
20use encoding_rs::{Encoding, REPLACEMENT, UTF_8, UTF_16BE, UTF_16LE};
21
22/// How faithfully a document was decoded.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub(crate) enum DecodeOutcome {
25    /// The chosen encoding decoded every byte.
26    Clean,
27    /// The declared encoding did not fit the bytes, which another one decoded.
28    Overridden { declared: &'static Encoding },
29    /// Invalid byte sequences were replaced with U+FFFD.
30    Lossy,
31}
32
33/// Byte order of a UTF-32 document.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(crate) enum Utf32Order {
36    Le,
37    Be,
38}
39
40impl Utf32Order {
41    const fn bom(self) -> &'static [u8] {
42        match self {
43            Self::Le => b"\xFF\xFE\x00\x00",
44            Self::Be => b"\x00\x00\xFE\xFF",
45        }
46    }
47
48    const fn name(self) -> &'static str {
49        match self {
50            Self::Le => "utf-32le",
51            Self::Be => "utf-32be",
52        }
53    }
54
55    fn from_label(label: &str) -> Option<Self> {
56        [Self::Le, Self::Be]
57            .into_iter()
58            .find(|order| label.trim().eq_ignore_ascii_case(order.name()))
59    }
60
61    /// Decodes `data`, replacing invalid units; the flag reports whether any were.
62    fn decode(self, data: &[u8]) -> (String, bool) {
63        let (units, tail) = data.as_chunks::<4>();
64        let mut had_errors = !tail.is_empty();
65        let mut text: String = units
66            .iter()
67            .map(|&unit| {
68                let scalar = match self {
69                    Self::Le => u32::from_le_bytes(unit),
70                    Self::Be => u32::from_be_bytes(unit),
71                };
72                char::from_u32(scalar).unwrap_or_else(|| {
73                    had_errors = true;
74                    char::REPLACEMENT_CHARACTER
75                })
76            })
77            .collect();
78        if !tail.is_empty() {
79            text.push(char::REPLACEMENT_CHARACTER);
80        }
81        (text, had_errors)
82    }
83}
84
85/// Splits a UTF-32 byte order mark off `data`.
86fn utf32_bom(data: &[u8]) -> Option<(Utf32Order, &[u8])> {
87    [Utf32Order::Le, Utf32Order::Be]
88        .into_iter()
89        .find_map(|order| Some((order, data.strip_prefix(order.bom())?)))
90}
91
92/// Recognizes BOM-less UTF-32 by the four bytes of a leading `<`.
93const fn utf32_markup(data: &[u8]) -> Option<(Utf32Order, &[u8])> {
94    match data {
95        [b'<', 0, 0, 0, ..] => Some((Utf32Order::Le, data)),
96        [0, 0, 0, b'<', ..] => Some((Utf32Order::Be, data)),
97        _ => None,
98    }
99}
100
101/// Encoding a document was decoded with.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub(crate) enum DocumentEncoding {
104    Whatwg(&'static Encoding),
105    Utf32(Utf32Order),
106}
107
108impl DocumentEncoding {
109    /// Lowercase name, as reported in `ParsedFeed::encoding`.
110    pub(crate) fn name(self) -> String {
111        match self {
112            Self::Whatwg(encoding) => encoding.name().to_ascii_lowercase(),
113            Self::Utf32(order) => order.name().to_string(),
114        }
115    }
116}
117
118/// A document decoded to UTF-8 for parsing.
119#[derive(Debug)]
120pub(crate) struct DecodedDocument<'a> {
121    /// Decoded text without a byte order mark.
122    pub(crate) text: Cow<'a, str>,
123    /// Encoding that produced `text`.
124    pub(crate) encoding: DocumentEncoding,
125    /// Whether decoding had to deviate from the declared encoding.
126    pub(crate) outcome: DecodeOutcome,
127}
128
129impl DecodedDocument<'_> {
130    /// Describes a decoding problem for `bozo_exception`, or `None` if decoding was clean.
131    pub(crate) fn problem(&self) -> Option<String> {
132        let used = self.encoding.name();
133        match self.outcome {
134            DecodeOutcome::Clean => None,
135            DecodeOutcome::Overridden { declared } => Some(format!(
136                "document declared as {} was decoded as {used}",
137                declared.name().to_ascii_lowercase()
138            )),
139            DecodeOutcome::Lossy => Some(format!(
140                "document is not valid {used}; invalid bytes were replaced"
141            )),
142        }
143    }
144}
145
146/// Decodes `data`, preferring BOM, then HTTP charset, then XML declaration, then UTF-8.
147pub(crate) fn decode_document<'a>(
148    data: &'a [u8],
149    content_type: Option<&str>,
150) -> DecodedDocument<'a> {
151    // Before any `encoding_rs` BOM sniffing: the UTF-32LE mark starts with the UTF-16LE one.
152    // A BOM-less `<` sniff goes before the UTF-16 heuristics for the same reason.
153    if let Some((order, body)) = utf32_bom(data).or_else(|| utf32_markup(data)) {
154        let (text, had_errors) = order.decode(body);
155        return DecodedDocument {
156            text: Cow::Owned(text),
157            encoding: DocumentEncoding::Utf32(order),
158            outcome: if had_errors {
159                DecodeOutcome::Lossy
160            } else {
161                DecodeOutcome::Clean
162            },
163        };
164    }
165
166    let candidate = candidate_encoding(data, content_type);
167    let lossy = if is_disproved(candidate, data) {
168        None
169    } else {
170        let (text, had_errors) = candidate.decode_with_bom_removal(data);
171        if !had_errors {
172            return DecodedDocument {
173                text,
174                encoding: DocumentEncoding::Whatwg(candidate),
175                outcome: DecodeOutcome::Clean,
176            };
177        }
178        Some(text)
179    };
180
181    if let Some((encoding, text)) = decode_strict_fallback(data) {
182        return DecodedDocument {
183            text,
184            encoding: DocumentEncoding::Whatwg(encoding),
185            outcome: DecodeOutcome::Overridden {
186                declared: candidate,
187            },
188        };
189    }
190
191    // A disproved label must not produce the replacement text either.
192    let (text, encoding) = lossy.map_or_else(
193        || (UTF_8.decode_without_bom_handling(data).0, UTF_8),
194        |text| (text, candidate),
195    );
196    DecodedDocument {
197        text,
198        encoding: DocumentEncoding::Whatwg(encoding),
199        outcome: DecodeOutcome::Lossy,
200    }
201}
202
203/// Decodes `data` without any replacement, as UTF-8 or else by its XML declaration.
204fn decode_strict_fallback(data: &[u8]) -> Option<(&'static Encoding, Cow<'_, str>)> {
205    let strict = |encoding: &'static Encoding| {
206        encoding
207            .decode_without_bom_handling_and_without_replacement(data)
208            .map(|text| (encoding, text))
209    };
210
211    strict(UTF_8).or_else(|| {
212        // A BOM outranks the declaration, and decoding past it would leak it into the text.
213        if Encoding::for_bom(data).is_some() {
214            return None;
215        }
216        xml_declaration_encoding(data)
217            .filter(|&encoding| encoding != REPLACEMENT && !is_disproved(encoding, data))
218            .and_then(strict)
219    })
220}
221
222fn candidate_encoding(data: &[u8], content_type: Option<&str>) -> &'static Encoding {
223    // `replacement` labels would discard the whole document.
224    let usable = |encoding: &&'static Encoding| *encoding != REPLACEMENT;
225
226    Encoding::for_bom(data)
227        .map(|(encoding, _)| encoding)
228        .or_else(|| {
229            content_type
230                // JSON is UTF-8 by definition (RFC 8259), so a header charset is noise.
231                .filter(|_| !sniffs_as_json(data))
232                .and_then(content_type_encoding)
233                .filter(usable)
234        })
235        .or_else(|| xml_declaration_encoding(data).filter(usable))
236        .unwrap_or(UTF_8)
237}
238
239/// Whether the bytes rule out `candidate` even though decoding with it may not fail.
240fn is_disproved(candidate: &'static Encoding, data: &[u8]) -> bool {
241    if candidate == UTF_16LE || candidate == UTF_16BE {
242        // BOM-less UTF-16 markup has a NUL next to its first `<`.
243        matches!(data.trim_ascii_start(), [b'<', second, ..] if *second != 0)
244    } else {
245        // Single-byte decoders accept UTF-8 and silently produce mojibake.
246        candidate.is_single_byte() && !data.is_ascii() && std::str::from_utf8(data).is_ok()
247    }
248}
249
250fn sniffs_as_json(data: &[u8]) -> bool {
251    data.trim_prefix(b"\xEF\xBB\xBF")
252        .trim_ascii_start()
253        .starts_with(b"{")
254}
255
256/// Detect character encoding from byte data
257///
258/// The feed parser applies a fallback chain on top of this detection.
259///
260/// Detection order:
261/// 1. BOM (Byte Order Mark)
262/// 2. XML declaration (`<?xml ... encoding="..."?>`)
263/// 3. Default to UTF-8
264///
265/// The declaration is honoured only at the start of the document (ASCII
266/// whitespace may precede it), and its closing `?>` must fall within the first
267/// 512 bytes. `encoding=` anywhere else is ignored.
268///
269/// # Arguments
270///
271/// * `data` - Raw byte data
272///
273/// # Returns
274///
275/// Detected encoding name (e.g., "utf-8", "iso-8859-1")
276///
277/// # Examples
278///
279/// ```
280/// use feedparser_rs::util::encoding::detect_encoding;
281///
282/// // UTF-8 with BOM
283/// let data = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>";
284/// assert_eq!(detect_encoding(data), "UTF-8");
285///
286/// // XML declaration
287/// let data = b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
288/// assert_eq!(detect_encoding(data), "windows-1252");
289/// ```
290pub fn detect_encoding(data: &[u8]) -> &'static str {
291    // Check BOM first
292    if let Some(bom_encoding) = detect_bom(data) {
293        return bom_encoding;
294    }
295
296    // Check XML declaration
297    if let Some(encoding) = xml_declaration_encoding(data) {
298        return encoding.name();
299    }
300
301    // Default to UTF-8
302    "UTF-8"
303}
304
305/// Extract encoding from XML declaration
306///
307/// Reads `encoding=` only from a `<?xml ... ?>` at the start of the document (after
308/// ASCII whitespace) that closes within the first 512 bytes, so the same text in the
309/// content is never taken for a declaration. The declaration is ASCII, so the search
310/// works on bytes.
311fn xml_declaration_encoding(data: &[u8]) -> Option<&'static Encoding> {
312    let head = &data[..data.len().min(512)];
313    let rest = head.trim_ascii_start().strip_prefix(b"<?xml")?;
314    if !rest.first()?.is_ascii_whitespace() {
315        return None;
316    }
317    let declaration = &rest[..rest.array_windows().position(|w| w == b"?>")?];
318
319    let needle = b"encoding=";
320    let enc_pos = declaration.array_windows().position(|w| w == needle)?;
321
322    let after_eq = &declaration[enc_pos + needle.len()..];
323    let quote = *after_eq.first()?;
324    if quote != b'"' && quote != b'\'' {
325        return None;
326    }
327
328    let value_bytes = &after_eq[1..];
329    let quote_end = value_bytes.iter().position(|&b| b == quote)?;
330    // The encoding name is always ASCII; reject if it contains non-ASCII bytes.
331    let encoding_name = std::str::from_utf8(&value_bytes[..quote_end]).ok()?;
332
333    label_encoding(encoding_name)
334}
335
336/// Resolve an encoding label, ignoring case and surrounding whitespace
337fn label_encoding(label: &str) -> Option<&'static Encoding> {
338    let normalized = label.trim().to_lowercase();
339    Encoding::for_label(normalized.as_bytes())
340}
341
342/// Convert data to UTF-8 from detected encoding
343///
344/// The feed parser applies a fallback chain on top of this conversion.
345///
346/// # Arguments
347///
348/// * `data` - Raw byte data in unknown encoding
349/// * `encoding_name` - Encoding name (e.g., "iso-8859-1", "utf-32le"); an unknown
350///   name falls back to UTF-8
351///
352/// # Returns
353///
354/// * `Ok(String)` - UTF-8 string
355/// * `Err(String)` - Error message if conversion failed
356///
357/// # Examples
358///
359/// ```
360/// use feedparser_rs::util::encoding::convert_to_utf8;
361///
362/// let latin1 = b"\xE9"; // é in ISO-8859-1
363/// let utf8 = convert_to_utf8(latin1, "iso-8859-1").unwrap();
364/// assert_eq!(utf8, "é");
365/// ```
366///
367/// # Errors
368///
369/// Returns an error if the encoding conversion encounters invalid byte sequences
370/// that cannot be properly decoded.
371pub fn convert_to_utf8(data: &[u8], encoding_name: &str) -> Result<String, String> {
372    let (text, had_errors) = Utf32Order::from_label(encoding_name).map_or_else(
373        || {
374            let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8);
375            let (cow, _encoding_used, had_errors) = encoding.decode(data);
376            (cow.into_owned(), had_errors)
377        },
378        |order| order.decode(data.trim_prefix(order.bom())),
379    );
380
381    if had_errors {
382        Err(format!(
383            "Encoding conversion from {encoding_name} had errors"
384        ))
385    } else {
386        Ok(text)
387    }
388}
389
390/// Detect encoding and convert to UTF-8 in one step
391///
392/// The feed parser applies a fallback chain on top of this and does not call it.
393///
394/// # Examples
395///
396/// ```
397/// use feedparser_rs::util::encoding::detect_and_convert;
398///
399/// let data = b"<?xml version=\"1.0\"?><root>Test</root>";
400/// let (utf8, detected_encoding) = detect_and_convert(data).unwrap();
401/// assert_eq!(detected_encoding, "UTF-8");
402/// assert!(utf8.contains("Test"));
403/// ```
404///
405/// # Errors
406///
407/// Returns an error if the encoding conversion encounters invalid byte sequences
408/// that cannot be properly decoded.
409pub fn detect_and_convert(data: &[u8]) -> Result<(String, &'static str), String> {
410    let encoding_name = detect_encoding(data);
411    let utf8_string = convert_to_utf8(data, encoding_name)?;
412    Ok((utf8_string, encoding_name))
413}
414
415/// Extract charset from HTTP Content-Type header
416///
417/// Reads the first `charset` parameter (name matched ignoring ASCII case) after the
418/// media type, strips one pair of matching quotes, and resolves the label.
419///
420/// # Arguments
421///
422/// * `content_type` - The Content-Type header value
423///
424/// # Returns
425///
426/// The canonical `encoding_rs` name, or `None` if the parameter is absent, empty
427/// or not a known label
428///
429/// # Examples
430///
431/// ```
432/// use feedparser_rs::util::encoding::extract_charset_from_content_type;
433///
434/// assert_eq!(
435///     extract_charset_from_content_type("text/xml; Charset='utf-8'"),
436///     Some("UTF-8")
437/// );
438/// assert_eq!(
439///     extract_charset_from_content_type("text/html"),
440///     None
441/// );
442/// ```
443#[must_use]
444pub fn extract_charset_from_content_type(content_type: &str) -> Option<&'static str> {
445    content_type_encoding(content_type).map(Encoding::name)
446}
447
448fn content_type_encoding(content_type: &str) -> Option<&'static Encoding> {
449    let value = content_type
450        .split(';')
451        .skip(1)
452        .filter_map(|param| param.split_once('='))
453        .find(|(name, _)| name.trim().eq_ignore_ascii_case("charset"))
454        .map(|(_, value)| value.trim())?;
455
456    let unquoted = ['"', '\'']
457        .into_iter()
458        .find_map(|quote| value.strip_prefix(quote)?.strip_suffix(quote))
459        .unwrap_or(value);
460
461    label_encoding(unquoted)
462}
463
464/// Detect encoding with optional HTTP Content-Type hint
465///
466/// Considers the Content-Type charset parameter in addition to BOM and XML
467/// declaration detection. The feed parser applies a fallback chain on top of
468/// this order.
469///
470/// # Priority Order
471///
472/// 1. BOM (Byte Order Mark) - highest priority, cannot be wrong
473/// 2. HTTP Content-Type charset (if provided)
474/// 3. XML declaration encoding attribute
475/// 4. Default to UTF-8
476///
477/// The declaration is honoured only at the start of the document (ASCII
478/// whitespace may precede it), and its closing `?>` must fall within the first
479/// 512 bytes. `encoding=` anywhere else is ignored.
480///
481/// # Arguments
482///
483/// * `data` - Raw byte data
484/// * `content_type` - Optional HTTP Content-Type header value
485///
486/// # Returns
487///
488/// Detected encoding name
489///
490/// # Examples
491///
492/// ```
493/// use feedparser_rs::util::encoding::detect_encoding_with_hint;
494///
495/// // BOM takes priority over Content-Type
496/// let data = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>";
497/// assert_eq!(
498///     detect_encoding_with_hint(data, Some("text/xml; charset=ISO-8859-1")),
499///     "UTF-8"
500/// );
501///
502/// // Content-Type is used when no BOM
503/// let data = b"<?xml version=\"1.0\"?>";
504/// assert_eq!(
505///     detect_encoding_with_hint(data, Some("text/xml; charset=ISO-8859-1")),
506///     "windows-1252"
507/// );
508///
509/// // Falls back to XML declaration when no Content-Type
510/// let data = b"<?xml version=\"1.0\" encoding=\"UTF-16\"?>";
511/// assert_eq!(detect_encoding_with_hint(data, None), "UTF-16LE");
512/// ```
513pub fn detect_encoding_with_hint(data: &[u8], content_type: Option<&str>) -> &'static str {
514    // Check BOM first - highest priority
515    if let Some(bom_encoding) = detect_bom(data) {
516        return bom_encoding;
517    }
518
519    // Check Content-Type charset if provided
520    if let Some(ct) = content_type
521        && let Some(charset) = extract_charset_from_content_type(ct)
522    {
523        return charset;
524    }
525
526    // Check XML declaration
527    if let Some(encoding) = xml_declaration_encoding(data) {
528        return encoding.name();
529    }
530
531    // Default to UTF-8
532    "UTF-8"
533}
534
535/// Detect encoding from BOM only
536///
537/// Returns the encoding if a BOM is present, None otherwise.
538fn detect_bom(data: &[u8]) -> Option<&'static str> {
539    if data.starts_with(&[0xEF, 0xBB, 0xBF]) {
540        return Some("UTF-8");
541    }
542    // UTF-32 BOMs must be checked BEFORE UTF-16 BOMs
543    // because UTF-32LE BOM (FF FE 00 00) starts with UTF-16LE BOM (FF FE)
544    if data.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
545        return Some("UTF-32BE");
546    }
547    if data.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
548        return Some("UTF-32LE");
549    }
550    if data.starts_with(&[0xFF, 0xFE]) {
551        return Some("UTF-16LE");
552    }
553    if data.starts_with(&[0xFE, 0xFF]) {
554        return Some("UTF-16BE");
555    }
556    None
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562
563    #[test]
564    fn test_detect_utf8_bom() {
565        let data = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>";
566        assert_eq!(detect_encoding(data), "UTF-8");
567    }
568
569    #[test]
570    fn test_detect_utf16le_bom() {
571        let data = b"\xFF\xFE<\x00?\x00x\x00m\x00l\x00";
572        assert_eq!(detect_encoding(data), "UTF-16LE");
573    }
574
575    #[test]
576    fn test_detect_utf16be_bom() {
577        let data = b"\xFE\xFF\x00<\x00?\x00x\x00m\x00l";
578        assert_eq!(detect_encoding(data), "UTF-16BE");
579    }
580
581    #[test]
582    fn test_detect_from_xml_declaration() {
583        let data = b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
584        assert_eq!(detect_encoding(data).to_lowercase(), "windows-1252");
585    }
586
587    #[test]
588    fn test_detect_from_xml_declaration_single_quotes() {
589        let data = b"<?xml version='1.0' encoding='UTF-8'?>";
590        assert_eq!(detect_encoding(data), "UTF-8");
591    }
592
593    #[test]
594    fn test_detect_default_utf8() {
595        let data = b"<?xml version=\"1.0\"?>";
596        assert_eq!(detect_encoding(data), "UTF-8");
597    }
598
599    #[test]
600    fn test_convert_iso8859_1() {
601        let data = b"\xE9";
602        let utf8 = convert_to_utf8(data, "iso-8859-1").unwrap();
603        assert_eq!(utf8, "é");
604    }
605
606    #[test]
607    fn test_convert_windows1252() {
608        let data = b"\x93Hello\x94";
609        let utf8 = convert_to_utf8(data, "windows-1252").unwrap();
610        assert!(utf8.contains("Hello"));
611    }
612
613    #[test]
614    fn test_detect_and_convert() {
615        let data = b"<?xml version=\"1.0\"?><root>Test</root>";
616        let (utf8, encoding) = detect_and_convert(data).unwrap();
617        assert_eq!(encoding, "UTF-8");
618        assert!(utf8.contains("Test"));
619    }
620
621    #[test]
622    fn test_xml_declaration_encoding_double_quotes() {
623        let data = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
624        assert!(xml_declaration_encoding(data).is_some());
625    }
626
627    #[test]
628    fn test_xml_declaration_encoding_single_quotes() {
629        let data = b"<?xml version='1.0' encoding='UTF-8'?>";
630        assert!(xml_declaration_encoding(data).is_some());
631    }
632
633    #[test]
634    fn test_xml_declaration_encoding_none() {
635        let data = b"<?xml version=\"1.0\"?>";
636        assert!(xml_declaration_encoding(data).is_none());
637    }
638
639    #[test]
640    fn test_label_encoding() {
641        let name = |label| label_encoding(label).map(Encoding::name);
642        assert_eq!(name("UTF-8"), Some("UTF-8"));
643        assert_eq!(name("utf-8"), Some("UTF-8"));
644        assert_eq!(name("  UTF-8  "), Some("UTF-8"));
645        assert_eq!(name("ISO-8859-1"), Some("windows-1252"));
646    }
647
648    #[test]
649    fn test_convert_utf8_to_utf8() {
650        let data = b"Hello";
651        let result = convert_to_utf8(data, "utf-8").unwrap();
652        assert_eq!(result, "Hello");
653    }
654
655    #[test]
656    fn test_detect_no_encoding_declaration() {
657        let data = b"<rss><channel></channel></rss>";
658        assert_eq!(detect_encoding(data), "UTF-8");
659    }
660
661    #[test]
662    fn test_empty_data() {
663        let data = b"";
664        assert_eq!(detect_encoding(data), "UTF-8");
665    }
666
667    // Tests for Content-Type charset extraction
668
669    #[test]
670    fn test_extract_charset_basic() {
671        assert_eq!(
672            extract_charset_from_content_type("text/xml; charset=utf-8"),
673            Some("UTF-8")
674        );
675    }
676
677    #[test]
678    fn test_extract_charset_no_space() {
679        assert_eq!(
680            extract_charset_from_content_type("text/xml;charset=utf-8"),
681            Some("UTF-8")
682        );
683    }
684
685    #[test]
686    fn test_extract_charset_quoted() {
687        assert_eq!(
688            extract_charset_from_content_type("text/xml; charset=\"UTF-8\""),
689            Some("UTF-8")
690        );
691    }
692
693    #[test]
694    fn test_extract_charset_single_quoted() {
695        assert_eq!(
696            extract_charset_from_content_type("text/xml; charset='UTF-8'"),
697            Some("UTF-8")
698        );
699    }
700
701    #[test]
702    fn test_extract_charset_uppercase() {
703        assert_eq!(
704            extract_charset_from_content_type("TEXT/XML; CHARSET=UTF-8"),
705            Some("UTF-8")
706        );
707    }
708
709    #[test]
710    fn test_extract_charset_iso8859() {
711        assert_eq!(
712            extract_charset_from_content_type("text/html; charset=iso-8859-1"),
713            Some("windows-1252")
714        );
715    }
716
717    #[test]
718    fn test_extract_charset_none() {
719        assert_eq!(extract_charset_from_content_type("text/xml"), None);
720    }
721
722    #[test]
723    fn test_extract_charset_empty() {
724        assert_eq!(extract_charset_from_content_type(""), None);
725    }
726
727    #[test]
728    fn test_extract_charset_with_boundary() {
729        // Content-Type with multiple parameters
730        assert_eq!(
731            extract_charset_from_content_type("multipart/form-data; boundary=----; charset=utf-8"),
732            Some("UTF-8")
733        );
734    }
735
736    // Tests for detect_encoding_with_hint
737
738    #[test]
739    fn test_hint_bom_priority() {
740        // BOM takes priority over Content-Type
741        let data = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>";
742        assert_eq!(
743            detect_encoding_with_hint(data, Some("text/xml; charset=ISO-8859-1")),
744            "UTF-8"
745        );
746    }
747
748    #[test]
749    fn test_hint_content_type_used() {
750        // Content-Type is used when no BOM
751        let data = b"<?xml version=\"1.0\"?>";
752        assert_eq!(
753            detect_encoding_with_hint(data, Some("text/xml; charset=ISO-8859-1")),
754            "windows-1252"
755        );
756    }
757
758    #[test]
759    fn test_hint_xml_declaration_fallback() {
760        // Falls back to XML declaration when no Content-Type charset
761        let data = b"<?xml version=\"1.0\" encoding=\"windows-1252\"?>";
762        assert_eq!(detect_encoding_with_hint(data, None), "windows-1252");
763    }
764
765    #[test]
766    fn test_hint_default_utf8() {
767        // Default to UTF-8 when no hints
768        let data = b"<rss><channel></channel></rss>";
769        assert_eq!(detect_encoding_with_hint(data, None), "UTF-8");
770    }
771
772    #[test]
773    fn test_hint_content_type_without_charset() {
774        // Content-Type without charset falls through to XML declaration
775        let data = b"<?xml version=\"1.0\" encoding=\"windows-1252\"?>";
776        assert_eq!(
777            detect_encoding_with_hint(data, Some("text/xml")),
778            "windows-1252"
779        );
780    }
781
782    // Tests for detect_bom
783
784    #[test]
785    fn test_detect_bom_utf8() {
786        assert_eq!(detect_bom(b"\xEF\xBB\xBF"), Some("UTF-8"));
787    }
788
789    #[test]
790    fn test_detect_bom_utf16le() {
791        assert_eq!(detect_bom(b"\xFF\xFE"), Some("UTF-16LE"));
792    }
793
794    #[test]
795    fn test_detect_bom_utf16be() {
796        assert_eq!(detect_bom(b"\xFE\xFF"), Some("UTF-16BE"));
797    }
798
799    #[test]
800    fn test_detect_bom_utf32le() {
801        assert_eq!(detect_bom(b"\xFF\xFE\x00\x00"), Some("UTF-32LE"));
802    }
803
804    #[test]
805    fn test_detect_bom_utf32be() {
806        assert_eq!(detect_bom(b"\x00\x00\xFE\xFF"), Some("UTF-32BE"));
807    }
808
809    #[test]
810    fn test_detect_bom_none() {
811        assert_eq!(detect_bom(b"<?xml"), None);
812        assert_eq!(detect_bom(b""), None);
813    }
814
815    // Tests for labels that the bytes disprove
816
817    fn xml_document(declared: &str, title: &str) -> String {
818        format!("<?xml version=\"1.0\" encoding=\"{declared}\"?><title>{title}</title>")
819    }
820
821    fn assert_overridden(data: &[u8], content_type: Option<&str>, declared: &str, text: &str) {
822        let decoded = decode_document(data, content_type);
823        assert_eq!(decoded.text, text);
824        assert_eq!(
825            decoded.encoding,
826            DocumentEncoding::Whatwg(UTF_8),
827            "{declared}"
828        );
829        assert!(
830            matches!(
831                decoded.outcome,
832                DecodeOutcome::Overridden { declared: found } if found.name() == declared
833            ),
834            "{declared}: {:?}",
835            decoded.outcome
836        );
837    }
838
839    #[test]
840    fn test_decode_single_byte_label_on_utf8_body_uses_utf8() {
841        let body = "<title>héllo</title>";
842        for (label, name) in [("iso-8859-1", "windows-1252"), ("koi8-r", "KOI8-R")] {
843            let content_type = format!("text/xml; charset={label}");
844            assert_overridden(body.as_bytes(), Some(&content_type), name, body);
845
846            let document = xml_document(label, "héllo");
847            assert_overridden(document.as_bytes(), None, name, &document);
848        }
849    }
850
851    #[test]
852    fn test_decode_single_byte_label_on_ascii_body_is_clean() {
853        let document = xml_document("iso-8859-1", "hello");
854        let decoded = decode_document(document.as_bytes(), None);
855        assert_eq!(decoded.encoding.name(), "windows-1252");
856        assert_eq!(decoded.outcome, DecodeOutcome::Clean);
857    }
858
859    #[test]
860    fn test_decode_utf16_label_on_single_byte_markup_uses_utf8() {
861        for (label, name) in [("utf-16", "UTF-16LE"), ("utf-16be", "UTF-16BE")] {
862            // Both parities: even lengths decode as garbage, odd lengths with errors.
863            for title in ["ab", "abc", "héllo"] {
864                let document = xml_document(label, title);
865                assert_overridden(document.as_bytes(), None, name, &document);
866
867                let content_type = format!("text/xml; charset={label}");
868                let body = format!("\n <title>{title}</title>");
869                assert_overridden(body.as_bytes(), Some(&content_type), name, &body);
870            }
871        }
872    }
873
874    #[test]
875    fn test_decode_utf16_label_on_invalid_utf8_markup_keeps_content() {
876        for data in [&b"<title>a\xFFb</title>"[..], b"<title>a\xFFbc</title>"] {
877            let decoded = decode_document(data, Some("text/xml; charset=utf-16"));
878            assert_eq!(decoded.text, String::from_utf8_lossy(data));
879            assert_eq!(decoded.encoding, DocumentEncoding::Whatwg(UTF_8));
880            assert_eq!(decoded.outcome, DecodeOutcome::Lossy);
881        }
882    }
883
884    /// `(declared label, canonical name, body bytes, decoded title)`.
885    const LEGACY_BODIES: [(&str, &str, &[u8], &str); 2] = [
886        (
887            "iso-8859-1",
888            "windows-1252",
889            b"Caf\xE9 fran\xE7ais",
890            "Café français",
891        ),
892        (
893            "windows-1251",
894            "windows-1251",
895            b"\xCF\xF0\xE8\xE2\xE5\xF2",
896            "Привет",
897        ),
898    ];
899
900    #[test]
901    fn test_decode_failed_http_label_falls_back_to_xml_declaration() {
902        for (label, name, title, expected) in LEGACY_BODIES {
903            let data = [
904                xml_document(label, "").as_bytes(),
905                b"<title>",
906                title,
907                b"</title>",
908            ]
909            .concat();
910            // A failing label and a disproved one take the same fallback.
911            for (charset, declared) in [("utf-8", UTF_8), ("utf-16", UTF_16LE)] {
912                let content_type = format!("text/xml; charset={charset}");
913                let decoded = decode_document(&data, Some(&content_type));
914
915                assert!(
916                    decoded.text.contains(expected),
917                    "{charset}: {}",
918                    decoded.text
919                );
920                assert_eq!(
921                    decoded.encoding.name(),
922                    name.to_ascii_lowercase(),
923                    "{charset}"
924                );
925                assert_eq!(decoded.outcome, DecodeOutcome::Overridden { declared });
926                let problem = decoded.problem().unwrap_or_default();
927                assert!(problem.ends_with(&name.to_ascii_lowercase()), "{problem}");
928            }
929        }
930    }
931
932    #[test]
933    fn test_decode_unusable_declaration_fallback_stays_lossy() {
934        // Each declaration fails strictly, is disproved, or would discard the document.
935        for label in ["shift_jis", "utf-16", "iso-2022-kr", "utf-8"] {
936            let mut data = xml_document(label, "a").into_bytes();
937            data.extend_from_slice(b"\xFF");
938            let decoded = decode_document(&data, Some("text/xml; charset=utf-8"));
939
940            assert_eq!(decoded.encoding, DocumentEncoding::Whatwg(UTF_8), "{label}");
941            assert_eq!(decoded.outcome, DecodeOutcome::Lossy, "{label}");
942        }
943    }
944
945    #[test]
946    fn test_decode_bom_outranks_declaration_fallback() {
947        let mut data = b"\xEF\xBB\xBF".to_vec();
948        data.extend_from_slice(xml_document("windows-1251", "a").as_bytes());
949        data.extend_from_slice(b"\xFF");
950        let decoded = decode_document(&data, None);
951
952        assert!(decoded.text.starts_with("<?xml"));
953        assert_eq!(decoded.encoding, DocumentEncoding::Whatwg(UTF_8));
954        assert_eq!(decoded.outcome, DecodeOutcome::Lossy);
955    }
956
957    #[test]
958    fn test_decode_bomless_utf16_keeps_label() {
959        for (label, to_bytes) in [
960            ("utf-16le", u16::to_le_bytes as fn(u16) -> [u8; 2]),
961            ("utf-16be", u16::to_be_bytes),
962        ] {
963            for text in [xml_document(label, "héllo"), "\n<title/>".to_string()] {
964                let data: Vec<u8> = text.encode_utf16().flat_map(to_bytes).collect();
965                let content_type = format!("text/xml; charset={label}");
966                let decoded = decode_document(&data, Some(&content_type));
967                assert_eq!(decoded.text, text, "{label}");
968                assert_eq!(decoded.outcome, DecodeOutcome::Clean, "{label}");
969            }
970        }
971    }
972
973    const UTF32_RSS: &str = r#"<rss version="2.0"><channel><title>T</title></channel></rss>"#;
974
975    fn utf32(text: &str, to_bytes: fn(u32) -> [u8; 4]) -> Vec<u8> {
976        text.chars().flat_map(|c| to_bytes(u32::from(c))).collect()
977    }
978
979    #[test]
980    fn test_decode_bomless_utf32_is_sniffed() {
981        for (order, to_bytes) in [
982            (Utf32Order::Le, u32::to_le_bytes as fn(u32) -> [u8; 4]),
983            (Utf32Order::Be, u32::to_be_bytes),
984        ] {
985            let data = utf32(UTF32_RSS, to_bytes);
986            let decoded = decode_document(&data, None);
987            assert_eq!(decoded.text, UTF32_RSS, "{order:?}");
988            assert_eq!(decoded.encoding, DocumentEncoding::Utf32(order));
989            assert_eq!(decoded.outcome, DecodeOutcome::Clean, "{order:?}");
990        }
991    }
992
993    #[test]
994    fn test_decode_bomless_utf32_outranks_utf16_label() {
995        let data = utf32(UTF32_RSS, u32::to_le_bytes);
996        let decoded = decode_document(&data, Some("text/xml; charset=utf-16le"));
997        assert_eq!(decoded.encoding, DocumentEncoding::Utf32(Utf32Order::Le));
998    }
999
1000    #[test]
1001    fn test_parse_bomless_utf32() {
1002        for (label, to_bytes) in [
1003            ("utf-32le", u32::to_le_bytes as fn(u32) -> [u8; 4]),
1004            ("utf-32be", u32::to_be_bytes),
1005        ] {
1006            let feed = crate::parse(&utf32(UTF32_RSS, to_bytes)).unwrap();
1007            assert_eq!(feed.encoding, label);
1008            assert_eq!(feed.version.to_string(), "rss20");
1009            assert_eq!(feed.feed.title.as_deref(), Some("T"));
1010            assert!(!feed.bozo, "{label}");
1011        }
1012    }
1013
1014    #[test]
1015    fn test_utf32_sniff_does_not_catch_utf16() {
1016        for (label, to_bytes) in [
1017            ("utf-16le", u16::to_le_bytes as fn(u16) -> [u8; 2]),
1018            ("utf-16be", u16::to_be_bytes),
1019        ] {
1020            let data: Vec<u8> = UTF32_RSS.encode_utf16().flat_map(to_bytes).collect();
1021            assert!(utf32_markup(&data).is_none(), "{label}");
1022            let decoded = decode_document(&data, Some(&format!("text/xml; charset={label}")));
1023            assert_eq!(decoded.text, UTF32_RSS, "{label}");
1024            assert_eq!(decoded.outcome, DecodeOutcome::Clean, "{label}");
1025        }
1026    }
1027
1028    #[test]
1029    fn test_declaration_must_open_the_document() {
1030        for data in [
1031            &b"<rss><title>encoding=\"gbk\"</title></rss>"[..],
1032            b"<?xml-stylesheet encoding=\"gbk\"?>",
1033            b"<?xml version=\"1.0\"?><a encoding=\"gbk\"/>",
1034            b"<?xml version=\"1.0\" encoding=\"gbk\"",
1035        ] {
1036            assert!(xml_declaration_encoding(data).is_none());
1037        }
1038        let padded = b" \r\n<?xml version=\"1.0\" encoding=\"gbk\"?>";
1039        assert_eq!(xml_declaration_encoding(padded), Some(encoding_rs::GBK));
1040    }
1041}