artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
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",
            })
    }
}

// Enough initial text to infer byte order without buffering an entire interactive line.
pub(super) const ENCODING_PREFIX: usize = 64;

/// With no BOM there is no unambiguous classifier for arbitrary output. Use aligned NULs
/// beside ASCII text as evidence of UTF-16; NUL-free byte text needs no inference.
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);
    }
    // SAFETY: returns a scalar code page for this process's console, or zero if detached.
    let console = unsafe { GetConsoleOutputCP() };
    // A console may be UTF-8 even when a redirected legacy tool uses the OEM page.
    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()?;
    // SAFETY: the input slice holds length bytes; a null output asks for the needed size.
    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];
    // SAFETY: both buffers hold the stated lengths; no pointer is retained.
    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]))
}