//! "Fallible" iterators. //! //! The iterator APIs in the Rust standard library do not support iteration //! that can fail in a first class manner. These iterators are typically modeled //! as iterating over `Result<T, E>` values; for example, the `Lines` iterator //! returns `io::Result<String>`s. When simply iterating over these types, the //! value being iterated over must be unwrapped in some way before it can be //! used: //! //! ```ignore //! for line in reader.lines() { //! let line = line?; //! // work with line //! } //! ``` //! //! In addition, many of the additional methods on the `Iterator` trait will //! not behave properly in the presence of errors when working with these kinds //! of iterators. For example, if one wanted to count the number of lines of //! text in a `Read`er, this might be a way to go about it: //! //! ```ignore //! let count = reader.lines().count(); //! ``` //! //! This will return the proper value when the reader operates successfully, but //! if it encounters an IO error, the result will either be slightly higher than //! expected if the error is transient, or it may run forever if the error is //! returned repeatedly! //! //! In contrast, a fallible iterator is built around the concept that a call to //! `next` can fail. The trait has an additional `Error` associated type in //! addition to the `Item` type, and `next` returns `Result<Option<Self::Item>, //! Self::Error>` rather than `Option<Self::Item>`. Methods like `count` return //! `Result`s as well. //! //! This does mean that fallible iterators are incompatible with Rust's `for` //! loop syntax, but `while let` loops offer a similar level of ergonomics: //! //! ```ignore //! while let Some(item) = iter.next()? { //! // work with item //! } //! ``` //! //! ## Fallible closure arguments //! //! Like `Iterator`, many `FallibleIterator` methods take closures as arguments. //! These use the same signatures as their `Iterator` counterparts, except that //! `FallibleIterator` expects the closures to be fallible: they return //! `Result<T, Self::Error>` instead of simply `T`. //! //! For example, the standard library's `Iterator::filter` adapter method //! filters the underlying iterator according to a predicate provided by the //! user, whose return type is `bool`. In `FallibleIterator::filter`, however, //! the predicate returns `Result<bool, Self::Error>`: //! //! ``` //! # use std::error::Error; //! # use std::str::FromStr; //! # use fallible_iterator::{convert, FallibleIterator}; //! let numbers = convert("100\n200\nfern\n400".lines().map(Ok::<&str, Box<Error>>)); //! let big_numbers = numbers.filter(|n| Ok(u64::from_str(n)? > 100)); //! assert!(big_numbers.count().is_err()); //! ``` #![doc(html_root_url = "https://docs.rs/fallible-iterator/0.2")] #![warn(missing_docs)] #![no_std]
use core::cmp::{self, Ordering}; use core::convert::Infallible; use core::iter; use core::marker::PhantomData;
/// An `Iterator`-like trait that allows for calculation of items to fail. pubtrait FallibleIterator { /// The type being iterated over. type Item;
/// The error type. type Error;
/// Advances the iterator and returns the next value. /// /// Returns `Ok(None)` when iteration is finished. /// /// The behavior of calling this method after a previous call has returned /// `Ok(None)` or `Err` is implementation defined. fn next(&mutself) -> Result<Option<Self::Item>, Self::Error>;
/// Returns bounds on the remaining length of the iterator. /// /// Specifically, the first half of the returned tuple is a lower bound and /// the second half is an upper bound. /// /// For the upper bound, `None` indicates that the upper bound is either /// unknown or larger than can be represented as a `usize`. /// /// Both bounds assume that all remaining calls to `next` succeed. That is, /// `next` could return an `Err` in fewer calls than specified by the lower /// bound. /// /// The default implementation returns `(0, None)`, which is correct for /// any iterator. #[inline] fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
/// Consumes the iterator, returning the number of remaining items. #[inline] fn count(self) -> Result<usize, Self::Error> where Self: Sized,
{ self.fold(0, |n, _| Ok(n + 1))
}
/// Returns the last element of the iterator. #[inline] fn last(self) -> Result<Option<Self::Item>, Self::Error> where Self: Sized,
{ self.fold(None, |_, v| Ok(Some(v)))
}
/// Returns the `n`th element of the iterator. #[inline] fn nth(&mutself, mut n: usize) -> Result<Option<Self::Item>, Self::Error> { whilelet Some(e) = self.next()? { if n == 0 { return Ok(Some(e));
}
n -= 1;
}
Ok(None)
}
/// Returns an iterator starting at the same point, but stepping by the given amount at each iteration. /// /// # Panics /// /// Panics if `step` is 0. #[inline] fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized,
{
assert!(step != 0);
StepBy {
it: self,
step: step - 1,
first_take: true,
}
}
/// Returns an iterator which yields the elements of this iterator followed /// by another. #[inline] fn chain<I>(self, it: I) -> Chain<Self, I> where
I: IntoFallibleIterator<Item = Self::Item, Error = Self::Error>, Self: Sized,
{
Chain {
front: self,
back: it,
state: ChainState::Both,
}
}
/// Returns an iterator that yields pairs of this iterator's and another /// iterator's values. #[inline] fn zip<I>(self, o: I) -> Zip<Self, I::IntoFallibleIter> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
{
Zip(self, o.into_fallible_iter())
}
/// Returns an iterator which applies a fallible transform to the elements /// of the underlying iterator. #[inline] fn map<F, B>(self, f: F) -> Map<Self, F> where Self: Sized,
F: FnMut(Self::Item) -> Result<B, Self::Error>,
{
Map { it: self, f }
}
/// Calls a fallible closure on each element of an iterator. #[inline] fn for_each<F>(self, mut f: F) -> Result<(), Self::Error> where Self: Sized,
F: FnMut(Self::Item) -> Result<(), Self::Error>,
{ self.fold((), move |(), item| f(item))
}
/// Returns an iterator which uses a predicate to determine which values /// should be yielded. The predicate may fail; such failures are passed to /// the caller. #[inline] fn filter<F>(self, f: F) -> Filter<Self, F> where Self: Sized,
F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
Filter { it: self, f }
}
/// Returns an iterator which both filters and maps. The closure may fail; /// such failures are passed along to the consumer. #[inline] fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where Self: Sized,
F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
{
FilterMap { it: self, f }
}
/// Returns an iterator which yields the current iteration count as well /// as the value. #[inline] fn enumerate(self) -> Enumerate<Self> where Self: Sized,
{
Enumerate { it: self, n: 0 }
}
/// Returns an iterator that can peek at the next element without consuming /// it. #[inline] fn peekable(self) -> Peekable<Self> where Self: Sized,
{
Peekable {
it: self,
next: None,
}
}
/// Returns an iterator that skips elements based on a predicate. #[inline] fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where Self: Sized,
P: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
SkipWhile {
it: self,
flag: false,
predicate,
}
}
/// Returns an iterator that yields elements based on a predicate. #[inline] fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where Self: Sized,
P: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
TakeWhile {
it: self,
flag: false,
predicate,
}
}
/// Returns an iterator which skips the first `n` values of this iterator. #[inline] fn skip(self, n: usize) -> Skip<Self> where Self: Sized,
{
Skip { it: self, n }
}
/// Returns an iterator that yields only the first `n` values of this /// iterator. #[inline] fn take(self, n: usize) -> Take<Self> where Self: Sized,
{
Take {
it: self,
remaining: n,
}
}
/// Returns an iterator which applies a stateful map to values of this /// iterator. #[inline] fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where Self: Sized,
F: FnMut(&mut St, Self::Item) -> Result<Option<B>, Self::Error>,
{
Scan {
it: self,
f,
state: initial_state,
}
}
/// Returns an iterator which maps this iterator's elements to iterators, yielding those iterators' values. #[inline] fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where Self: Sized,
U: IntoFallibleIterator<Error = Self::Error>,
F: FnMut(Self::Item) -> Result<U, Self::Error>,
{
FlatMap {
it: self.map(f),
cur: None,
}
}
/// Returns an iterator which flattens an iterator of iterators, yielding those iterators' values. #[inline] fn flatten(self) -> Flatten<Self> where Self: Sized, Self::Item: IntoFallibleIterator<Error = Self::Error>,
{
Flatten {
it: self,
cur: None,
}
}
/// Returns an iterator which yields this iterator's elements and ends after /// the first `Ok(None)`. /// /// The behavior of calling `next` after it has previously returned /// `Ok(None)` is normally unspecified. The iterator returned by this method /// guarantees that `Ok(None)` will always be returned. #[inline] fn fuse(self) -> Fuse<Self> where Self: Sized,
{
Fuse {
it: self,
done: false,
}
}
/// Returns an iterator which passes each element to a closure before returning it. #[inline] fn inspect<F>(self, f: F) -> Inspect<Self, F> where Self: Sized,
F: FnMut(&Self::Item) -> Result<(), Self::Error>,
{
Inspect { it: self, f }
}
/// Borrow an iterator rather than consuming it. /// /// This is useful to allow the use of iterator adaptors that would /// otherwise consume the value. #[inline] fn by_ref(&mutself) -> &mutSelf where Self: Sized,
{ self
}
/// Transforms the iterator into a collection. /// /// An `Err` will be returned if any invocation of `next` returns `Err`. #[inline] fn collect<T>(self) -> Result<T, Self::Error> where
T: iter::FromIterator<Self::Item>, Self: Sized,
{ self.iterator().collect()
}
/// Transforms the iterator into two collections, partitioning elements by a closure. #[inline] fn partition<B, F>(self, mut f: F) -> Result<(B, B), Self::Error> where Self: Sized,
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{ letmut a = B::default(); letmut b = B::default();
/// Applies a function over the elements of the iterator, producing a single /// final value. #[inline] fn fold<B, F>(mutself, init: B, f: F) -> Result<B, Self::Error> where Self: Sized,
F: FnMut(B, Self::Item) -> Result<B, Self::Error>,
{ self.try_fold(init, f)
}
/// Applies a function over the elements of the iterator, producing a single final value. /// /// This is used as the "base" of many methods on `FallibleIterator`. #[inline] fn try_fold<B, E, F>(&mutself, mut init: B, mut f: F) -> Result<B, E> where Self: Sized,
E: From<Self::Error>,
F: FnMut(B, Self::Item) -> Result<B, E>,
{ whilelet Some(v) = self.next()? {
init = f(init, v)?;
}
Ok(init)
}
/// Determines if all elements of this iterator match a predicate. #[inline] fn all<F>(&mutself, mut f: F) -> Result<bool, Self::Error> where Self: Sized,
F: FnMut(Self::Item) -> Result<bool, Self::Error>,
{ self.try_fold((), |(), v| { if !f(v)? { return Err(FoldStop::Break(false));
}
Ok(())
})
.map(|()| true)
.unpack_fold()
}
/// Determines if any element of this iterator matches a predicate. #[inline] fn any<F>(&mutself, mut f: F) -> Result<bool, Self::Error> where Self: Sized,
F: FnMut(Self::Item) -> Result<bool, Self::Error>,
{ self.try_fold((), |(), v| { if f(v)? { return Err(FoldStop::Break(true));
}
Ok(())
})
.map(|()| false)
.unpack_fold()
}
/// Returns the first element of the iterator that matches a predicate. #[inline] fn find<F>(&mutself, mut f: F) -> Result<Option<Self::Item>, Self::Error> where Self: Sized,
F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{ self.try_fold((), |(), v| { if f(&v)? { return Err(FoldStop::Break(Some(v)));
}
Ok(())
})
.map(|()| None)
.unpack_fold()
}
/// Applies a function to the elements of the iterator, returning the first non-`None` result. #[inline] fn find_map<B, F>(&mutself, f: F) -> Result<Option<B>, Self::Error> where Self: Sized,
F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
{ self.filter_map(f).next()
}
/// Returns the position of the first element of this iterator that matches /// a predicate. The predicate may fail; such failures are returned to the /// caller. #[inline] fn position<F>(&mutself, mut f: F) -> Result<Option<usize>, Self::Error> where Self: Sized,
F: FnMut(Self::Item) -> Result<bool, Self::Error>,
{ self.try_fold(0, |n, v| { if f(v)? { return Err(FoldStop::Break(Some(n)));
}
Ok(n + 1)
})
.map(|_| None)
.unpack_fold()
}
/// Returns the maximal element of the iterator. #[inline] fn max(self) -> Result<Option<Self::Item>, Self::Error> where Self: Sized, Self::Item: Ord,
{ self.max_by(|a, b| Ok(a.cmp(b)))
}
/// Returns the element of the iterator which gives the maximum value from /// the function. #[inline] fn max_by_key<B, F>(mutself, mut f: F) -> Result<Option<Self::Item>, Self::Error> where Self: Sized,
B: Ord,
F: FnMut(&Self::Item) -> Result<B, Self::Error>,
{ let max = matchself.next()? {
Some(v) => (f(&v)?, v),
None => return Ok(None),
};
/// Returns the element that gives the maximum value with respect to the function. #[inline] fn max_by<F>(mutself, mut f: F) -> Result<Option<Self::Item>, Self::Error> where Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
{ let max = matchself.next()? {
Some(v) => v,
None => return Ok(None),
};
/// Returns the minimal element of the iterator. #[inline] fn min(self) -> Result<Option<Self::Item>, Self::Error> where Self: Sized, Self::Item: Ord,
{ self.min_by(|a, b| Ok(a.cmp(b)))
}
/// Returns the element of the iterator which gives the minimum value from /// the function. #[inline] fn min_by_key<B, F>(mutself, mut f: F) -> Result<Option<Self::Item>, Self::Error> where Self: Sized,
B: Ord,
F: FnMut(&Self::Item) -> Result<B, Self::Error>,
{ let min = matchself.next()? {
Some(v) => (f(&v)?, v),
None => return Ok(None),
};
/// Returns the element that gives the minimum value with respect to the function. #[inline] fn min_by<F>(mutself, mut f: F) -> Result<Option<Self::Item>, Self::Error> where Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
{ let min = matchself.next()? {
Some(v) => v,
None => return Ok(None),
};
/// Returns an iterator that yields this iterator's items in the opposite /// order. #[inline] fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedFallibleIterator,
{
Rev(self)
}
/// Converts an iterator of pairs into a pair of containers. #[inline] fn unzip<A, B, FromA, FromB>(self) -> Result<(FromA, FromB), Self::Error> where Self: Sized + FallibleIterator<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{ letmut from_a = FromA::default(); letmut from_b = FromB::default();
/// Returns an iterator which clones all of its elements. #[inline] fn cloned<'a, T>(self) -> Cloned<Self> where Self: Sized + FallibleIterator<Item = &'a T>,
T: 'a + Clone,
{
Cloned(self)
}
/// Returns an iterator which repeats this iterator endlessly. #[inline] fn cycle(self) -> Cycle<Self> where Self: Sized + Clone,
{
Cycle {
it: self.clone(),
cur: self,
}
}
/// Lexicographically compares the elements of this iterator to that of /// another. #[inline] fn cmp<I>(mutself, other: I) -> Result<Ordering, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Item = Self::Item, Error = Self::Error>, Self::Item: Ord,
{ letmut other = other.into_fallible_iter();
/// Lexicographically compares the elements of this iterator to that of /// another. #[inline] fn partial_cmp<I>(mutself, other: I) -> Result<Option<Ordering>, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialOrd<I::Item>,
{ letmut other = other.into_fallible_iter();
/// Determines if the elements of this iterator are equal to those of /// another. #[inline] fn eq<I>(mutself, other: I) -> Result<bool, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialEq<I::Item>,
{ letmut other = other.into_fallible_iter();
loop { match (self.next()?, other.next()?) {
(None, None) => return Ok(true),
(None, _) | (_, None) => return Ok(false),
(Some(x), Some(y)) => { if x != y { return Ok(false);
}
}
}
}
}
/// Determines if the elements of this iterator are not equal to those of /// another. #[inline] fn ne<I>(mutself, other: I) -> Result<bool, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialEq<I::Item>,
{ letmut other = other.into_fallible_iter();
loop { match (self.next()?, other.next()?) {
(None, None) => return Ok(false),
(None, _) | (_, None) => return Ok(true),
(Some(x), Some(y)) => { if x != y { return Ok(true);
}
}
}
}
}
/// Determines if the elements of this iterator are lexicographically less /// than those of another. #[inline] fn lt<I>(mutself, other: I) -> Result<bool, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialOrd<I::Item>,
{ letmut other = other.into_fallible_iter();
/// Determines if the elements of this iterator are lexicographically less /// than or equal to those of another. #[inline] fn le<I>(mutself, other: I) -> Result<bool, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialOrd<I::Item>,
{ letmut other = other.into_fallible_iter();
/// Determines if the elements of this iterator are lexicographically /// greater than those of another. #[inline] fn gt<I>(mutself, other: I) -> Result<bool, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialOrd<I::Item>,
{ letmut other = other.into_fallible_iter();
/// Determines if the elements of this iterator are lexicographically /// greater than or equal to those of another. #[inline] fn ge<I>(mutself, other: I) -> Result<bool, Self::Error> where Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>, Self::Item: PartialOrd<I::Item>,
{ letmut other = other.into_fallible_iter();
/// Returns a normal (non-fallible) iterator over `Result<Item, Error>`. #[inline] fn iterator(self) -> Iterator<Self> where Self: Sized,
{
Iterator(self)
}
/// Returns an iterator which applies a transform to the errors of the /// underlying iterator. #[inline] fn map_err<B, F>(self, f: F) -> MapErr<Self, F> where
F: FnMut(Self::Error) -> B, Self: Sized,
{
MapErr { it: self, f }
}
/// Returns an iterator which unwraps all of its elements. #[inline] fn unwrap<T>(self) -> Unwrap<Self> where Self: Sized + FallibleIterator<Item = T>, Self::Error: core::fmt::Debug,
{
Unwrap(self)
}
}
impl<I: FallibleIterator + ?Sized> FallibleIterator for &mut I { type Item = I::Item; type Error = I::Error;
/// A fallible iterator able to yield elements from both ends. pubtrait DoubleEndedFallibleIterator: FallibleIterator { /// Advances the end of the iterator, returning the last value. fn next_back(&mutself) -> Result<Option<Self::Item>, Self::Error>;
/// Applies a function over the elements of the iterator in reverse order, producing a single final value. #[inline] fn rfold<B, F>(mutself, init: B, f: F) -> Result<B, Self::Error> where Self: Sized,
F: FnMut(B, Self::Item) -> Result<B, Self::Error>,
{ self.try_rfold(init, f)
}
/// Applies a function over the elements of the iterator in reverse, producing a single final value. /// /// This is used as the "base" of many methods on `DoubleEndedFallibleIterator`. #[inline] fn try_rfold<B, E, F>(&mutself, mut init: B, mut f: F) -> Result<B, E> where Self: Sized,
E: From<Self::Error>,
F: FnMut(B, Self::Item) -> Result<B, E>,
{ whilelet Some(v) = self.next_back()? {
init = f(init, v)?;
}
Ok(init)
}
}
/// Conversion into a `FallibleIterator`. pubtrait IntoFallibleIterator { /// The elements of the iterator. type Item;
/// The error value of the iterator. type Error;
/// The iterator. type IntoFallibleIter: FallibleIterator<Item = Self::Item, Error = Self::Error>;
/// Creates a fallible iterator from a value. fn into_fallible_iter(self) -> Self::IntoFallibleIter;
}
impl<I> IntoFallibleIterator for I where
I: FallibleIterator,
{ type Item = I::Item; type Error = I::Error; type IntoFallibleIter = I;
#[inline] fn into_fallible_iter(self) -> I { self
}
}
/// An iterator which applies a fallible transform to the elements of the /// underlying iterator. #[derive(Clone)] pubstruct Map<T, F> {
it: T,
f: F,
}
/// An iterator which yields the elements of one iterator followed by another. #[derive(Clone, Debug)] pubstruct Chain<T, U> {
front: T,
back: U,
state: ChainState,
}
impl<T, U> FallibleIterator for Chain<T, U> where
T: FallibleIterator,
U: FallibleIterator<Item = T::Item, Error = T::Error>,
{ type Item = T::Item; type Error = T::Error;
#[inline] fn size_hint(&self) -> (usize, Option<usize>) { let front_hint = self.front.size_hint(); let back_hint = self.back.size_hint();
let low = front_hint.0.saturating_add(back_hint.0); let high = match (front_hint.1, back_hint.1) {
(Some(f), Some(b)) => f.checked_add(b),
_ => None,
};
/// An iterator that yields the iteration count as well as the values of the /// underlying iterator. #[derive(Clone, Debug)] pubstruct Enumerate<I> {
it: I,
n: usize,
}
impl<I> FallibleIterator for Enumerate<I> where
I: FallibleIterator,
{ type Item = (usize, I::Item); type Error = I::Error;
#[inline] fn try_fold<B, E, F>(&mutself, init: B, mut f: F) -> Result<B, E> where
E: From<I::Error>,
F: FnMut(B, (usize, I::Item)) -> Result<B, E>,
{ let n = &mutself.n; self.it.try_fold(init, |acc, v| { let i = *n;
*n += 1;
f(acc, (i, v))
})
}
}
/// An iterator which uses a fallible predicate to determine which values of the /// underlying iterator should be yielded. #[derive(Clone, Debug)] pubstruct Filter<I, F> {
it: I,
f: F,
}
impl<I, F> FallibleIterator for Filter<I, F> where
I: FallibleIterator,
F: FnMut(&I::Item) -> Result<bool, I::Error>,
{ type Item = I::Item; type Error = I::Error;
/// An iterator which both filters and maps the values of the underlying /// iterator. #[derive(Clone, Debug)] pubstruct FilterMap<I, F> {
it: I,
f: F,
}
impl<B, I, F> FallibleIterator for FilterMap<I, F> where
I: FallibleIterator,
F: FnMut(I::Item) -> Result<Option<B>, I::Error>,
{ type Item = B; type Error = I::Error;
#[inline] fn try_fold<C, E, G>(&mutself, init: C, mut f: G) -> Result<C, E> where
E: From<I::Error>,
G: FnMut(C, B) -> Result<C, E>,
{ let map = &mutself.f; self.it.try_fold(init, |acc, v| match map(v)? {
Some(v) => f(acc, v),
None => Ok(acc),
})
}
}
impl<B, I, F> DoubleEndedFallibleIterator for FilterMap<I, F> where
I: DoubleEndedFallibleIterator,
F: FnMut(I::Item) -> Result<Option<B>, I::Error>,
{ #[inline] fn next_back(&mutself) -> Result<Option<B>, I::Error> { let map = &mutself.f; self.it
.try_rfold((), |(), v| match map(v)? {
Some(v) => Err(FoldStop::Break(Some(v))),
None => Ok(()),
})
.map(|()| None)
.unpack_fold()
}
#[inline] fn try_rfold<C, E, G>(&mutself, init: C, mut f: G) -> Result<C, E> where
E: From<I::Error>,
G: FnMut(C, B) -> Result<C, E>,
{ let map = &mutself.f; self.it.try_rfold(init, |acc, v| match map(v)? {
Some(v) => f(acc, v),
None => Ok(acc),
})
}
}
/// An iterator which maps each element to another iterator, yielding those iterator's elements. #[derive(Clone, Debug)] pubstruct FlatMap<I, U, F> where
U: IntoFallibleIterator,
{
it: Map<I, F>,
cur: Option<U::IntoFallibleIter>,
}
impl<I, U, F> FallibleIterator for FlatMap<I, U, F> where
I: FallibleIterator,
U: IntoFallibleIterator<Error = I::Error>,
F: FnMut(I::Item) -> Result<U, I::Error>,
{ type Item = U::Item; type Error = U::Error;
let cur = &mutself.cur; self.it.try_fold(acc, |acc, v| { letmut it = v.into_fallible_iter(); match it.try_fold(acc, &mut f) {
Ok(acc) => Ok(acc),
Err(e) => {
*cur = Some(it);
Err(e)
}
}
})
}
}
/// An iterator which flattens an iterator of iterators, yielding those iterators' elements. pubstruct Flatten<I> where
I: FallibleIterator,
I::Item: IntoFallibleIterator,
{
it: I,
cur: Option<<I::Item as IntoFallibleIterator>::IntoFallibleIter>,
}
impl<I> FallibleIterator for Flatten<I> where
I: FallibleIterator,
I::Item: IntoFallibleIterator<Error = I::Error>,
{ type Item = <I::Item as IntoFallibleIterator>::Item; type Error = <I::Item as IntoFallibleIterator>::Error;
/// An iterator that yields `Ok(None)` forever after the underlying iterator /// yields `Ok(None)` once. #[derive(Clone, Debug)] pubstruct Fuse<I> {
it: I,
done: bool,
}
impl<I> FallibleIterator for Fuse<I> where
I: FallibleIterator,
{ type Item = I::Item; type Error = I::Error;
/// An iterator which applies a transform to the errors of the underlying /// iterator. #[derive(Clone, Debug)] pubstruct MapErr<I, F> {
it: I,
f: F,
}
impl<B, F, I> FallibleIterator for MapErr<I, F> where
I: FallibleIterator,
F: FnMut(I::Error) -> B,
{ type Item = I::Item; type Error = B;
/// An iterator which can look at the next element without consuming it. #[derive(Clone, Debug)] pubstruct Peekable<I: FallibleIterator> {
it: I,
next: Option<I::Item>,
}
impl<I> Peekable<I> where
I: FallibleIterator,
{ /// Returns a reference to the next value without advancing the iterator. #[inline] pubfn peek(&mutself) -> Result<Option<&I::Item>, I::Error> { ifself.next.is_none() { self.next = self.it.next()?;
}
Ok(self.next.as_ref())
}
/// Consume and return the next value of this iterator if a condition is true. /// /// If func returns true for the next value of this iterator, consume and return it. Otherwise, return None. #[inline] pubfn next_if(&mutself, f: implFn(&I::Item) -> bool) -> Result<Option<I::Item>, I::Error> { matchself.peek()? {
Some(item) if f(item) => self.next(),
_ => Ok(None),
}
}
/// Consume and return the next item if it is equal to `expected`. #[inline] pubfn next_if_eq<T>(&mutself, expected: &T) -> Result<Option<I::Item>, I::Error> where
T: ?Sized,
I::Item: PartialEq<T>,
{ self.next_if(|found| found == expected)
}
}
impl<I> FallibleIterator for Peekable<I> where
I: FallibleIterator,
{ type Item = I::Item; type Error = I::Error;
/// An iterator which skips initial elements based on a predicate. #[derive(Clone, Debug)] pubstruct SkipWhile<I, P> {
it: I,
flag: bool,
predicate: P,
}
impl<I, P> FallibleIterator for SkipWhile<I, P> where
I: FallibleIterator,
P: FnMut(&I::Item) -> Result<bool, I::Error>,
{ type Item = I::Item; type Error = I::Error;
#[inline] fn next(&mutself) -> Result<Option<I::Item>, I::Error> { let flag = &mutself.flag; let pred = &mutself.predicate; self.it.find(move |x| { if *flag || !pred(x)? {
*flag = true;
Ok(true)
} else {
Ok(false)
}
})
}
#[inline] fn size_hint(&self) -> (usize, Option<usize>) { let hint = self.it.size_hint(); ifself.flag {
hint
} else {
(0, hint.1)
}
}
}
/// An iterator which steps through the elements of the underlying iterator by a certain amount. #[derive(Clone, Debug)] pubstruct StepBy<I> {
it: I,
step: usize,
first_take: bool,
}
impl<I> FallibleIterator for StepBy<I> where
I: FallibleIterator,
{ type Item = I::Item; type Error = I::Error;
fn size_hint(&self) -> (usize, Option<usize>) { let inner_hint = self.it.size_hint();
ifself.first_take { let f = |n| { if n == 0 { 0
} else { 1 + (n - 1) / (self.step + 1)
}
};
(f(inner_hint.0), inner_hint.1.map(f))
} else { let f = |n| n / (self.step + 1);
(f(inner_hint.0), inner_hint.1.map(f))
}
}
}
/// An iterator which yields a limited number of elements from the underlying /// iterator. #[derive(Clone, Debug)] pubstruct Take<I> {
it: I,
remaining: usize,
}
impl<I> FallibleIterator for Take<I> where
I: FallibleIterator,
{ type Item = I::Item; type Error = I::Error;
/// An extnsion-trait with set of useful methods to convert [`core::iter::Iterator`] /// into [`FallibleIterator`] pubtrait IteratorExt { /// Convert an iterator of `Result`s into `FallibleIterator` by transposition fn transpose_into_fallible<T, E>(self) -> Convert<Self> where Self: iter::Iterator<Item = Result<T, E>> + Sized;
/// Convert an iterator of anything into `FallibleIterator` by wrapping /// into `Result<T, Infallible>` where `Infallible` is an error that can never actually /// happen. fn into_fallible<T>(self) -> IntoFallible<Self> where Self: iter::Iterator<Item = T> + Sized;
}
impl<I> IteratorExt for I where
I: iter::Iterator,
{ /// Convert an iterator of `Result`s into `FallibleIterator` by transposition fn transpose_into_fallible<T, E>(self) -> Convert<Self> where Self: iter::Iterator<Item = Result<T, E>> + Sized,
{
Convert(self)
}
/// Convert an iterator of anything into `FallibleIterator` by wrapping /// into `Result<T, Infallible>` where `Infallible` is an error that can never actually /// happen. fn into_fallible<T>(self) -> IntoFallible<Self> where Self: iter::Iterator<Item = T> + Sized,
{
IntoFallible(self)
}
}
/// An iterator that yields nothing. #[derive(Clone, Debug)] pubstruct Empty<T, E>(PhantomData<T>, PhantomData<E>);
impl<T, E> FallibleIterator for Empty<T, E> { type Item = T; type Error = E;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.