From 80abb6f6264e254fb627d211f62f179ce4299c10 Mon Sep 17 00:00:00 2001 From: Connor Kuehl Date: Tue, 2 Jun 2020 12:16:05 -0700 Subject: [PATCH] Implement From for errno::Error 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 for ErrNo { fn from(err: io::Error) -> ErrNo { ErrNo(err.raw_os_error().unwrap()) } } impl From 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 --- src/errno.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/errno.rs b/src/errno.rs index cbbe6b0..5e20510 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -116,9 +116,9 @@ impl From for Error { } } -impl Into for Error { - fn into(self) -> io::Error { - io::Error::from_raw_os_error(self.0) +impl From for io::Error { + fn from(err: Error) -> io::Error { + io::Error::from_raw_os_error(err.0) } }