use std::cmp::Ordering;
use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::OsStrExt;
use windows::Win32::Globalization::{CompareStringOrdinal, CSTR_EQUAL, CSTR_GREATER_THAN, CSTR_LESS_THAN};
#[derive(Clone, Debug)]
pub(crate) struct EnvKey {
name: OsString,
wide: Vec<u16>,
}
impl EnvKey {
pub(super) fn new(key: &OsStr) -> Self {
Self {
name: key.to_os_string(),
wide: key.encode_wide().collect(),
}
}
pub(super) fn name(&self) -> &OsStr {
&self.name
}
}
impl Ord for EnvKey {
fn cmp(&self, other: &Self) -> Ordering {
cmp_ignore_case(&self.wide, &other.wide, MAX_CHUNK)
}
}
impl PartialOrd for EnvKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for EnvKey {
fn eq(&self, other: &Self) -> bool {
self.wide.len() == other.wide.len() && self.cmp(other) == Ordering::Equal
}
}
impl Eq for EnvKey {}
const MAX_CHUNK: usize = i32::MAX as usize;
fn cmp_ignore_case(a: &[u16], b: &[u16], chunk: usize) -> Ordering {
debug_assert!(
(1..=MAX_CHUNK).contains(&chunk),
"chunk {chunk} out of CompareStringOrdinal's range"
);
for (a, b) in a.chunks(chunk).zip(b.chunks(chunk)) {
let result = unsafe { CompareStringOrdinal(a, b, true) };
match result {
CSTR_EQUAL => {}
CSTR_LESS_THAN => return Ordering::Less,
CSTR_GREATER_THAN => return Ordering::Greater,
_ => panic!("comparing environment keys failed: {}", std::io::Error::last_os_error()),
}
}
a.len().cmp(&b.len())
}
#[cfg(test)]
#[path = "env_key_tests.rs"]
mod env_key_tests;