pub trait StashErr<T, E, S, I>: Iterator<Item = Result<T, E>>where
E: Into<I>,{
// Provided method
fn stash_err(self, stash: &mut S) -> StashErrIter<'_, Self, T, E, S, I> ⓘ
where Self: Sized { ... }
}Expand description
Adds the stash_err method on
Iterator<Item = Result<T, E>>
if E implements Into<I>.
Do not implement this trait.
Importing the trait is sufficient due to blanket implementations.
The trait is implemented automatically if E implements Into<I>,
where I is the inner error type,
typically prelude::Stashable.
Provided Methods§
Sourcefn stash_err(self, stash: &mut S) -> StashErrIter<'_, Self, T, E, S, I> ⓘwhere
Self: Sized,
fn stash_err(self, stash: &mut S) -> StashErrIter<'_, Self, T, E, S, I> ⓘwhere
Self: Sized,
Turns an Iterator<Item = Result<T, E>>
into an Iterator<Item = T>
that will move any E item into an error stash
as soon as it is encountered.
#[cfg(any(feature = "rust-v1.81", feature = "std"))]
use lazy_errors::{prelude::*, Result};
#[cfg(not(any(feature = "rust-v1.81", feature = "std")))]
use lazy_errors::surrogate_error_trait::{prelude::*, Result};
fn parse_each_u8(tokens: &[&str]) -> (Vec<u8>, usize) {
let mut errs = ErrorStash::new(|| "There were one or more errors");
let numbers: Vec<u8> = tokens
.iter()
.map(|&s| u8::from_str(s))
.stash_err(&mut errs)
.collect();
let errors = match errs.into_result() {
Ok(()) => 0,
Err(e) => e.children().len(),
};
(numbers, errors)
}
assert_eq!(parse_each_u8(&[]), (vec![], 0));
assert_eq!(parse_each_u8(&["1", "42", "3"]), (vec![1, 42, 3], 0));
assert_eq!(parse_each_u8(&["1", "XX", "3"]), (vec![1, 3], 1));
assert_eq!(parse_each_u8(&["1", "XX", "Y"]), (vec![1], 2));
assert_eq!(parse_each_u8(&["X", "YY", "Z"]), (vec![], 3));stash_err is most useful for chaining another method, such as
Iterator::filter or Iterator::map,
on the resulting Iterator<Item = T> before calling
Iterator::collect, Iterator::fold, or a similar method.
When using stash_err together with collect,
there will be no indication of whether
the iterator contained any Err items:
all Err items will simply be moved into the error stash.
If you don’t need to chain any methods between calling
stash_err and collect, or if
you need collect to fail (lazily) if
the iterator contained any Err items,
you can call try_collect_or_stash
on Iterator<Item = Result<…>> instead.
If you want to map elements of a fixed-size array,
take a look at try_map_or_stash.