Debian Codegraph @

src/event/sys/windows/poll.rs

raw
1 use std::io;
2 use std::time::Duration;
3
4 use crossterm_winapi::Handle;
5 use winapi::{
6 shared::winerror::WAIT_TIMEOUT,
7 um::{
8 synchapi::WaitForMultipleObjects,
9 winbase::{INFINITE, WAIT_ABANDONED_0, WAIT_FAILED, WAIT_OBJECT_0},
10 },
11 };
12
13 #[cfg(feature = "event-stream")]
14 pub(crate) use super::waker::Waker;
15
16 #[derive(Debug)]
17 pub(crate) struct WinApiPoll {
18 #[cfg(feature = "event-stream")]
19 waker: Waker,
20 }
21
22 impl WinApiPoll {
23 #[cfg(not(feature = "event-stream"))]
24 pub(crate) fn new() -> WinApiPoll {
25 WinApiPoll {}
26 }
27
28 #[cfg(feature = "event-stream")]
29 pub(crate) fn new() -> std::io::Result<WinApiPoll> {
30 Ok(WinApiPoll {
31 waker: Waker::new()?,
32 })
33 }
34 }
35
36 impl WinApiPoll {
37 pub fn poll(&mut self, timeout: Option<Duration>) -> std::io::Result<Option<bool>> {
38 let dw_millis = if let Some(duration) = timeout {
39 duration.as_millis() as u32
40 } else {
41 INFINITE
42 };
43
44 let console_handle = Handle::current_in_handle()?;
45
46 #[cfg(feature = "event-stream")]
47 let semaphore = self.waker.semaphore();
48 #[cfg(feature = "event-stream")]
49 let handles = &[*console_handle, **semaphore.handle()];
50 #[cfg(not(feature = "event-stream"))]
51 let handles = &[*console_handle];
52
53 let output =
54 unsafe { WaitForMultipleObjects(handles.len() as u32, handles.as_ptr(), 0, dw_millis) };
55
56 match output {
57 output if output == WAIT_OBJECT_0 => {
58 // input handle triggered
59 Ok(Some(true))
60 }
61 #[cfg(feature = "event-stream")]
62 output if output == WAIT_OBJECT_0 + 1 => {
63 // semaphore handle triggered
64 let _ = self.waker.reset();
65 Err(io::Error::new(
66 io::ErrorKind::Interrupted,
67 "Poll operation was woken up by `Waker::wake`",
68 ))
69 }
70 WAIT_TIMEOUT | WAIT_ABANDONED_0 => {
71 // timeout elapsed
72 Ok(None)
73 }
74 WAIT_FAILED => Err(io::Error::last_os_error()),
75 _ => Err(io::Error::new(
76 io::ErrorKind::Other,
77 "WaitForMultipleObjects returned unexpected result.",
78 )),
79 }
80 }
81
82 #[cfg(feature = "event-stream")]
83 pub fn waker(&self) -> Waker {
84 self.waker.clone()
85 }
86 }