#![allow(unsafe_code)]
use std::io;
use std::os::windows::io::{AsHandle, AsRawHandle, FromRawHandle, OwnedHandle};
use std::time::Duration;
use windows_sys::Win32::Foundation::{
HANDLE, INVALID_HANDLE_VALUE, WAIT_ABANDONED, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, WaitForSingleObject};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WaitOutcome {
Signaled,
TimedOut,
Abandoned,
}
pub fn wait(handle: &impl AsHandle, timeout: Option<Duration>) -> io::Result<WaitOutcome> {
let milliseconds = timeout.map_or(u32::MAX, clamp_timeout);
let raw = handle.as_handle().as_raw_handle();
match unsafe { WaitForSingleObject(raw, milliseconds) } {
WAIT_OBJECT_0 => Ok(WaitOutcome::Signaled),
WAIT_TIMEOUT => Ok(WaitOutcome::TimedOut),
WAIT_ABANDONED => Ok(WaitOutcome::Abandoned),
WAIT_FAILED => Err(io::Error::last_os_error()),
other => Err(io::Error::other(format!(
"unexpected wait result {other:#x}"
))),
}
}
#[cfg(test)]
pub(crate) fn is_signaled(handle: &impl AsHandle) -> bool {
matches!(
wait(handle, Some(Duration::ZERO)),
Ok(WaitOutcome::Signaled | WaitOutcome::Abandoned)
)
}
pub(crate) fn current_process() -> HANDLE {
unsafe { GetCurrentProcess() }
}
pub(crate) fn owned_from_creation(handle: HANDLE) -> io::Result<OwnedHandle> {
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
pub(crate) fn clamp_timeout(timeout: Duration) -> u32 {
timeout.as_millis().min(u128::from(u32::MAX - 1)) as u32
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::clamp_timeout;
#[test]
fn timeouts_never_collapse_into_infinite() {
assert_eq!(clamp_timeout(Duration::ZERO), 0);
assert_eq!(clamp_timeout(Duration::from_millis(250)), 250);
assert_eq!(clamp_timeout(Duration::from_secs(u64::MAX)), u32::MAX - 1);
}
}