Crate result_iter [] [src]

Tools for dealing with tricky error handling situations

This crate provides the ResultIterExt trait, which provides conveniences for converting collections of Result<T> types to collections of T, while handling errors correctly.

The basic way to use this library is to call fail_fast_if_err()? on any Iterator of Result, to "unwrap" all the individual elements, returning the first error encountered.

Note that although this method chains off an iterator, and produces a new iterator, it drains he former iterator before returning, and requires temporary storage proportional to the elements returned by the original iterator.

Examples

Read a directory of files to String, stopping at the first error and returning it if necessary.

extern crate result_iter;

use result_iter::ResultIterExt;
use std::io::{self, Read, BufReader};
use std::fs::{self, File};

fn run() -> Result<Vec<String>, io::Error> {
    // Read a directory of files into a Vec, where each
    // file my generate an error
    let maybe_strings;
    maybe_strings = fs::read_dir(".")?
        .map(|dirent| {
            dirent.and_then(|d| File::open(d.path()))
                .and_then(|f| {
                    let mut f = BufReader::new(f);
                    let mut s = String::new();
                    f.read_to_string(&mut s)?;
            Ok(s)})
        });

    // As soon as we encounter an error, return it.
    // Otherwise return a Vec<String>
    let strings = maybe_strings.fail_fast_if_err()?.collect();
    Ok(strings)
}

fn main() {
    let _ = run();
}

Read a directory of files to String, continuing after the first error, and returning all errors.

extern crate result_iter;

use result_iter::{ResultIterExt, MultiError};
use std::io::{self, Read, BufReader};
use std::fs::{self, File};

fn run() -> Result<Vec<String>, MultiError<io::Error>> {
    // Read a directory of files into a Vec, where each
    // file my generate an error
    let maybe_strings;
    maybe_strings = fs::read_dir(".")
        // Map io::Error to MultiError<io::Error> to satisfy
        // the example return type.
        .map_err(|e| MultiError::new(vec![e]))?
        .map(|dirent| {
            dirent.and_then(|d| File::open(d.path()))
                .and_then(|f| {
                    let mut f = BufReader::new(f);
                    let mut s = String::new();
                    f.read_to_string(&mut s)?;
            Ok(s)})
        });

    let maybe_strings = maybe_strings.collect::<Vec<_>>();
    let maybe_strings = maybe_strings.into_iter();

    // As soon as we encounter an error, return it.
    // Otherwise return a Vec<String>
    let strings = maybe_strings.fail_slow_if_err()?.collect();
    Ok(strings)
}

fn main() {
    let _ = run();
}

Structs

EndIfErrIter
MultiError

Traits

ResultIterExt