pub(super) fn decode(bytes: &[u8]) -> String {
decode_lines(bytes, decode_fallback)
}
fn decode_lines(bytes: &[u8], mut fallback: impl FnMut(&[u8]) -> String) -> String {
let mut out = String::with_capacity(bytes.len());
let mut first = true;
for line in bytes.split(|b| *b == b'\n') {
if !first {
out.push('\n');
}
first = false;
match std::str::from_utf8(line) {
Ok(text) => out.push_str(text),
Err(_) => out.push_str(&fallback(line)),
}
}
out
}
#[cfg(not(windows))]
fn decode_fallback(bytes: &[u8]) -> String {
lossy(bytes)
}
#[cfg(windows)]
fn decode_fallback(bytes: &[u8]) -> String {
let code_page = unsafe { windows_sys::Win32::Globalization::GetOEMCP() };
if code_page == 0 {
return lossy(bytes);
}
decode_code_page(bytes, code_page)
}
fn lossy(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
#[cfg(windows)]
fn decode_code_page(bytes: &[u8], code_page: u32) -> String {
let Ok(len) = i32::try_from(bytes.len()) else {
return lossy(bytes);
};
let width = unsafe {
windows_sys::Win32::Globalization::MultiByteToWideChar(
code_page,
0,
bytes.as_ptr(),
len,
std::ptr::null_mut(),
0,
)
};
let Ok(code_units) = usize::try_from(width) else {
return lossy(bytes);
};
if code_units == 0 {
return lossy(bytes);
}
let mut wide = vec![0u16; code_units];
let written = unsafe {
windows_sys::Win32::Globalization::MultiByteToWideChar(
code_page,
0,
bytes.as_ptr(),
len,
wide.as_mut_ptr(),
width,
)
};
match usize::try_from(written) {
Ok(written) => {
wide.truncate(written);
String::from_utf16_lossy(&wide)
}
Err(_) => lossy(bytes),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bytewise(bytes: &[u8]) -> String {
bytes.iter().map(|b| char::from(*b)).collect()
}
struct DecodeCase {
name: &'static str,
input: &'static [u8],
fallback: fn(&[u8]) -> String,
expected: &'static str,
}
#[test]
fn valid_utf8_lines_are_kept_beside_lines_that_are_not() {
let mixed = b"ok: h\xc3\xa9llo\nnot utf-8: \x80\x81\nok: done\n";
let cases: &[DecodeCase] = &[
DecodeCase {
name: "the lines around the one that is not UTF-8 are kept",
input: mixed,
fallback: bytewise,
expected: "ok: héllo\nnot utf-8: \u{80}\u{81}\nok: done\n",
},
DecodeCase {
name: "only the unreadable line takes the fallback's reading",
input: mixed,
fallback: |_| "<other>".to_string(),
expected: "ok: héllo\n<other>\nok: done\n",
},
];
for case in cases {
let decoded = decode_lines(case.input, case.fallback);
assert_eq!(decoded, case.expected, "[{}]", case.name);
}
}
#[test]
fn the_inputs_own_line_breaks_are_left_where_they_were() {
let cases: &[DecodeCase] = &[
DecodeCase {
name: "the break belongs to the reader, the \\r to the line",
input: b"\xff\r\nplain",
fallback: bytewise,
expected: "\u{ff}\r\nplain",
},
DecodeCase {
name: "an empty capture stays empty",
input: b"",
fallback: bytewise,
expected: "",
},
];
for case in cases {
let decoded = decode_lines(case.input, case.fallback);
assert_eq!(decoded, case.expected, "[{}]", case.name);
}
}
#[test]
fn only_the_line_that_is_not_utf8_is_handed_over() {
let mut lines = Vec::new();
let text = decode_lines(b"a\n\xff\nb\n", |line| {
lines.push(line.to_vec());
bytewise(line)
});
assert_eq!(text, "a\n\u{ff}\nb\n");
assert_eq!(lines, vec![b"\xff".to_vec()]);
}
}