#error #error-handling #no-alloc

no-std err-into

Extension traits for core::convert::Into to use with Results and Options

2 stable releases

Uses old Rust 2015

1.0.1 Jul 22, 2023

#313 in No standard library

MIT license

7KB

Error Into

Extension traits for core::convert::Into that allow Result and Option to convert their contained values inline.

Usage

Import the traits and you are done:

use err_into::*;
// use err_into::MapInto;    // .map(Into::into)                     -> .map_into()
// use err_into::ErrorInto;  // .map_err(Into::into)                 -> .err_into()
// use err_into::ResultInto; // .map(Into::into).map_err(Into::into) -> .res_into()

Look at the documentation for more information.


lib.rs:

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))?)
}

No runtime deps