subc-os 0.1.60

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
use std::{
    cmp::Ordering,
    collections::BTreeMap,
    ffi::{OsStr, OsString},
    io,
    os::windows::ffi::OsStrExt,
};

use windows_sys::Win32::Globalization::{
    CompareStringOrdinal, CSTR_EQUAL, CSTR_GREATER_THAN, CSTR_LESS_THAN,
};

struct Key(Vec<u16>);

impl PartialEq for Key {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Key {}

impl PartialOrd for Key {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Key {
    fn cmp(&self, other: &Self) -> Ordering {
        // Windows (and std's Windows Command) compare keys by case-insensitive
        // UTF-16 ordinal order, both for replacement and for block ordering.
        // SAFETY: Each length fits i32 and describes the corresponding buffer.
        match unsafe {
            CompareStringOrdinal(
                self.0.as_ptr(),
                self.0.len() as i32,
                other.0.as_ptr(),
                other.0.len() as i32,
                1,
            )
        } {
            CSTR_EQUAL => Ordering::Equal,
            CSTR_GREATER_THAN => Ordering::Greater,
            CSTR_LESS_THAN => Ordering::Less,
            _ => unreachable!("CompareStringOrdinal failed for valid UTF-16 buffers"),
        }
    }
}

/// A complete, case-insensitively sorted UTF-16 child environment block.
#[derive(Debug)]
pub struct Environment(pub(super) Vec<u16>);

impl Environment {
    /// Resolve inherited entries and then apply explicit changes. `None`
    /// removes the inherited entry; a present empty value is not a removal.
    pub fn from_entries<'a>(
        inherited: impl IntoIterator<Item = (OsString, OsString)>,
        changes: impl IntoIterator<Item = (&'a OsStr, Option<&'a OsStr>)>,
    ) -> io::Result<Self> {
        fn key(name: &OsStr) -> io::Result<Key> {
            let name = wide_without_nul(name)?;
            // Windows keeps per-drive current directories in names like =C:.
            if name.is_empty() || name.len() > i32::MAX as usize || name[1..].contains(&EQUAL) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "invalid environment name",
                ));
            }
            Ok(Key(name))
        }

        const EQUAL: u16 = b'=' as u16;
        let mut entries = BTreeMap::new();
        for (name, value) in inherited {
            entries.insert(key(&name)?, wide_without_nul(&value)?);
        }
        for (name, value) in changes {
            let name = key(name)?;
            match value {
                Some(value) => {
                    entries.insert(name, wide_without_nul(value)?);
                }
                None => {
                    entries.remove(&name);
                }
            }
        }
        let mut block = Vec::new();
        for (name, value) in entries {
            block.extend(name.0);
            block.push(EQUAL);
            block.extend(value);
            block.push(0);
        }
        if block.is_empty() {
            block.push(0);
        }
        block.push(0);
        Ok(Self(block))
    }
}

pub(super) fn wide_without_nul(value: &OsStr) -> io::Result<Vec<u16>> {
    let wide: Vec<_> = value.encode_wide().collect();
    if wide.contains(&0) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Windows string contains NUL",
        ));
    }
    Ok(wide)
}