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 {
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"),
}
}
}
#[derive(Debug)]
pub struct Environment(pub(super) Vec<u16>);
impl Environment {
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)?;
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)
}