use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::OsStringExt;
use windows::core::PCWSTR;
use windows::Win32::System::Environment::{FreeEnvironmentStringsW, GetEnvironmentStringsW};
use super::env_key::EnvKey;
use crate::error::{win32_io_error, Error};
fn freed(result: windows::core::Result<()>) -> Result<(), Error> {
result.map_err(|e| Error::Io(win32_io_error(e)))
}
pub(crate) struct EnvSnapshot(Vec<u16>);
impl EnvSnapshot {
pub(crate) fn read() -> Result<Self, Error> {
let raw = unsafe { GetEnvironmentStringsW() };
if raw.is_null() {
return Err(Error::Io(std::io::Error::last_os_error()));
}
let mut len = 0;
unsafe {
while *raw.0.add(len) != 0 {
while *raw.0.add(len) != 0 {
len += 1;
}
len += 1;
}
}
let block = unsafe { std::slice::from_raw_parts(raw.0, len + 1) }.to_vec();
freed(unsafe { FreeEnvironmentStringsW(PCWSTR(raw.0)) })?;
Ok(Self::from_block(block))
}
pub(crate) fn from_block(mut block: Vec<u16>) -> Self {
debug_assert!(
block.last() == Some(&0) && (block.len() == 1 || block[block.len() - 2] == 0),
"an environment block ends in an empty entry"
);
if block.len() == 1 {
block.push(0);
}
Self(block)
}
pub(crate) fn block(&self) -> &[u16] {
&self.0
}
pub(crate) fn vars(&self) -> impl Iterator<Item = (OsString, OsString)> + '_ {
self.0[..self.0.len() - 1]
.split(|&u| u == 0)
.filter(|entry| !entry.is_empty())
.filter_map(|entry| {
let eq = entry[1..].iter().position(|&u| u == u16::from(b'='))? + 1;
Some((OsString::from_wide(&entry[..eq]), OsString::from_wide(&entry[eq + 1..])))
})
}
pub(crate) fn var(&self, name: &OsStr) -> Option<OsString> {
let name = EnvKey::new(name);
self.vars()
.find(|(key, _)| EnvKey::new(key) == name)
.map(|(_, val)| val)
}
}
#[cfg(test)]
#[path = "env_snapshot_tests.rs"]
mod env_snapshot_tests;