sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::{Path, PathBuf};

use windows::Win32::Foundation::HANDLE;

use super::read::RtlUserProcessParameters;
use crate::ProcessRefreshKind;

pub(super) fn get_cwd_and_root<T: RtlUserProcessParameters>(
    params: &T,
    handle: HANDLE,
    refresh_kind: ProcessRefreshKind,
    cwd: &mut Option<PathBuf>,
    root: &mut Option<PathBuf>,
) {
    let cwd_needs_update = refresh_kind.cwd().needs_update(|| cwd.is_none());
    let root_needs_update = refresh_kind.root().needs_update(|| root.is_none());
    if !cwd_needs_update && !root_needs_update {
        return;
    }
    match params.get_cwd(handle) {
        Ok(buffer) => unsafe {
            let tmp_cwd = PathBuf::from(null_terminated_wchar_to_string(buffer.as_slice()));
            update_root(refresh_kind, &tmp_cwd, root);
            if cwd_needs_update {
                *cwd = Some(tmp_cwd);
            }
        },
        Err(_e) => {
            sinf_debug!("get_cwd_and_root failed to get data: {:?}", _e);
            *cwd = None;
        }
    }
}

pub(super) unsafe fn null_terminated_wchar_to_string(slice: &[u16]) -> OsString {
    match slice.iter().position(|&x| x == 0) {
        Some(pos) => OsString::from_wide(&slice[..pos]),
        None => OsString::from_wide(slice),
    }
}

fn update_root(refresh_kind: ProcessRefreshKind, cwd: &Path, root: &mut Option<PathBuf>) {
    if !refresh_kind.root().needs_update(|| root.is_none()) {
        return;
    }
    if cwd.has_root() {
        let mut ancestors = cwd.ancestors().peekable();
        while let Some(path) = ancestors.next() {
            if ancestors.peek().is_none() {
                *root = Some(path.into());
                return;
            }
        }
    } else {
        *root = None;
    }
}