Skip to content

Commit

Permalink
Implement From<io::Error> for errno::Error
Browse files Browse the repository at this point in the history
This will automatically give us blanket implementations of Into for
io::Error and errno::Error. This simplifies things for client code that
don't want to have to handle both errno::Error and io::Error and it's
convenient because they don't have to explicitly convert between the
types themselves.

For example, if an application programmer only wants to express failures
from their code as io::Errors, then we don't have to go out of our way
to map the result, we can still use the ? operator and the blanket trait
conversions will still do the right thing:

	use std::io;

	struct ErrNo(i32);

	impl From<io::Error> for ErrNo {
	    fn from(err: io::Error) -> ErrNo {
		ErrNo(err.raw_os_error().unwrap())
	    }
	}

	impl From<ErrNo> for io::Error {
	    fn from(err: ErrNo) -> io::Error {
		io::Error::from_raw_os_error(err.0)
	    }
	}

	fn lib_returns_errno() -> Result<(), ErrNo> {
	    Err(ErrNo(9))
	}

	fn an_io_err_occurs() -> Result<(), io::Error> {
	    // Even though lib_returns_errno() will return
	    // something that is not an io::Error, the blanket
	    // trait implementations convert it seamlessly for
	    // us and we don't need to map the error into an
	    // io::Error.
	    let _res = lib_returns_errno()?;

	    Ok(())
	}

	fn main() {
	    let err = an_io_err_occurs();
	    assert!(err.is_err());
	    assert_eq!(err.unwrap_err().raw_os_error().unwrap(), 9);
	}

Signed-off-by: Connor Kuehl <[email protected]>
  • Loading branch information
Connor Kuehl authored and andreeaflorescu committed Jun 3, 2020
1 parent 93747d2 commit 80abb6f
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/errno.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ impl From<io::Error> for Error {
}
}

impl Into<io::Error> for Error {
fn into(self) -> io::Error {
io::Error::from_raw_os_error(self.0)
impl From<Error> for io::Error {
fn from(err: Error) -> io::Error {
io::Error::from_raw_os_error(err.0)
}
}

Expand Down

0 comments on commit 80abb6f

Please sign in to comment.