use std::borrow::Cow;
pub fn output(bytes: &[u8]) -> Cow<'_, str> {
let text = decode(bytes);
if text.contains("\r\n") {
Cow::Owned(text.replace("\r\n", "\n"))
} else {
text
}
}
const UTF8_BOM: &[u8] = b"\xef\xbb\xbf";
fn decode(bytes: &[u8]) -> Cow<'_, str> {
#[cfg(windows)]
if let Some(text) = utf16_output(bytes) {
return Cow::Owned(text);
}
String::from_utf8_lossy(bytes.strip_prefix(UTF8_BOM).unwrap_or(bytes))
}
#[cfg(windows)]
const UTF16_ASCII_MAJORITY_DIVISOR: usize = 2;
#[cfg(windows)]
const UTF16_UNIT_BYTES: usize = 2;
#[cfg(windows)]
const UTF16_LE_BOM: &[u8] = b"\xff\xfe";
#[cfg(windows)]
const UTF16_BE_BOM: &[u8] = b"\xfe\xff";
#[cfg(windows)]
fn utf16_output(bytes: &[u8]) -> Option<String> {
let (bytes, little_endian) = if let Some(bytes) = bytes.strip_prefix(UTF16_LE_BOM) {
(bytes, true)
} else if let Some(bytes) = bytes.strip_prefix(UTF16_BE_BOM) {
(bytes, false)
} else {
let (units, _) = bytes.as_chunks::<UTF16_UNIT_BYTES>();
let ascii = units
.iter()
.filter(|[low, high]| *low != 0 && low.is_ascii() && *high == 0)
.count();
if ascii <= units.len() / UTF16_ASCII_MAJORITY_DIVISOR || units.contains(&[0, 0]) {
return None;
}
(bytes, true)
};
let (units, rest) = bytes.as_chunks::<UTF16_UNIT_BYTES>();
let byte_order = if little_endian {
u16::from_le_bytes
} else {
u16::from_be_bytes
};
Some(
char::decode_utf16(units.iter().copied().map(byte_order))
.map(|character| character.unwrap_or(char::REPLACEMENT_CHARACTER))
.chain((!rest.is_empty()).then_some(char::REPLACEMENT_CHARACTER))
.collect(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn command_output_normalizes_crlf() {
assert_eq!(output(b"first\r\nsecond\n"), "first\nsecond\n");
}
#[cfg(windows)]
#[test]
fn native_utf16_text_keeps_unicode_and_line_boundaries() {
let utf16le = "help: 한글\r\n".encode_utf16().flat_map(u16::to_le_bytes);
let bom: Vec<_> = [0xff, 0xfe].into_iter().chain(utf16le.clone()).collect();
assert_eq!(output(&bom), "help: 한글\n");
assert_eq!(output(&utf16le.collect::<Vec<_>>()), "help: 한글\n");
}
}