use std::{
ffi::c_void,
io,
ptr::{null_mut, NonNull},
sync::Mutex,
task::{Context, Poll, Waker},
};
use windows_sys::Win32::{
Foundation::{HANDLE, INVALID_HANDLE_VALUE},
System::Threading::{
RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE,
},
};
#[derive(Default, Debug)]
struct State {
fired: bool,
waker: Option<Waker>,
}
#[derive(Debug)]
pub(super) struct ProcessWait {
registration: HANDLE,
state: NonNull<Mutex<State>>,
}
unsafe impl Send for ProcessWait {}
unsafe impl Sync for ProcessWait {}
impl ProcessWait {
pub(super) fn new(process: HANDLE) -> io::Result<Self> {
let state = NonNull::from(Box::leak(Box::<Mutex<State>>::default()));
let mut registration = null_mut();
if unsafe {
RegisterWaitForSingleObject(
&mut registration,
process,
Some(notify),
state.as_ptr().cast(),
INFINITE,
WT_EXECUTEONLYONCE,
)
} == 0
{
let error = io::Error::last_os_error();
drop(unsafe { Box::from_raw(state.as_ptr()) });
return Err(error);
}
Ok(Self {
registration,
state,
})
}
pub(super) fn poll(&self, cx: &Context<'_>) -> Poll<()> {
let mut state = unsafe { self.state.as_ref() }
.lock()
.unwrap_or_else(|p| p.into_inner());
if state.fired {
Poll::Ready(())
} else {
match &mut state.waker {
Some(waker) => waker.clone_from(cx.waker()),
slot => *slot = Some(cx.waker().clone()),
}
Poll::Pending
}
}
}
impl Drop for ProcessWait {
fn drop(&mut self) {
if unsafe { UnregisterWaitEx(self.registration, INVALID_HANDLE_VALUE) } != 0 {
drop(unsafe { Box::from_raw(self.state.as_ptr()) });
}
}
}
unsafe extern "system" fn notify(state: *mut c_void, _: bool) {
let state = unsafe { &*state.cast::<Mutex<State>>() };
let waker = {
let mut state = state.lock().unwrap_or_else(|p| p.into_inner());
state.fired = true;
state.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
}