use encoding_rs::{Encoding, UTF_8, WINDOWS_1252};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Fix {
Keep,
Text { text: String, changed: bool },
Left,
}
#[derive(Clone, Copy)]
enum Declared {
Latin1,
Utf8,
Other(&'static Encoding),
}
fn resolve(label: &[u8]) -> Option<Declared> {
let text = std::str::from_utf8(label).ok()?.trim().to_ascii_lowercase();
match text.as_str() {
"iso-8859-1" | "iso8859-1" | "iso_8859-1" | "latin1" | "latin-1" | "l1" | "iso88591" => {
return Some(Declared::Latin1)
}
"utf-8" | "utf8" => return Some(Declared::Utf8),
_ => {}
}
let enc = Encoding::for_label(text.as_bytes())?;
if enc == UTF_8 {
return Some(Declared::Utf8);
}
enc.is_ascii_compatible().then_some(Declared::Other(enc))
}
pub fn decode_declared(label: &[u8], bytes: &[u8]) -> Option<String> {
match resolve(label)? {
Declared::Latin1 => Some(latin1_text(bytes)),
Declared::Utf8 => std::str::from_utf8(bytes).ok().map(str::to_string),
Declared::Other(enc) => enc
.decode_without_bom_handling_and_without_replacement(bytes)
.map(|c| c.into_owned()),
}
}
pub fn declares_utf8(label: &[u8]) -> bool {
matches!(resolve(label), Some(Declared::Utf8))
}
pub fn repair_mojibake(text: &str) -> Option<String> {
if text.is_ascii() {
return None;
}
let candidates = [latin1_bytes(text), windows_1252_bytes(text)];
for bytes in candidates.into_iter().flatten() {
let Ok(fixed) = String::from_utf8(bytes) else {
continue;
};
if fixed == text
|| fixed
.chars()
.any(|c| c == '\u{FFFD}' || (c.is_control() && !matches!(c, '\n' | '\t' | '\r')))
{
continue;
}
let back = latin1_text(fixed.as_bytes()) == text
|| WINDOWS_1252.decode_without_bom_handling(fixed.as_bytes()).0 == text;
if back {
return Some(fixed);
}
}
None
}
fn latin1_bytes(text: &str) -> Option<Vec<u8>> {
text.chars()
.map(|c| u8::try_from(u32::from(c)).ok())
.collect()
}
fn latin1_text(bytes: &[u8]) -> String {
bytes.iter().map(|b| char::from(*b)).collect()
}
fn windows_1252_bytes(text: &str) -> Option<Vec<u8>> {
let (bytes, _, had_errors) = WINDOWS_1252.encode(text);
(!had_errors).then(|| bytes.into_owned())
}
fn looks_mangled(text: &str) -> bool {
text.contains(['\u{00C2}', '\u{00C3}', '\u{00E2}'])
}
pub fn fix(bytes: &[u8], declared: Option<&[u8]>) -> Fix {
let repaired = |text: &str| {
repair_mojibake(text).map(|text| Fix::Text {
text,
changed: true,
})
};
let Some(label) = declared else {
return match std::str::from_utf8(bytes) {
Ok(text) => repaired(text).unwrap_or(if looks_mangled(text) {
Fix::Left
} else {
Fix::Keep
}),
Err(_) => Fix::Left,
};
};
if declares_utf8(label) {
let Ok(text) = std::str::from_utf8(bytes) else {
return Fix::Left;
};
return repaired(text).unwrap_or(Fix::Text {
text: text.to_string(),
changed: false,
});
}
match decode_declared(label, bytes) {
Some(text) => Fix::Text {
text,
changed: true,
},
None => Fix::Left,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn text(f: Fix) -> String {
match f {
Fix::Text { text, .. } => text,
other => panic!("not a text: {other:?}"),
}
}
#[test]
fn a_declared_latin1_message_is_decoded() {
assert_eq!(
text(fix(b"caf\xe9 au lait\n", Some(b"ISO-8859-1"))),
"caf\u{e9} au lait\n"
);
assert_eq!(text(fix(b"\x80", Some(b"latin1"))), "\u{80}");
assert_eq!(text(fix(b"\x80", Some(b"windows-1252"))), "\u{20ac}");
}
#[test]
fn other_declared_encodings_go_through_encoding_rs() {
assert_eq!(
text(fix(b"\x93\xfa\x96\x7b", Some(b"Shift_JIS"))),
"\u{65e5}\u{672c}"
);
assert_eq!(fix(b"\x93", Some(b"Shift_JIS")), Fix::Left);
assert_eq!(fix(b"x", Some(b"no-such-encoding")), Fix::Left);
}
#[test]
fn mojibake_is_repaired_when_the_round_trip_is_exact() {
assert_eq!(
text(fix("R\u{c3}\u{a9}\u{c3}\u{a9}criture\n".as_bytes(), None)),
"R\u{e9}\u{e9}criture\n"
);
assert_eq!(
text(fix("it\u{e2}\u{20ac}\u{2122}s".as_bytes(), None)),
"it\u{2019}s"
);
assert_eq!(
text(fix("it\u{e2}\u{80}\u{99}s".as_bytes(), None)),
"it\u{2019}s"
);
}
#[test]
fn a_text_that_is_not_provably_mojibake_is_left() {
assert_eq!(fix("\u{c3}\u{a9} et \u{e9}".as_bytes(), None), Fix::Left);
assert_eq!(
fix("\u{c3}\u{a9} \u{65e5}\u{672c}".as_bytes(), None),
Fix::Left
);
assert_eq!(fix("caf\u{e9}".as_bytes(), None), Fix::Keep);
assert_eq!(fix(b"plain ascii", None), Fix::Keep);
assert_eq!(fix(b"caf\xe9", None), Fix::Left);
}
#[test]
fn a_declared_utf8_header_only_goes() {
assert_eq!(
fix("caf\u{e9}".as_bytes(), Some(b"UTF-8")),
Fix::Text {
text: "caf\u{e9}".into(),
changed: false
}
);
}
}