Skip to content

Commit

Permalink
crossterm::ErrorKind to io::Error (#553)
Browse files Browse the repository at this point in the history
  • Loading branch information
Plecra authored Apr 13, 2021
1 parent 174de58 commit 58f580e
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 131 deletions.
3 changes: 1 addition & 2 deletions src/cursor/sys/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ fn read_position_raw() -> Result<(u16, u16)> {
return Err(Error::new(
ErrorKind::Other,
"The cursor position could not be read within a normal duration",
)
.into());
));
}
Err(_) => {}
}
Expand Down
10 changes: 4 additions & 6 deletions src/cursor/sys/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,7 @@ impl ScreenBufferCursor {
"Argument Out of Range Exception when setting cursor position to X: {}",
x
),
)
.into());
));
}

if y < 0 {
Expand All @@ -149,8 +148,7 @@ impl ScreenBufferCursor {
"Argument Out of Range Exception when setting cursor position to Y: {}",
y
),
)
.into());
));
}

let position = COORD { X: x, Y: y };
Expand All @@ -160,7 +158,7 @@ impl ScreenBufferCursor {
**self.screen_buffer.handle(),
position,
)) {
return Err(io::Error::last_os_error().into());
return Err(io::Error::last_os_error());
}
}
Ok(())
Expand All @@ -177,7 +175,7 @@ impl ScreenBufferCursor {
**self.screen_buffer.handle(),
&cursor_info,
)) {
return Err(io::Error::last_os_error().into());
return Err(io::Error::last_os_error());
}
}
Ok(())
Expand Down
46 changes: 2 additions & 44 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,8 @@
//! Module containing error handling logic.

use std::{
fmt::{self, Display, Formatter},
io,
};

use crate::impl_from;
use std::io;

/// The `crossterm` result type.
pub type Result<T> = std::result::Result<T, ErrorKind>;

/// Wrapper for all errors that can occur in `crossterm`.
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorKind {
IoError(io::Error),
FmtError(fmt::Error),
Utf8Error(std::string::FromUtf8Error),
ParseIntError(std::num::ParseIntError),
ResizingTerminalFailure(String),
SettingTerminalTitleFailure,
}

impl std::error::Error for ErrorKind {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ErrorKind::IoError(e) => Some(e),
ErrorKind::FmtError(e) => Some(e),
ErrorKind::Utf8Error(e) => Some(e),
ErrorKind::ParseIntError(e) => Some(e),
_ => None,
}
}
}

impl Display for ErrorKind {
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match *self {
ErrorKind::IoError(_) => write!(fmt, "IO-error occurred"),
ErrorKind::ResizingTerminalFailure(_) => write!(fmt, "Cannot resize the terminal"),
_ => write!(fmt, "Some error has occurred"),
}
}
}

impl_from!(io::Error, ErrorKind::IoError);
impl_from!(fmt::Error, ErrorKind::FmtError);
impl_from!(std::string::FromUtf8Error, ErrorKind::Utf8Error);
impl_from!(std::num::ParseIntError, ErrorKind::ParseIntError);
pub type ErrorKind = io::Error;
36 changes: 10 additions & 26 deletions src/event/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ use super::source::windows::WindowsEventSource;
#[cfg(feature = "event-stream")]
use super::sys::Waker;
use super::{filter::Filter, source::EventSource, timeout::PollTimeout, InternalEvent, Result};

use crate::ErrorKind;

/// Can be used to read `InternalEvent`s.
pub(crate) struct InternalEventReader {
events: VecDeque<InternalEvent>,
Expand Down Expand Up @@ -57,8 +54,7 @@ impl InternalEventReader {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to initialize input reader",
)
.into())
))
}
};

Expand All @@ -75,14 +71,13 @@ impl InternalEventReader {
None
}
}
Err(ErrorKind::IoError(e)) => {
Err(e) => {
if e.kind() == io::ErrorKind::Interrupted {
return Ok(false);
}

return Err(ErrorKind::IoError(e));
return Err(e);
}
Err(e) => return Err(e),
};

