use std::borrow::Cow;
use windows_sys::Win32::{
Globalization::{CP_OEMCP, CP_UTF8, MultiByteToWideChar},
System::Console::GetConsoleOutputCP,
};
#[derive(Clone, Copy)]
pub(super) enum Endian {
Little,
Big,
}
impl Endian {
fn bom(self) -> [u8; 2] {
match self {
Self::Little => [0xff, 0xfe],
Self::Big => [0xfe, 0xff],
}
}
pub(super) fn decode(self, bytes: &[u8]) -> String {
let bytes = bytes.strip_prefix(&self.bom()).unwrap_or(bytes);
let (units, tail) = bytes.as_chunks();
let unit = match self {
Self::Little => u16::from_le_bytes,
Self::Big => u16::from_be_bytes,
};
char::decode_utf16(units.iter().copied().map(unit))
.map(|item| item.unwrap_or(char::REPLACEMENT_CHARACTER))
.chain((!tail.is_empty()).then_some(char::REPLACEMENT_CHARACTER))
.collect()
}
pub(super) fn ends_line(self, bytes: &[u8]) -> bool {
bytes.len().is_multiple_of(2)
&& bytes.ends_with(match self {
Self::Little => b"\n\0",
Self::Big => b"\0\n",
})
}
}
pub(super) const ENCODING_PREFIX: usize = 64;
pub(super) fn wide_encoding(bytes: &[u8]) -> Option<Endian> {
if bytes.starts_with(&Endian::Little.bom()) {
return Some(Endian::Little);
}
if bytes.starts_with(&Endian::Big.bom()) {
return Some(Endian::Big);
}
let prefix = &bytes[..bytes.len().min(ENCODING_PREFIX)];
let ascii = |byte: u8| byte.is_ascii_graphic() || byte.is_ascii_whitespace();
let (little, big) =
prefix
.as_chunks::<2>()
.0
.iter()
.fold((0, 0), |(little, big), &[first, second]| {
(
little + usize::from(ascii(first) && second == 0),
big + usize::from(first == 0 && ascii(second)),
)
});
match little.cmp(&big) {
std::cmp::Ordering::Greater => Some(Endian::Little),
std::cmp::Ordering::Less => Some(Endian::Big),
std::cmp::Ordering::Equal => None,
}
}
pub(super) fn byte_text(bytes: &[u8]) -> Cow<'_, str> {
if let Some(utf8) = bytes.strip_prefix(b"\xef\xbb\xbf") {
return String::from_utf8_lossy(utf8);
}
if let Ok(text) = str::from_utf8(bytes) {
return Cow::Borrowed(text);
}
let console = unsafe { GetConsoleOutputCP() };
let page = if matches!(console, 0 | CP_UTF8) {
CP_OEMCP
} else {
console
};
code_page_text(bytes, page).map_or_else(|| String::from_utf8_lossy(bytes), Cow::Owned)
}
pub(super) fn code_page_text(bytes: &[u8], page: u32) -> Option<String> {
let length = i32::try_from(bytes.len()).ok()?;
let size =
unsafe { MultiByteToWideChar(page, 0, bytes.as_ptr(), length, std::ptr::null_mut(), 0) };
if size <= 0 {
return None;
}
let mut wide = vec![0; size as usize];
let written =
unsafe { MultiByteToWideChar(page, 0, bytes.as_ptr(), length, wide.as_mut_ptr(), size) };
(written > 0).then(|| String::from_utf16_lossy(&wide[..written as usize]))
}