From 18ebee8755117c08466b54bfb0e72b32c5a4092a Mon Sep 17 00:00:00 2001 From: Maxscout Date: Mon, 31 Mar 2025 21:24:47 -0400 Subject: [PATCH] Change poll_input functions to return results instead of options --- src/unix_input.rs | 11 ++++++----- src/windows_input.rs | 15 ++++++++------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/unix_input.rs b/src/unix_input.rs index ed6c3d9..385ebc7 100644 --- a/src/unix_input.rs +++ b/src/unix_input.rs @@ -44,7 +44,7 @@ impl Iterator for ReadIterator { } } -pub fn poll_input(timeout: Duration) -> Option> { +pub fn poll_input(timeout: Duration) -> io::Result { let mut fds = [PollFD { fd: STDIN_FILENO, events: POLLIN, @@ -60,12 +60,13 @@ pub fn poll_input(timeout: Duration) -> Option> { let mut read_iter = ReadIterator::new(STDIN_FILENO); if result > 0 { - let item = read_iter.next()?.ok()?; - Some(try_parse_event(item, &mut read_iter)) + let item = read_iter.next().ok_or(io::ErrorKind::InvalidData)??; + try_parse_event(item, &mut read_iter) } else if result == 0 { - None + // The function timed out. + Err(io::ErrorKind::TimedOut.into()) } else { - Some(Err(io::Error::last_os_error())) + Err(io::Error::last_os_error()) } } diff --git a/src/windows_input.rs b/src/windows_input.rs index 7c26c0c..7583a92 100644 --- a/src/windows_input.rs +++ b/src/windows_input.rs @@ -64,8 +64,8 @@ unsafe extern "system" { ) -> u32; } -pub fn poll_input(timeout: Duration) -> Option> { - let handle = get_std_handle(STD_INPUT_HANDLE).ok()?; +pub fn poll_input(timeout: Duration) -> io::Result { + let handle = get_std_handle(STD_INPUT_HANDLE)?; let mut record: InputRecord = unsafe { mem::zeroed() }; let mut read = 0; @@ -73,23 +73,24 @@ pub fn poll_input(timeout: Duration) -> Option> { let mut handles = [handle]; let result = unsafe { WaitForMultipleObjects(1, handles.as_mut_ptr(), 0, wait_time_millis) }; + // The function timed out if result != 0 { - return None; + return Err(io::ErrorKind::TimedOut.into()); } let result = unsafe { ReadConsoleInputW(handle, &mut record, 1, &mut read) }; if result == 0 { - return Some(Err(io::Error::last_os_error())); + return Err(io::Error::last_os_error())?; } if record.event_type == 1 { let key_event = unsafe { record.event.key_event }; if key_event.key_down == 0 { - return Some(Ok(Event::Key(KeyEvent::Null))); + return Ok(Event::Key(KeyEvent::Null)); } - return Some(Ok(Event::Key(parse_key_event(&key_event)))); + return Ok(Event::Key(parse_key_event(&key_event))); } - None + Err(io::ErrorKind::InvalidData.into()) } fn parse_key_event(event: &KeyEventRecord) -> KeyEvent {