use crate::report::Charset;
fn all_non_ascii_isolated(raw: &[u8]) -> bool {
raw.iter().enumerate().all(|(i, b)| {
b.is_ascii()
|| ((i == 0 || raw[i - 1].is_ascii()) && (i + 1 == raw.len() || raw[i + 1].is_ascii()))
})
}
pub(crate) fn resolve(raw: &[u8]) -> (String, Charset) {
if let Ok(s) = std::str::from_utf8(raw) {
return (s.to_owned(), Charset::Utf8);
}
if all_non_ascii_isolated(raw) {
return (windows_1252(raw), Charset::Latin1);
}
if let Some(text) =
encoding_rs::SHIFT_JIS.decode_without_bom_handling_and_without_replacement(raw)
{
return (text.into_owned(), Charset::ShiftJis);
}
(windows_1252(raw), Charset::Latin1)
}
fn windows_1252(raw: &[u8]) -> String {
encoding_rs::WINDOWS_1252
.decode_without_bom_handling(raw)
.0
.into_owned()
}
pub(crate) fn decode_legacy(raw: &[u8], label: Charset) -> Option<String> {
let strict = |encoding: &'static encoding_rs::Encoding| {
encoding
.decode_without_bom_handling_and_without_replacement(raw)
.map(std::borrow::Cow::into_owned)
};
match label {
Charset::Utf8 => std::str::from_utf8(raw).ok().map(str::to_owned),
Charset::ShiftJis => strict(encoding_rs::SHIFT_JIS),
Charset::Latin1 => Some(windows_1252(raw)),
Charset::Gb18030 => strict(encoding_rs::GB18030),
Charset::Eci | Charset::Unknown | Charset::Unrecognized => None,
}
}
pub(crate) fn iso_8859_1(raw: &[u8]) -> String {
raw.iter().map(|&b| char::from(b)).collect()
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
fn windows_1252(s: &str) -> Vec<u8> {
let (bytes, _, had_errors) = encoding_rs::WINDOWS_1252.encode(s);
assert!(!had_errors);
bytes.into_owned()
}
#[test]
fn latin1_accented_words_resolve_as_latin1_not_garbled_sjis() {
for truth in ["Québec", "señor", "crème brûlée", "café au lait", "Éé"] {
let raw = windows_1252(truth);
let (text, charset) = resolve(&raw);
assert_eq!(text, truth);
assert_eq!(charset, Charset::Latin1, "{truth}");
}
}
#[test]
fn real_shift_jis_runs_still_resolve_as_sjis() {
let (raw, _, had_errors) = encoding_rs::SHIFT_JIS.encode("日本語テスト");
assert!(!had_errors);
let (text, charset) = resolve(&raw);
assert_eq!(text, "日本語テスト");
assert_eq!(charset, Charset::ShiftJis);
let (raw, _, _) = encoding_rs::SHIFT_JIS.encode("QR: 漢字");
let (text, charset) = resolve(&raw);
assert_eq!(text, "QR: 漢字");
assert_eq!(charset, Charset::ShiftJis);
}
#[test]
fn utf8_always_wins() {
let (text, charset) = resolve("déjà 日本".as_bytes());
assert_eq!(text, "déjà 日本");
assert_eq!(charset, Charset::Utf8);
}
#[test]
fn byte_order_marks_are_bytes_not_encoding_switches() {
let (text, charset) = resolve(&[0xFF, 0xFE, 0x41, 0x00]);
assert_eq!(text, "ÿþA\u{0}");
assert_eq!(charset, Charset::Latin1);
assert_eq!(
decode_legacy(&[0xFF, 0xFE, 0x41, 0x00], charset).as_deref(),
Some("ÿþA\u{0}")
);
}
#[test]
fn legacy_labels_decode_what_they_promise() {
assert_eq!(
decode_legacy(&[0xA1], Charset::Latin1).as_deref(),
Some("¡")
);
assert_eq!(
decode_legacy(&[0x80], Charset::Latin1).as_deref(),
Some("€")
);
assert_eq!(decode_legacy(&[0xA1], Charset::Utf8), None);
assert_eq!(
decode_legacy(&[0x82, 0xB1], Charset::ShiftJis).as_deref(),
Some("こ")
);
assert_eq!(decode_legacy(&[0xFF], Charset::ShiftJis), None);
assert_eq!(
decode_legacy(&[0xD6, 0xD0, 0xCE, 0xC4], Charset::Gb18030).as_deref(),
Some("中文")
);
assert_eq!(decode_legacy(&[0xB0, 0xFF], Charset::Gb18030), None);
for label in [Charset::Eci, Charset::Unknown, Charset::Unrecognized] {
assert_eq!(
decode_legacy(b"ok", label),
None,
"{label:?} has no decoder"
);
}
assert_eq!(iso_8859_1(&[0x35, 0x80, 0xFF]), "5\u{80}ÿ");
}
#[test]
fn invalid_everywhere_falls_back_to_latin1_lossy() {
let (_, charset) = resolve(&[0xFF, 0xFF]);
assert_eq!(charset, Charset::Latin1);
}
#[test]
fn all_non_ascii_isolated_neighbour_logic_is_exact() {
assert!(all_non_ascii_isolated(&[0x41, 0xE9])); assert_eq!(resolve(&[0x41, 0xE9]), ("Aé".to_owned(), Charset::Latin1));
assert!(!all_non_ascii_isolated(&[0x41, 0xE9, 0xEA, 0x41])); assert!(all_non_ascii_isolated(&[0x41, 0xE9, 0x41])); }
}