use std::borrow::Cow;
use encoding_rs::{Encoding, REPLACEMENT, UTF_8, UTF_16BE, UTF_16LE};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DecodeOutcome {
Clean,
Overridden { declared: &'static Encoding },
Lossy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Utf32Order {
Le,
Be,
}
impl Utf32Order {
const fn bom(self) -> &'static [u8] {
match self {
Self::Le => b"\xFF\xFE\x00\x00",
Self::Be => b"\x00\x00\xFE\xFF",
}
}
const fn name(self) -> &'static str {
match self {
Self::Le => "utf-32le",
Self::Be => "utf-32be",
}
}
fn from_label(label: &str) -> Option<Self> {
[Self::Le, Self::Be]
.into_iter()
.find(|order| label.trim().eq_ignore_ascii_case(order.name()))
}
fn decode(self, data: &[u8]) -> (String, bool) {
let (units, tail) = data.as_chunks::<4>();
let mut had_errors = !tail.is_empty();
let mut text: String = units
.iter()
.map(|&unit| {
let scalar = match self {
Self::Le => u32::from_le_bytes(unit),
Self::Be => u32::from_be_bytes(unit),
};
char::from_u32(scalar).unwrap_or_else(|| {
had_errors = true;
char::REPLACEMENT_CHARACTER
})
})
.collect();
if !tail.is_empty() {
text.push(char::REPLACEMENT_CHARACTER);
}
(text, had_errors)
}
}
fn utf32_bom(data: &[u8]) -> Option<(Utf32Order, &[u8])> {
[Utf32Order::Le, Utf32Order::Be]
.into_iter()
.find_map(|order| Some((order, data.strip_prefix(order.bom())?)))
}
const fn utf32_markup(data: &[u8]) -> Option<(Utf32Order, &[u8])> {
match data {
[b'<', 0, 0, 0, ..] => Some((Utf32Order::Le, data)),
[0, 0, 0, b'<', ..] => Some((Utf32Order::Be, data)),
_ => None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DocumentEncoding {
Whatwg(&'static Encoding),
Utf32(Utf32Order),
}
impl DocumentEncoding {
pub(crate) fn name(self) -> String {
match self {
Self::Whatwg(encoding) => encoding.name().to_ascii_lowercase(),
Self::Utf32(order) => order.name().to_string(),
}
}
}
#[derive(Debug)]
pub(crate) struct DecodedDocument<'a> {
pub(crate) text: Cow<'a, str>,
pub(crate) encoding: DocumentEncoding,
pub(crate) outcome: DecodeOutcome,
}
impl DecodedDocument<'_> {
pub(crate) fn problem(&self) -> Option<String> {
let used = self.encoding.name();
match self.outcome {
DecodeOutcome::Clean => None,
DecodeOutcome::Overridden { declared } => Some(format!(
"document declared as {} was decoded as {used}",
declared.name().to_ascii_lowercase()
)),
DecodeOutcome::Lossy => Some(format!(
"document is not valid {used}; invalid bytes were replaced"
)),
}
}
}
pub(crate) fn decode_document<'a>(
data: &'a [u8],
content_type: Option<&str>,
) -> DecodedDocument<'a> {
if let Some((order, body)) = utf32_bom(data).or_else(|| utf32_markup(data)) {
let (text, had_errors) = order.decode(body);
return DecodedDocument {
text: Cow::Owned(text),
encoding: DocumentEncoding::Utf32(order),
outcome: if had_errors {
DecodeOutcome::Lossy
} else {
DecodeOutcome::Clean
},
};
}
let candidate = candidate_encoding(data, content_type);
let lossy = if is_disproved(candidate, data) {
None
} else {
let (text, had_errors) = candidate.decode_with_bom_removal(data);
if !had_errors {
return DecodedDocument {
text,
encoding: DocumentEncoding::Whatwg(candidate),
outcome: DecodeOutcome::Clean,
};
}
Some(text)
};
if let Some((encoding, text)) = decode_strict_fallback(data) {
return DecodedDocument {
text,
encoding: DocumentEncoding::Whatwg(encoding),
outcome: DecodeOutcome::Overridden {
declared: candidate,
},
};
}
let (text, encoding) = lossy.map_or_else(
|| (UTF_8.decode_without_bom_handling(data).0, UTF_8),
|text| (text, candidate),
);
DecodedDocument {
text,
encoding: DocumentEncoding::Whatwg(encoding),
outcome: DecodeOutcome::Lossy,
}
}
fn decode_strict_fallback(data: &[u8]) -> Option<(&'static Encoding, Cow<'_, str>)> {
let strict = |encoding: &'static Encoding| {
encoding
.decode_without_bom_handling_and_without_replacement(data)
.map(|text| (encoding, text))
};
strict(UTF_8).or_else(|| {
if Encoding::for_bom(data).is_some() {
return None;
}
xml_declaration_encoding(data)
.filter(|&encoding| encoding != REPLACEMENT && !is_disproved(encoding, data))
.and_then(strict)
})
}
fn candidate_encoding(data: &[u8], content_type: Option<&str>) -> &'static Encoding {
let usable = |encoding: &&'static Encoding| *encoding != REPLACEMENT;
Encoding::for_bom(data)
.map(|(encoding, _)| encoding)
.or_else(|| {
content_type
.filter(|_| !sniffs_as_json(data))
.and_then(content_type_encoding)
.filter(usable)
})
.or_else(|| xml_declaration_encoding(data).filter(usable))
.unwrap_or(UTF_8)
}
fn is_disproved(candidate: &'static Encoding, data: &[u8]) -> bool {
if candidate == UTF_16LE || candidate == UTF_16BE {
matches!(data.trim_ascii_start(), [b'<', second, ..] if *second != 0)
} else {
candidate.is_single_byte() && !data.is_ascii() && std::str::from_utf8(data).is_ok()
}
}
fn sniffs_as_json(data: &[u8]) -> bool {
data.trim_prefix(b"\xEF\xBB\xBF")
.trim_ascii_start()
.starts_with(b"{")
}
pub fn detect_encoding(data: &[u8]) -> &'static str {
if let Some(bom_encoding) = detect_bom(data) {
return bom_encoding;
}
if let Some(encoding) = xml_declaration_encoding(data) {
return encoding.name();
}
"UTF-8"
}
fn xml_declaration_encoding(data: &[u8]) -> Option<&'static Encoding> {
let head = &data[..data.len().min(512)];
let rest = head.trim_ascii_start().strip_prefix(b"<?xml")?;
if !rest.first()?.is_ascii_whitespace() {
return None;
}
let declaration = &rest[..rest.array_windows().position(|w| w == b"?>")?];
let needle = b"encoding=";
let enc_pos = declaration.array_windows().position(|w| w == needle)?;
let after_eq = &declaration[enc_pos + needle.len()..];
let quote = *after_eq.first()?;
if quote != b'"' && quote != b'\'' {
return None;
}
let value_bytes = &after_eq[1..];
let quote_end = value_bytes.iter().position(|&b| b == quote)?;
let encoding_name = std::str::from_utf8(&value_bytes[..quote_end]).ok()?;
label_encoding(encoding_name)
}
fn label_encoding(label: &str) -> Option<&'static Encoding> {
let normalized = label.trim().to_lowercase();
Encoding::for_label(normalized.as_bytes())
}
pub fn convert_to_utf8(data: &[u8], encoding_name: &str) -> Result<String, String> {
let (text, had_errors) = Utf32Order::from_label(encoding_name).map_or_else(
|| {
let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8);
let (cow, _encoding_used, had_errors) = encoding.decode(data);
(cow.into_owned(), had_errors)
},
|order| order.decode(data.trim_prefix(order.bom())),
);
if had_errors {
Err(format!(
"Encoding conversion from {encoding_name} had errors"
))
} else {
Ok(text)
}
}
pub fn detect_and_convert(data: &[u8]) -> Result<(String, &'static str), String> {
let encoding_name = detect_encoding(data);
let utf8_string = convert_to_utf8(data, encoding_name)?;
Ok((utf8_string, encoding_name))
}
#[must_use]
pub fn extract_charset_from_content_type(content_type: &str) -> Option<&'static str> {
content_type_encoding(content_type).map(Encoding::name)
}
fn content_type_encoding(content_type: &str) -> Option<&'static Encoding> {
let value = content_type
.split(';')
.skip(1)
.filter_map(|param| param.split_once('='))
.find(|(name, _)| name.trim().eq_ignore_ascii_case("charset"))
.map(|(_, value)| value.trim())?;
let unquoted = ['"', '\'']
.into_iter()
.find_map(|quote| value.strip_prefix(quote)?.strip_suffix(quote))
.unwrap_or(value);
label_encoding(unquoted)
}
pub fn detect_encoding_with_hint(data: &[u8], content_type: Option<&str>) -> &'static str {
if let Some(bom_encoding) = detect_bom(data) {
return bom_encoding;
}
if let Some(ct) = content_type
&& let Some(charset) = extract_charset_from_content_type(ct)
{
return charset;
}
if let Some(encoding) = xml_declaration_encoding(data) {
return encoding.name();
}
"UTF-8"
}
fn detect_bom(data: &[u8]) -> Option<&'static str> {
if data.starts_with(&[0xEF, 0xBB, 0xBF]) {
return Some("UTF-8");
}
if data.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
return Some("UTF-32BE");
}
if data.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
return Some("UTF-32LE");
}
if data.starts_with(&[0xFF, 0xFE]) {
return Some("UTF-16LE");
}
if data.starts_with(&[0xFE, 0xFF]) {
return Some("UTF-16BE");
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detect_utf8_bom() {
let data = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>";
assert_eq!(detect_encoding(data), "UTF-8");
}
#[test]
fn test_detect_utf16le_bom() {
let data = b"\xFF\xFE<\x00?\x00x\x00m\x00l\x00";
assert_eq!(detect_encoding(data), "UTF-16LE");
}
#[test]
fn test_detect_utf16be_bom() {
let data = b"\xFE\xFF\x00<\x00?\x00x\x00m\x00l";
assert_eq!(detect_encoding(data), "UTF-16BE");
}
#[test]
fn test_detect_from_xml_declaration() {
let data = b"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
assert_eq!(detect_encoding(data).to_lowercase(), "windows-1252");
}
#[test]
fn test_detect_from_xml_declaration_single_quotes() {
let data = b"<?xml version='1.0' encoding='UTF-8'?>";
assert_eq!(detect_encoding(data), "UTF-8");
}
#[test]
fn test_detect_default_utf8() {
let data = b"<?xml version=\"1.0\"?>";
assert_eq!(detect_encoding(data), "UTF-8");
}
#[test]
fn test_convert_iso8859_1() {
let data = b"\xE9";
let utf8 = convert_to_utf8(data, "iso-8859-1").unwrap();
assert_eq!(utf8, "é");
}
#[test]
fn test_convert_windows1252() {
let data = b"\x93Hello\x94";
let utf8 = convert_to_utf8(data, "windows-1252").unwrap();
assert!(utf8.contains("Hello"));
}
#[test]
fn test_detect_and_convert() {
let data = b"<?xml version=\"1.0\"?><root>Test</root>";
let (utf8, encoding) = detect_and_convert(data).unwrap();
assert_eq!(encoding, "UTF-8");
assert!(utf8.contains("Test"));
}
#[test]
fn test_xml_declaration_encoding_double_quotes() {
let data = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
assert!(xml_declaration_encoding(data).is_some());
}
#[test]
fn test_xml_declaration_encoding_single_quotes() {
let data = b"<?xml version='1.0' encoding='UTF-8'?>";
assert!(xml_declaration_encoding(data).is_some());
}
#[test]
fn test_xml_declaration_encoding_none() {
let data = b"<?xml version=\"1.0\"?>";
assert!(xml_declaration_encoding(data).is_none());
}
#[test]
fn test_label_encoding() {
let name = |label| label_encoding(label).map(Encoding::name);
assert_eq!(name("UTF-8"), Some("UTF-8"));
assert_eq!(name("utf-8"), Some("UTF-8"));
assert_eq!(name(" UTF-8 "), Some("UTF-8"));
assert_eq!(name("ISO-8859-1"), Some("windows-1252"));
}
#[test]
fn test_convert_utf8_to_utf8() {
let data = b"Hello";
let result = convert_to_utf8(data, "utf-8").unwrap();
assert_eq!(result, "Hello");
}
#[test]
fn test_detect_no_encoding_declaration() {
let data = b"<rss><channel></channel></rss>";
assert_eq!(detect_encoding(data), "UTF-8");
}
#[test]
fn test_empty_data() {
let data = b"";
assert_eq!(detect_encoding(data), "UTF-8");
}
#[test]
fn test_extract_charset_basic() {
assert_eq!(
extract_charset_from_content_type("text/xml; charset=utf-8"),
Some("UTF-8")
);
}
#[test]
fn test_extract_charset_no_space() {
assert_eq!(
extract_charset_from_content_type("text/xml;charset=utf-8"),
Some("UTF-8")
);
}
#[test]
fn test_extract_charset_quoted() {
assert_eq!(
extract_charset_from_content_type("text/xml; charset=\"UTF-8\""),
Some("UTF-8")
);
}
#[test]
fn test_extract_charset_single_quoted() {
assert_eq!(
extract_charset_from_content_type("text/xml; charset='UTF-8'"),
Some("UTF-8")
);
}
#[test]
fn test_extract_charset_uppercase() {
assert_eq!(
extract_charset_from_content_type("TEXT/XML; CHARSET=UTF-8"),
Some("UTF-8")
);
}
#[test]
fn test_extract_charset_iso8859() {
assert_eq!(
extract_charset_from_content_type("text/html; charset=iso-8859-1"),
Some("windows-1252")
);
}
#[test]
fn test_extract_charset_none() {
assert_eq!(extract_charset_from_content_type("text/xml"), None);
}
#[test]
fn test_extract_charset_empty() {
assert_eq!(extract_charset_from_content_type(""), None);
}
#[test]
fn test_extract_charset_with_boundary() {
assert_eq!(
extract_charset_from_content_type("multipart/form-data; boundary=----; charset=utf-8"),
Some("UTF-8")
);
}
#[test]
fn test_hint_bom_priority() {
let data = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>";
assert_eq!(
detect_encoding_with_hint(data, Some("text/xml; charset=ISO-8859-1")),
"UTF-8"
);
}
#[test]
fn test_hint_content_type_used() {
let data = b"<?xml version=\"1.0\"?>";
assert_eq!(
detect_encoding_with_hint(data, Some("text/xml; charset=ISO-8859-1")),
"windows-1252"
);
}
#[test]
fn test_hint_xml_declaration_fallback() {
let data = b"<?xml version=\"1.0\" encoding=\"windows-1252\"?>";
assert_eq!(detect_encoding_with_hint(data, None), "windows-1252");
}
#[test]
fn test_hint_default_utf8() {
let data = b"<rss><channel></channel></rss>";
assert_eq!(detect_encoding_with_hint(data, None), "UTF-8");
}
#[test]
fn test_hint_content_type_without_charset() {
let data = b"<?xml version=\"1.0\" encoding=\"windows-1252\"?>";
assert_eq!(
detect_encoding_with_hint(data, Some("text/xml")),
"windows-1252"
);
}
#[test]
fn test_detect_bom_utf8() {
assert_eq!(detect_bom(b"\xEF\xBB\xBF"), Some("UTF-8"));
}
#[test]
fn test_detect_bom_utf16le() {
assert_eq!(detect_bom(b"\xFF\xFE"), Some("UTF-16LE"));
}
#[test]
fn test_detect_bom_utf16be() {
assert_eq!(detect_bom(b"\xFE\xFF"), Some("UTF-16BE"));
}
#[test]
fn test_detect_bom_utf32le() {
assert_eq!(detect_bom(b"\xFF\xFE\x00\x00"), Some("UTF-32LE"));
}
#[test]
fn test_detect_bom_utf32be() {
assert_eq!(detect_bom(b"\x00\x00\xFE\xFF"), Some("UTF-32BE"));
}
#[test]
fn test_detect_bom_none() {
assert_eq!(detect_bom(b"<?xml"), None);
assert_eq!(detect_bom(b""), None);
}
fn xml_document(declared: &str, title: &str) -> String {
format!("<?xml version=\"1.0\" encoding=\"{declared}\"?><title>{title}</title>")
}
fn assert_overridden(data: &[u8], content_type: Option<&str>, declared: &str, text: &str) {
let decoded = decode_document(data, content_type);
assert_eq!(decoded.text, text);
assert_eq!(
decoded.encoding,
DocumentEncoding::Whatwg(UTF_8),
"{declared}"
);
assert!(
matches!(
decoded.outcome,
DecodeOutcome::Overridden { declared: found } if found.name() == declared
),
"{declared}: {:?}",
decoded.outcome
);
}
#[test]
fn test_decode_single_byte_label_on_utf8_body_uses_utf8() {
let body = "<title>héllo</title>";
for (label, name) in [("iso-8859-1", "windows-1252"), ("koi8-r", "KOI8-R")] {
let content_type = format!("text/xml; charset={label}");
assert_overridden(body.as_bytes(), Some(&content_type), name, body);
let document = xml_document(label, "héllo");
assert_overridden(document.as_bytes(), None, name, &document);
}
}
#[test]
fn test_decode_single_byte_label_on_ascii_body_is_clean() {
let document = xml_document("iso-8859-1", "hello");
let decoded = decode_document(document.as_bytes(), None);
assert_eq!(decoded.encoding.name(), "windows-1252");
assert_eq!(decoded.outcome, DecodeOutcome::Clean);
}
#[test]
fn test_decode_utf16_label_on_single_byte_markup_uses_utf8() {
for (label, name) in [("utf-16", "UTF-16LE"), ("utf-16be", "UTF-16BE")] {
for title in ["ab", "abc", "héllo"] {
let document = xml_document(label, title);
assert_overridden(document.as_bytes(), None, name, &document);
let content_type = format!("text/xml; charset={label}");
let body = format!("\n <title>{title}</title>");
assert_overridden(body.as_bytes(), Some(&content_type), name, &body);
}
}
}
#[test]
fn test_decode_utf16_label_on_invalid_utf8_markup_keeps_content() {
for data in [&b"<title>a\xFFb</title>"[..], b"<title>a\xFFbc</title>"] {
let decoded = decode_document(data, Some("text/xml; charset=utf-16"));
assert_eq!(decoded.text, String::from_utf8_lossy(data));
assert_eq!(decoded.encoding, DocumentEncoding::Whatwg(UTF_8));
assert_eq!(decoded.outcome, DecodeOutcome::Lossy);
}
}
const LEGACY_BODIES: [(&str, &str, &[u8], &str); 2] = [
(
"iso-8859-1",
"windows-1252",
b"Caf\xE9 fran\xE7ais",
"Café français",
),
(
"windows-1251",
"windows-1251",
b"\xCF\xF0\xE8\xE2\xE5\xF2",
"Привет",
),
];
#[test]
fn test_decode_failed_http_label_falls_back_to_xml_declaration() {
for (label, name, title, expected) in LEGACY_BODIES {
let data = [
xml_document(label, "").as_bytes(),
b"<title>",
title,
b"</title>",
]
.concat();
for (charset, declared) in [("utf-8", UTF_8), ("utf-16", UTF_16LE)] {
let content_type = format!("text/xml; charset={charset}");
let decoded = decode_document(&data, Some(&content_type));
assert!(
decoded.text.contains(expected),
"{charset}: {}",
decoded.text
);
assert_eq!(
decoded.encoding.name(),
name.to_ascii_lowercase(),
"{charset}"
);
assert_eq!(decoded.outcome, DecodeOutcome::Overridden { declared });
let problem = decoded.problem().unwrap_or_default();
assert!(problem.ends_with(&name.to_ascii_lowercase()), "{problem}");
}
}
}
#[test]
fn test_decode_unusable_declaration_fallback_stays_lossy() {
for label in ["shift_jis", "utf-16", "iso-2022-kr", "utf-8"] {
let mut data = xml_document(label, "a").into_bytes();
data.extend_from_slice(b"\xFF");
let decoded = decode_document(&data, Some("text/xml; charset=utf-8"));
assert_eq!(decoded.encoding, DocumentEncoding::Whatwg(UTF_8), "{label}");
assert_eq!(decoded.outcome, DecodeOutcome::Lossy, "{label}");
}
}
#[test]
fn test_decode_bom_outranks_declaration_fallback() {
let mut data = b"\xEF\xBB\xBF".to_vec();
data.extend_from_slice(xml_document("windows-1251", "a").as_bytes());
data.extend_from_slice(b"\xFF");
let decoded = decode_document(&data, None);
assert!(decoded.text.starts_with("<?xml"));
assert_eq!(decoded.encoding, DocumentEncoding::Whatwg(UTF_8));
assert_eq!(decoded.outcome, DecodeOutcome::Lossy);
}
#[test]
fn test_decode_bomless_utf16_keeps_label() {
for (label, to_bytes) in [
("utf-16le", u16::to_le_bytes as fn(u16) -> [u8; 2]),
("utf-16be", u16::to_be_bytes),
] {
for text in [xml_document(label, "héllo"), "\n<title/>".to_string()] {
let data: Vec<u8> = text.encode_utf16().flat_map(to_bytes).collect();
let content_type = format!("text/xml; charset={label}");
let decoded = decode_document(&data, Some(&content_type));
assert_eq!(decoded.text, text, "{label}");
assert_eq!(decoded.outcome, DecodeOutcome::Clean, "{label}");
}
}
}
const UTF32_RSS: &str = r#"<rss version="2.0"><channel><title>T</title></channel></rss>"#;
fn utf32(text: &str, to_bytes: fn(u32) -> [u8; 4]) -> Vec<u8> {
text.chars().flat_map(|c| to_bytes(u32::from(c))).collect()
}
#[test]
fn test_decode_bomless_utf32_is_sniffed() {
for (order, to_bytes) in [
(Utf32Order::Le, u32::to_le_bytes as fn(u32) -> [u8; 4]),
(Utf32Order::Be, u32::to_be_bytes),
] {
let data = utf32(UTF32_RSS, to_bytes);
let decoded = decode_document(&data, None);
assert_eq!(decoded.text, UTF32_RSS, "{order:?}");
assert_eq!(decoded.encoding, DocumentEncoding::Utf32(order));
assert_eq!(decoded.outcome, DecodeOutcome::Clean, "{order:?}");
}
}
#[test]
fn test_decode_bomless_utf32_outranks_utf16_label() {
let data = utf32(UTF32_RSS, u32::to_le_bytes);
let decoded = decode_document(&data, Some("text/xml; charset=utf-16le"));
assert_eq!(decoded.encoding, DocumentEncoding::Utf32(Utf32Order::Le));
}
#[test]
fn test_parse_bomless_utf32() {
for (label, to_bytes) in [
("utf-32le", u32::to_le_bytes as fn(u32) -> [u8; 4]),
("utf-32be", u32::to_be_bytes),
] {
let feed = crate::parse(&utf32(UTF32_RSS, to_bytes)).unwrap();
assert_eq!(feed.encoding, label);
assert_eq!(feed.version.to_string(), "rss20");
assert_eq!(feed.feed.title.as_deref(), Some("T"));
assert!(!feed.bozo, "{label}");
}
}
#[test]
fn test_utf32_sniff_does_not_catch_utf16() {
for (label, to_bytes) in [
("utf-16le", u16::to_le_bytes as fn(u16) -> [u8; 2]),
("utf-16be", u16::to_be_bytes),
] {
let data: Vec<u8> = UTF32_RSS.encode_utf16().flat_map(to_bytes).collect();
assert!(utf32_markup(&data).is_none(), "{label}");
let decoded = decode_document(&data, Some(&format!("text/xml; charset={label}")));
assert_eq!(decoded.text, UTF32_RSS, "{label}");
assert_eq!(decoded.outcome, DecodeOutcome::Clean, "{label}");
}
}
#[test]
fn test_declaration_must_open_the_document() {
for data in [
&b"<rss><title>encoding=\"gbk\"</title></rss>"[..],
b"<?xml-stylesheet encoding=\"gbk\"?>",
b"<?xml version=\"1.0\"?><a encoding=\"gbk\"/>",
b"<?xml version=\"1.0\" encoding=\"gbk\"",
] {
assert!(xml_declaration_encoding(data).is_none());
}
let padded = b" \r\n<?xml version=\"1.0\" encoding=\"gbk\"?>";
assert_eq!(xml_declaration_encoding(padded), Some(encoding_rs::GBK));
}
}