if poll_timeout.elapsed() || maybe_event.is_some() {
Expand Down Expand Up @@ -131,6 +126,7 @@ impl InternalEventReader {

#[cfg(test)]
mod tests {
use std::io;
use std::{collections::VecDeque, time::Duration};

use crate::ErrorKind;
Expand Down Expand Up @@ -314,7 +310,7 @@ mod tests {

#[test]
fn test_poll_propagates_error() {
let source = FakeSource::with_error(ErrorKind::ResizingTerminalFailure("Foo".to_string()));
let source = FakeSource::with_error(ErrorKind::from(io::ErrorKind::Other));

let mut reader = InternalEventReader {
events: VecDeque::new(),
Expand All @@ -327,16 +323,13 @@ mod tests {
.poll(Some(Duration::from_secs(0)), &InternalEventFilter)
.err()
.map(|e| format!("{:?}", &e)),
Some(format!(
"{:?}",
ErrorKind::ResizingTerminalFailure("Foo".to_string())
))
Some(format!("{:?}", ErrorKind::from(io::ErrorKind::Other)))
);
}

#[test]
fn test_read_propagates_error() {
let source = FakeSource::with_error(ErrorKind::ResizingTerminalFailure("Foo".to_string()));
let source = FakeSource::with_error(ErrorKind::from(io::ErrorKind::Other));

let mut reader = InternalEventReader {
events: VecDeque::new(),
Expand All @@ -349,21 +342,15 @@ mod tests {
.read(&InternalEventFilter)
.err()
.map(|e| format!("{:?}", &e)),
Some(format!(
"{:?}",
ErrorKind::ResizingTerminalFailure("Foo".to_string())
))
Some(format!("{:?}", ErrorKind::from(io::ErrorKind::Other)))
);
}

#[test]
fn test_poll_continues_after_error() {
const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10));

let source = FakeSource::new(
&[EVENT, EVENT],
ErrorKind::ResizingTerminalFailure("Foo".to_string()),
);
let source = FakeSource::new(&[EVENT, EVENT], ErrorKind::from(io::ErrorKind::Other));

let mut reader = InternalEventReader {
events: VecDeque::new(),
Expand All @@ -382,10 +369,7 @@ mod tests {
fn test_read_continues_after_error() {
const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10));

let source = FakeSource::new(
&[EVENT, EVENT],
ErrorKind::ResizingTerminalFailure("Foo".to_string()),
);
let source = FakeSource::new(&[EVENT, EVENT], ErrorKind::from(io::ErrorKind::Other));

let mut reader = InternalEventReader {
events: VecDeque::new(),
Expand Down
7 changes: 3 additions & 4 deletions src/event/source/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::VecDeque, io, time::Duration};
use mio::{unix::SourceFd, Events, Interest, Poll, Token};
use signal_hook::iterator::Signals;

use crate::{ErrorKind, Result};
use crate::Result;

#[cfg(feature = "event-stream")]
use super::super::sys::Waker;
Expand Down Expand Up @@ -87,7 +87,7 @@ impl EventSource for UnixInternalEventSource {
if e.kind() == io::ErrorKind::Interrupted {
continue;
} else {
return Err(ErrorKind::IoError(e));
return Err(e);
}
};

Expand All @@ -109,7 +109,7 @@ impl EventSource for UnixInternalEventSource {
);
}
}
Err(ErrorKind::IoError(e)) => {
Err(e) => {
// No more data to read at the moment. We will receive another event
if e.kind() == io::ErrorKind::WouldBlock {
break;
Expand All @@ -119,7 +119,6 @@ impl EventSource for UnixInternalEventSource {
continue;
}
}
Err(e) => return Err(e),
};

if let Some(event) = self.parser.next() {
Expand Down
4 changes: 2 additions & 2 deletions src/event/sys/unix/file_descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{

use libc::size_t;

use crate::{ErrorKind, Result};
use crate::Result;

/// A file descriptor wrapper.
///
Expand Down Expand Up @@ -38,7 +38,7 @@ impl FileDesc {
};

if result < 0 {
Err(ErrorKind::IoError(io::Error::last_os_error()))
Err(io::Error::last_os_error())
} else {
Ok(result as usize)
}
Expand Down
5 changes: 1 addition & 4 deletions src/event/sys/unix/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ use super::super::super::InternalEvent;
//

fn could_not_parse_event_error() -> ErrorKind {
ErrorKind::IoError(io::Error::new(
io::ErrorKind::Other,
"Could not parse an event.",
))
io::Error::new(io::ErrorKind::Other, "Could not parse an event.")
}

pub(crate) fn parse_event(buffer: &[u8], input_available: bool) -> Result<Option<InternalEvent>> {
Expand Down
5 changes: 2 additions & 3 deletions src/event/sys/windows/poll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,11 @@ impl WinApiPoll {
// timeout elapsed
Ok(None)
}
WAIT_FAILED => Err(io::Error::last_os_error().into()),
WAIT_FAILED => Err(io::Error::last_os_error()),
_ => Err(io::Error::new(
io::ErrorKind::Other,
"WaitForMultipleObjects returned unexpected result.",
)
.into()),
)),
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ macro_rules! execute {
// Queue each command, then flush
$crate::queue!($writer $(, $command)*)
.and_then(|()| {
::std::io::Write::flush($writer.by_ref()).map_err($crate::ErrorKind::IoError)
::std::io::Write::flush($writer.by_ref())
})
}}
}
Expand Down
4 changes: 2 additions & 2 deletions src/terminal/sys/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use libc::{
};
use parking_lot::Mutex;

use crate::error::{ErrorKind, Result};
use crate::error::Result;
use crate::event::sys::unix::file_descriptor::{tty_fd, FileDesc};

// Some(Termios) -> we're in the raw mode and this is the previous mode
Expand Down Expand Up @@ -129,7 +129,7 @@ fn set_terminal_attr(fd: RawFd, termios: &Termios) -> Result<()> {

fn wrap_with_result(result: i32) -> Result<()> {
if result == -1 {
Err(ErrorKind::IoError(io::Error::last_os_error()))
Err(io::Error::last_os_error())
} else {
Ok(())
}
Expand Down
Loading

0 comments on commit 58f580e

Please sign in to comment.