Expand description
A no_std
library to simpify chaining methods when you are returning a Result
. It is a
trivial library which sould be compatible with all environments.
This is specially noticeable when using crates like anyhow
which provide a “catch all” error type, so you need to convert all errors you recieve.
It is also helpful when you have many custom errors constructed with
thiserror
or
justerror
, or use many libraries with different error
types.
§Usage
Import the traits and you can benefit from it immediately:
use err_into::MapInto;
use err_into::ErrorInto;
use err_into::ResultInto;
// ...
let _: Option<i32> = Some(0u8).map_into();
let _: Result<i32, ()> = Ok(0u8).map_into();
let _: Result<(), i32> = Err(0u8).err_into();
let _: Result<u16, i32> = (if false { Ok(0u8) } else { Err(0i8) }).res_into();
§Motivating example
This is slightly contrived because I don’t want to depend on any libraries but showcases where
err_into
excels:
use err_into::ErrorInto;
fn process(val: u16) -> Result<u8, u8> {
if val > 255 {
Err((val >> 8) as u8)
} else {
Ok(val as _)
}
}
fn long_chain() -> Result<u8, i32> {
(0u16..16u16).map(|x| x * x * x * x)
.filter(|x| x % 2 == 0)
.map(process)
.next()
.unwrap_or(Err(0))
.err_into()
}
fn long_chain_no_err_into() -> Result<u8, i32> {
// May be confusing
(0u16..16u16).map(|x| x * x * x * x)
.filter(|x| x % 2 == 0)
.map(process)
.next()
.unwrap_or(Err(0))
.map_err(Into::into)
}
fn long_chain_no_map_err() -> Result<u8, i32> {
// Please don't do this
Ok((0u16..16u16).map(|x| x * x * x * x)
.filter(|x| x % 2 == 0)
.map(process)
.next()
.unwrap_or(Err(0))?)
}
Traits§
- Error
Into - Maps an error using
Into::into
- MapInto
- Maps a value using
Into::into
- Result
Into - Maps both the Value and the Error of a
Result
usingInto::into