fallible_iterator/
lib.rs

1//! "Fallible" iterators.
2//!
3//! The iterator APIs in the Rust standard library do not support iteration
4//! that can fail in a first class manner. These iterators are typically modeled
5//! as iterating over `Result<T, E>` values; for example, the `Lines` iterator
6//! returns `io::Result<String>`s. When simply iterating over these types, the
7//! value being iterated over must be unwrapped in some way before it can be
8//! used:
9//!
10//! ```ignore
11//! for line in reader.lines() {
12//!     let line = line?;
13//!     // work with line
14//! }
15//! ```
16//!
17//! In addition, many of the additional methods on the `Iterator` trait will
18//! not behave properly in the presence of errors when working with these kinds
19//! of iterators. For example, if one wanted to count the number of lines of
20//! text in a `Read`er, this might be a way to go about it:
21//!
22//! ```ignore
23//! let count = reader.lines().count();
24//! ```
25//!
26//! This will return the proper value when the reader operates successfully, but
27//! if it encounters an IO error, the result will either be slightly higher than
28//! expected if the error is transient, or it may run forever if the error is
29//! returned repeatedly!
30//!
31//! In contrast, a fallible iterator is built around the concept that a call to
32//! `next` can fail. The trait has an additional `Error` associated type in
33//! addition to the `Item` type, and `next` returns `Result<Option<Self::Item>,
34//! Self::Error>` rather than `Option<Self::Item>`. Methods like `count` return
35//! `Result`s as well.
36//!
37//! This does mean that fallible iterators are incompatible with Rust's `for`
38//! loop syntax, but `while let` loops offer a similar level of ergonomics:
39//!
40//! ```ignore
41//! while let Some(item) = iter.next()? {
42//!     // work with item
43//! }
44//! ```
45//!
46//! ## Fallible closure arguments
47//!
48//! Like `Iterator`, many `FallibleIterator` methods take closures as arguments.
49//! These use the same signatures as their `Iterator` counterparts, except that
50//! `FallibleIterator` expects the closures to be fallible: they return
51//! `Result<T, Self::Error>` instead of simply `T`.
52//!
53//! For example, the standard library's `Iterator::filter` adapter method
54//! filters the underlying iterator according to a predicate provided by the
55//! user, whose return type is `bool`. In `FallibleIterator::filter`, however,
56//! the predicate returns `Result<bool, Self::Error>`:
57//!
58//! ```
59//! # use std::error::Error;
60//! # use std::str::FromStr;
61//! # use fallible_iterator::{convert, FallibleIterator};
62//! let numbers = convert("100\n200\nfern\n400".lines().map(Ok::<&str, Box<Error>>));
63//! let big_numbers = numbers.filter(|n| Ok(u64::from_str(n)? > 100));
64//! assert!(big_numbers.count().is_err());
65//! ```
66#![doc(html_root_url = "https://docs.rs/fallible-iterator/0.2")]
67#![warn(missing_docs)]
68#![cfg_attr(feature = "alloc", feature(alloc))]
69#![no_std]
70
71use core::cmp::{self, Ordering};
72use core::iter;
73
74#[cfg(all(feature = "alloc", not(feature = "std")))]
75#[cfg_attr(test, macro_use)]
76extern crate alloc;
77
78#[cfg(all(feature = "alloc", not(feature = "std")))]
79mod imports {
80    pub use alloc::boxed::Box;
81    pub use alloc::collections::btree_map::BTreeMap;
82    pub use alloc::collections::btree_set::BTreeSet;
83    pub use alloc::vec::Vec;
84}
85
86#[cfg(feature = "std")]
87#[cfg_attr(test, macro_use)]
88extern crate std;
89
90#[cfg(feature = "std")]
91mod imports {
92    pub use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
93    pub use std::hash::{BuildHasher, Hash};
94    pub use std::prelude::v1::*;
95}
96
97#[cfg(any(feature = "std", feature = "alloc"))]
98use crate::imports::*;
99
100#[cfg(any(feature = "std", feature = "alloc"))]
101#[cfg(test)]
102mod test;
103
104enum FoldStop<T, E> {
105    Break(T),
106    Err(E),
107}
108
109impl<T, E> From<E> for FoldStop<T, E> {
110    #[inline]
111    fn from(e: E) -> FoldStop<T, E> {
112        FoldStop::Err(e)
113    }
114}
115
116trait ResultExt<T, E> {
117    fn unpack_fold(self) -> Result<T, E>;
118}
119
120impl<T, E> ResultExt<T, E> for Result<T, FoldStop<T, E>> {
121    #[inline]
122    fn unpack_fold(self) -> Result<T, E> {
123        match self {
124            Ok(v) => Ok(v),
125            Err(FoldStop::Break(v)) => Ok(v),
126            Err(FoldStop::Err(e)) => Err(e),
127        }
128    }
129}
130
131/// An `Iterator`-like trait that allows for calculation of items to fail.
132pub trait FallibleIterator {
133    /// The type being iterated over.
134    type Item;
135
136    /// The error type.
137    type Error;
138
139    /// Advances the iterator and returns the next value.
140    ///
141    /// Returns `Ok(None)` when iteration is finished.
142    ///
143    /// The behavior of calling this method after a previous call has returned
144    /// `Ok(None)` or `Err` is implemenetation defined.
145    fn next(&mut self) -> Result<Option<Self::Item>, Self::Error>;
146
147    /// Returns bounds on the remaining length of the iterator.
148    ///
149    /// Specifically, the first half of the returned tuple is a lower bound and
150    /// the second half is an upper bound.
151    ///
152    /// For the upper bound, `None` indicates that the upper bound is either
153    /// unknown or larger than can be represented as a `usize`.
154    ///
155    /// Both bounds assume that all remaining calls to `next` succeed. That is,
156    /// `next` could return an `Err` in fewer calls than specified by the lower
157    /// bound.
158    ///
159    /// The default implementation returns `(0, None)`, which is correct for
160    /// any iterator.
161    #[inline]
162    fn size_hint(&self) -> (usize, Option<usize>) {
163        (0, None)
164    }
165
166    /// Consumes the iterator, returning the number of remaining items.
167    #[inline]
168    fn count(self) -> Result<usize, Self::Error>
169    where
170        Self: Sized,
171    {
172        self.fold(0, |n, _| Ok(n + 1))
173    }
174
175    /// Returns the last element of the iterator.
176    #[inline]
177    fn last(self) -> Result<Option<Self::Item>, Self::Error>
178    where
179        Self: Sized,
180    {
181        self.fold(None, |_, v| Ok(Some(v)))
182    }
183
184    /// Returns the `n`th element of the iterator.
185    #[inline]
186    fn nth(&mut self, mut n: usize) -> Result<Option<Self::Item>, Self::Error> {
187        while let Some(e) = self.next()? {
188            if n == 0 {
189                return Ok(Some(e));
190            }
191            n -= 1;
192        }
193        Ok(None)
194    }
195
196    /// Returns an iterator starting at the same point, but stepping by the given amount at each iteration.
197    ///
198    /// # Panics
199    ///
200    /// Panics if `step` is 0.
201    #[inline]
202    fn step_by(self, step: usize) -> StepBy<Self>
203    where
204        Self: Sized,
205    {
206        assert!(step != 0);
207        StepBy {
208            it: self,
209            step: step - 1,
210            first_take: true,
211        }
212    }
213
214    /// Returns an iterator which yields the elements of this iterator followed
215    /// by another.
216    #[inline]
217    fn chain<I>(self, it: I) -> Chain<Self, I>
218    where
219        I: IntoFallibleIterator<Item = Self::Item, Error = Self::Error>,
220        Self: Sized,
221    {
222        Chain {
223            front: self,
224            back: it,
225            state: ChainState::Both,
226        }
227    }
228
229    /// Returns an iterator that yields pairs of this iterator's and another
230    /// iterator's values.
231    #[inline]
232    fn zip<I>(self, o: I) -> Zip<Self, I::IntoFallibleIter>
233    where
234        Self: Sized,
235        I: IntoFallibleIterator<Error = Self::Error>,
236    {
237        Zip(self, o.into_fallible_iter())
238    }
239
240    /// Returns an iterator which applies a fallible transform to the elements
241    /// of the underlying iterator.
242    #[inline]
243    fn map<F, B>(self, f: F) -> Map<Self, F>
244    where
245        Self: Sized,
246        F: FnMut(Self::Item) -> Result<B, Self::Error>,
247    {
248        Map { it: self, f: f }
249    }
250
251    /// Calls a fallible closure on each element of an iterator.
252    #[inline]
253    fn for_each<F>(self, mut f: F) -> Result<(), Self::Error>
254    where
255        Self: Sized,
256        F: FnMut(Self::Item) -> Result<(), Self::Error>,
257    {
258        self.fold((), move |(), item| f(item))
259    }
260
261    /// Returns an iterator which uses a predicate to determine which values
262    /// should be yielded. The predicate may fail; such failures are passed to
263    /// the caller.
264    #[inline]
265    fn filter<F>(self, f: F) -> Filter<Self, F>
266    where
267        Self: Sized,
268        F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
269    {
270        Filter { it: self, f: f }
271    }
272
273    /// Returns an iterator which both filters and maps. The closure may fail;
274    /// such failures are passed along to the consumer.
275    #[inline]
276    fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
277    where
278        Self: Sized,
279        F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
280    {
281        FilterMap { it: self, f: f }
282    }
283
284    /// Returns an iterator which yields the current iteration count as well
285    /// as the value.
286    #[inline]
287    fn enumerate(self) -> Enumerate<Self>
288    where
289        Self: Sized,
290    {
291        Enumerate { it: self, n: 0 }
292    }
293
294    /// Returns an iterator that can peek at the next element without consuming
295    /// it.
296    #[inline]
297    fn peekable(self) -> Peekable<Self>
298    where
299        Self: Sized,
300    {
301        Peekable {
302            it: self,
303            next: None,
304        }
305    }
306
307    /// Returns an iterator that skips elements based on a predicate.
308    #[inline]
309    fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
310    where
311        Self: Sized,
312        P: FnMut(&Self::Item) -> Result<bool, Self::Error>,
313    {
314        SkipWhile {
315            it: self,
316            flag: false,
317            predicate,
318        }
319    }
320
321    /// Returns an iterator that yields elements based on a predicate.
322    #[inline]
323    fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
324    where
325        Self: Sized,
326        P: FnMut(&Self::Item) -> Result<bool, Self::Error>,
327    {
328        TakeWhile {
329            it: self,
330            flag: false,
331            predicate,
332        }
333    }
334
335    /// Returns an iterator which skips the first `n` values of this iterator.
336    #[inline]
337    fn skip(self, n: usize) -> Skip<Self>
338    where
339        Self: Sized,
340    {
341        Skip { it: self, n }
342    }
343
344    /// Returns an iterator that yields only the first `n` values of this
345    /// iterator.
346    #[inline]
347    fn take(self, n: usize) -> Take<Self>
348    where
349        Self: Sized,
350    {
351        Take {
352            it: self,
353            remaining: n,
354        }
355    }
356
357    /// Returns an iterator which applies a stateful map to values of this
358    /// iterator.
359    #[inline]
360    fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
361    where
362        Self: Sized,
363        F: FnMut(&mut St, Self::Item) -> Result<Option<B>, Self::Error>,
364    {
365        Scan {
366            it: self,
367            f,
368            state: initial_state,
369        }
370    }
371
372    /// Returns an iterator which maps this iterator's elements to iterators, yielding those iterators' values.
373    #[inline]
374    fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
375    where
376        Self: Sized,
377        U: IntoFallibleIterator<Error = Self::Error>,
378        F: FnMut(Self::Item) -> Result<U, Self::Error>,
379    {
380        FlatMap {
381            it: self.map(f),
382            cur: None,
383        }
384    }
385
386    /// Returns an iterator which flattens an iterator of iterators, yielding those iterators' values.
387    #[inline]
388    fn flatten(self) -> Flatten<Self>
389    where
390        Self: Sized,
391        Self::Item: IntoFallibleIterator<Error = Self::Error>,
392    {
393        Flatten {
394            it: self,
395            cur: None,
396        }
397    }
398
399    /// Returns an iterator which yields this iterator's elements and ends after
400    /// the first `Ok(None)`.
401    ///
402    /// The behavior of calling `next` after it has previously returned
403    /// `Ok(None)` is normally unspecified. The iterator returned by this method
404    /// guarantees that `Ok(None)` will always be returned.
405    #[inline]
406    fn fuse(self) -> Fuse<Self>
407    where
408        Self: Sized,
409    {
410        Fuse {
411            it: self,
412            done: false,
413        }
414    }
415
416    /// Returns an iterator which passes each element to a closure before returning it.
417    #[inline]
418    fn inspect<F>(self, f: F) -> Inspect<Self, F>
419    where
420        Self: Sized,
421        F: FnMut(&Self::Item) -> Result<(), Self::Error>,
422    {
423        Inspect { it: self, f }
424    }
425
426    /// Borrow an iterator rather than consuming it.
427    ///
428    /// This is useful to allow the use of iterator adaptors that would
429    /// otherwise consume the value.
430    #[inline]
431    fn by_ref(&mut self) -> &mut Self
432    where
433        Self: Sized,
434    {
435        self
436    }
437
438    /// Transforms the iterator into a collection.
439    ///
440    /// An `Err` will be returned if any invocation of `next` returns `Err`.
441    #[inline]
442    fn collect<T>(self) -> Result<T, Self::Error>
443    where
444        T: FromFallibleIterator<Self::Item>,
445        Self: Sized,
446    {
447        T::from_fallible_iter(self)
448    }
449
450    /// Transforms the iterator into two collections, partitioning elements by a closure.
451    #[inline]
452    fn partition<B, F>(self, mut f: F) -> Result<(B, B), Self::Error>
453    where
454        Self: Sized,
455        B: Default + Extend<Self::Item>,
456        F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
457    {
458        let mut a = B::default();
459        let mut b = B::default();
460
461        self.for_each(|i| {
462            if f(&i)? {
463                a.extend(Some(i));
464            } else {
465                b.extend(Some(i));
466            }
467            Ok(())
468        })?;
469
470        Ok((a, b))
471    }
472
473    /// Applies a function over the elements of the iterator, producing a single
474    /// final value.
475    #[inline]
476    fn fold<B, F>(mut self, init: B, f: F) -> Result<B, Self::Error>
477    where
478        Self: Sized,
479        F: FnMut(B, Self::Item) -> Result<B, Self::Error>,
480    {
481        self.try_fold(init, f)
482    }
483
484    /// Applies a function over the elements of the iterator, producing a single final value.
485    ///
486    /// This is used as the "base" of many methods on `FallibleIterator`.
487    #[inline]
488    fn try_fold<B, E, F>(&mut self, mut init: B, mut f: F) -> Result<B, E>
489    where
490        Self: Sized,
491        E: From<Self::Error>,
492        F: FnMut(B, Self::Item) -> Result<B, E>,
493    {
494        while let Some(v) = self.next()? {
495            init = f(init, v)?;
496        }
497        Ok(init)
498    }
499
500    /// Determines if all elements of this iterator match a predicate.
501    #[inline]
502    fn all<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
503    where
504        Self: Sized,
505        F: FnMut(Self::Item) -> Result<bool, Self::Error>,
506    {
507        self.try_fold((), |(), v| {
508            if !f(v)? {
509                return Err(FoldStop::Break(false));
510            }
511            Ok(())
512        })
513        .map(|()| true)
514        .unpack_fold()
515    }
516
517    /// Determines if any element of this iterator matches a predicate.
518    #[inline]
519    fn any<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
520    where
521        Self: Sized,
522        F: FnMut(Self::Item) -> Result<bool, Self::Error>,
523    {
524        self.try_fold((), |(), v| {
525            if f(v)? {
526                return Err(FoldStop::Break(true));
527            }
528            Ok(())
529        })
530        .map(|()| false)
531        .unpack_fold()
532    }
533
534    /// Returns the first element of the iterator that matches a predicate.
535    #[inline]
536    fn find<F>(&mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
537    where
538        Self: Sized,
539        F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
540    {
541        self.try_fold((), |(), v| {
542            if f(&v)? {
543                return Err(FoldStop::Break(Some(v)));
544            }
545            Ok(())
546        })
547        .map(|()| None)
548        .unpack_fold()
549    }
550
551    /// Applies a function to the elements of the iterator, returning the first non-`None` result.
552    #[inline]
553    fn find_map<B, F>(&mut self, f: F) -> Result<Option<B>, Self::Error>
554    where
555        Self: Sized,
556        F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
557    {
558        self.filter_map(f).next()
559    }
560
561    /// Returns the position of the first element of this iterator that matches
562    /// a predicate. The predicate may fail; such failures are returned to the
563    /// caller.
564    #[inline]
565    fn position<F>(&mut self, mut f: F) -> Result<Option<usize>, Self::Error>
566    where
567        Self: Sized,
568        F: FnMut(Self::Item) -> Result<bool, Self::Error>,
569    {
570        self.try_fold(0, |n, v| {
571            if f(v)? {
572                return Err(FoldStop::Break(Some(n)));
573            }
574            Ok(n + 1)
575        })
576        .map(|_| None)
577        .unpack_fold()
578    }
579
580    /// Returns the maximal element of the iterator.
581    #[inline]
582    fn max(self) -> Result<Option<Self::Item>, Self::Error>
583    where
584        Self: Sized,
585        Self::Item: Ord,
586    {
587        self.max_by(|a, b| Ok(a.cmp(b)))
588    }
589
590    /// Returns the element of the iterator which gives the maximum value from
591    /// the function.
592    #[inline]
593    fn max_by_key<B, F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
594    where
595        Self: Sized,
596        B: Ord,
597        F: FnMut(&Self::Item) -> Result<B, Self::Error>,
598    {
599        let max = match self.next()? {
600            Some(v) => (f(&v)?, v),
601            None => return Ok(None),
602        };
603
604        self.fold(max, |(key, max), v| {
605            let new_key = f(&v)?;
606            if key > new_key {
607                Ok((key, max))
608            } else {
609                Ok((new_key, v))
610            }
611        })
612        .map(|v| Some(v.1))
613    }
614
615    /// Returns the element that gives the maximum value with respect to the function.
616    #[inline]
617    fn max_by<F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
618    where
619        Self: Sized,
620        F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
621    {
622        let max = match self.next()? {
623            Some(v) => v,
624            None => return Ok(None),
625        };
626
627        self.fold(max, |max, v| {
628            if f(&max, &v)? == Ordering::Greater {
629                Ok(max)
630            } else {
631                Ok(v)
632            }
633        })
634        .map(Some)
635    }
636
637    /// Returns the minimal element of the iterator.
638    #[inline]
639    fn min(self) -> Result<Option<Self::Item>, Self::Error>
640    where
641        Self: Sized,
642        Self::Item: Ord,
643    {
644        self.min_by(|a, b| Ok(a.cmp(b)))
645    }
646
647    /// Returns the element of the iterator which gives the minimum value from
648    /// the function.
649    #[inline]
650    fn min_by_key<B, F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
651    where
652        Self: Sized,
653        B: Ord,
654        F: FnMut(&Self::Item) -> Result<B, Self::Error>,
655    {
656        let min = match self.next()? {
657            Some(v) => (f(&v)?, v),
658            None => return Ok(None),
659        };
660
661        self.fold(min, |(key, min), v| {
662            let new_key = f(&v)?;
663            if key < new_key {
664                Ok((key, min))
665            } else {
666                Ok((new_key, v))
667            }
668        })
669        .map(|v| Some(v.1))
670    }
671
672    /// Returns the element that gives the minimum value with respect to the function.
673    #[inline]
674    fn min_by<F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
675    where
676        Self: Sized,
677        F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
678    {
679        let min = match self.next()? {
680            Some(v) => v,
681            None => return Ok(None),
682        };
683
684        self.fold(min, |min, v| {
685            if f(&min, &v)? == Ordering::Less {
686                Ok(min)
687            } else {
688                Ok(v)
689            }
690        })
691        .map(Some)
692    }
693
694    /// Returns an iterator that yields this iterator's items in the opposite
695    /// order.
696    #[inline]
697    fn rev(self) -> Rev<Self>
698    where
699        Self: Sized + DoubleEndedFallibleIterator,
700    {
701        Rev(self)
702    }
703
704    /// Converts an iterator of pairs into a pair of containers.
705    #[inline]
706    fn unzip<A, B, FromA, FromB>(self) -> Result<(FromA, FromB), Self::Error>
707    where
708        Self: Sized + FallibleIterator<Item = (A, B)>,
709        FromA: Default + Extend<A>,
710        FromB: Default + Extend<B>,
711    {
712        let mut from_a = FromA::default();
713        let mut from_b = FromB::default();
714
715        self.for_each(|(a, b)| {
716            from_a.extend(Some(a));
717            from_b.extend(Some(b));
718            Ok(())
719        })?;
720
721        Ok((from_a, from_b))
722    }
723
724    /// Returns an iterator which clones all of its elements.
725    #[inline]
726    fn cloned<'a, T>(self) -> Cloned<Self>
727    where
728        Self: Sized + FallibleIterator<Item = &'a T>,
729        T: 'a + Clone,
730    {
731        Cloned(self)
732    }
733
734    /// Returns an iterator which repeas this iterator endlessly.
735    #[inline]
736    fn cycle(self) -> Cycle<Self>
737    where
738        Self: Sized + Clone,
739    {
740        Cycle {
741            it: self.clone(),
742            cur: self,
743        }
744    }
745
746    /// Lexicographically compares the elements of this iterator to that of
747    /// another.
748    #[inline]
749    fn cmp<I>(mut self, other: I) -> Result<Ordering, Self::Error>
750    where
751        Self: Sized,
752        I: IntoFallibleIterator<Item = Self::Item, Error = Self::Error>,
753        Self::Item: Ord,
754    {
755        let mut other = other.into_fallible_iter();
756
757        loop {
758            match (self.next()?, other.next()?) {
759                (None, None) => return Ok(Ordering::Equal),
760                (None, _) => return Ok(Ordering::Less),
761                (_, None) => return Ok(Ordering::Greater),
762                (Some(x), Some(y)) => match x.cmp(&y) {
763                    Ordering::Equal => {}
764                    o => return Ok(o),
765                },
766            }
767        }
768    }
769
770    /// Lexicographically compares the elements of this iterator to that of
771    /// another.
772    #[inline]
773    fn partial_cmp<I>(mut self, other: I) -> Result<Option<Ordering>, Self::Error>
774    where
775        Self: Sized,
776        I: IntoFallibleIterator<Error = Self::Error>,
777        Self::Item: PartialOrd<I::Item>,
778    {
779        let mut other = other.into_fallible_iter();
780
781        loop {
782            match (self.next()?, other.next()?) {
783                (None, None) => return Ok(Some(Ordering::Equal)),
784                (None, _) => return Ok(Some(Ordering::Less)),
785                (_, None) => return Ok(Some(Ordering::Greater)),
786                (Some(x), Some(y)) => match x.partial_cmp(&y) {
787                    Some(Ordering::Equal) => {}
788                    o => return Ok(o),
789                },
790            }
791        }
792    }
793
794    /// Determines if the elements of this iterator are equal to those of
795    /// another.
796    #[inline]
797    fn eq<I>(mut self, other: I) -> Result<bool, Self::Error>
798    where
799        Self: Sized,
800        I: IntoFallibleIterator<Error = Self::Error>,
801        Self::Item: PartialEq<I::Item>,
802    {
803        let mut other = other.into_fallible_iter();
804
805        loop {
806            match (self.next()?, other.next()?) {
807                (None, None) => return Ok(true),
808                (None, _) | (_, None) => return Ok(false),
809                (Some(x), Some(y)) => {
810                    if x != y {
811                        return Ok(false);
812                    }
813                }
814            }
815        }
816    }
817
818    /// Determines if the elements of this iterator are not equal to those of
819    /// another.
820    #[inline]
821    fn ne<I>(mut self, other: I) -> Result<bool, Self::Error>
822    where
823        Self: Sized,
824        I: IntoFallibleIterator<Error = Self::Error>,
825        Self::Item: PartialEq<I::Item>,
826    {
827        let mut other = other.into_fallible_iter();
828
829        loop {
830            match (self.next()?, other.next()?) {
831                (None, None) => return Ok(false),
832                (None, _) | (_, None) => return Ok(true),
833                (Some(x), Some(y)) => {
834                    if x != y {
835                        return Ok(true);
836                    }
837                }
838            }
839        }
840    }
841
842    /// Determines if the elements of this iterator are lexicographically less
843    /// than those of another.
844    #[inline]
845    fn lt<I>(mut self, other: I) -> Result<bool, Self::Error>
846    where
847        Self: Sized,
848        I: IntoFallibleIterator<Error = Self::Error>,
849        Self::Item: PartialOrd<I::Item>,
850    {
851        let mut other = other.into_fallible_iter();
852
853        loop {
854            match (self.next()?, other.next()?) {
855                (None, None) => return Ok(false),
856                (None, _) => return Ok(true),
857                (_, None) => return Ok(false),
858                (Some(x), Some(y)) => match x.partial_cmp(&y) {
859                    Some(Ordering::Less) => return Ok(true),
860                    Some(Ordering::Equal) => {}
861                    Some(Ordering::Greater) => return Ok(false),
862                    None => return Ok(false),
863                },
864            }
865        }
866    }
867
868    /// Determines if the elements of this iterator are lexicographically less
869    /// than or equal to those of another.
870    #[inline]
871    fn le<I>(mut self, other: I) -> Result<bool, Self::Error>
872    where
873        Self: Sized,
874        I: IntoFallibleIterator<Error = Self::Error>,
875        Self::Item: PartialOrd<I::Item>,
876    {
877        let mut other = other.into_fallible_iter();
878
879        loop {
880            match (self.next()?, other.next()?) {
881                (None, None) => return Ok(true),
882                (None, _) => return Ok(true),
883                (_, None) => return Ok(false),
884                (Some(x), Some(y)) => match x.partial_cmp(&y) {
885                    Some(Ordering::Less) => return Ok(true),
886                    Some(Ordering::Equal) => {}
887                    Some(Ordering::Greater) => return Ok(false),
888                    None => return Ok(false),
889                },
890            }
891        }
892    }
893
894    /// Determines if the elements of this iterator are lexicographically
895    /// greater than those of another.
896    #[inline]
897    fn gt<I>(mut self, other: I) -> Result<bool, Self::Error>
898    where
899        Self: Sized,
900        I: IntoFallibleIterator<Error = Self::Error>,
901        Self::Item: PartialOrd<I::Item>,
902    {
903        let mut other = other.into_fallible_iter();
904
905        loop {
906            match (self.next()?, other.next()?) {
907                (None, None) => return Ok(false),
908                (None, _) => return Ok(false),
909                (_, None) => return Ok(true),
910                (Some(x), Some(y)) => match x.partial_cmp(&y) {
911                    Some(Ordering::Less) => return Ok(false),
912                    Some(Ordering::Equal) => {}
913                    Some(Ordering::Greater) => return Ok(true),
914                    None => return Ok(false),
915                },
916            }
917        }
918    }
919
920    /// Determines if the elements of this iterator are lexicographically
921    /// greater than or equal to those of another.
922    #[inline]
923    fn ge<I>(mut self, other: I) -> Result<bool, Self::Error>
924    where
925        Self: Sized,
926        I: IntoFallibleIterator<Error = Self::Error>,
927        Self::Item: PartialOrd<I::Item>,
928    {
929        let mut other = other.into_fallible_iter();
930
931        loop {
932            match (self.next()?, other.next()?) {
933                (None, None) => return Ok(true),
934                (None, _) => return Ok(false),
935                (_, None) => return Ok(true),
936                (Some(x), Some(y)) => match x.partial_cmp(&y) {
937                    Some(Ordering::Less) => return Ok(false),
938                    Some(Ordering::Equal) => {}
939                    Some(Ordering::Greater) => return Ok(true),
940                    None => return Ok(false),
941                },
942            }
943        }
944    }
945
946    /// Returns a normal (non-fallible) iterator over `Result<Item, Error>`.
947    #[inline]
948    fn iterator(self) -> Iterator<Self>
949    where
950        Self: Sized,
951    {
952        Iterator(self)
953    }
954
955    /// Returns an iterator which applies a transform to the errors of the
956    /// underlying iterator.
957    #[inline]
958    fn map_err<B, F>(self, f: F) -> MapErr<Self, F>
959    where
960        F: FnMut(Self::Error) -> B,
961        Self: Sized,
962    {
963        MapErr { it: self, f: f }
964    }
965}
966
967impl<I: FallibleIterator + ?Sized> FallibleIterator for &mut I {
968    type Item = I::Item;
969    type Error = I::Error;
970
971    #[inline]
972    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
973        (**self).next()
974    }
975
976    #[inline]
977    fn size_hint(&self) -> (usize, Option<usize>) {
978        (**self).size_hint()
979    }
980
981    #[inline]
982    fn nth(&mut self, n: usize) -> Result<Option<I::Item>, I::Error> {
983        (**self).nth(n)
984    }
985}
986
987impl<I: DoubleEndedFallibleIterator + ?Sized> DoubleEndedFallibleIterator for &mut I {
988    #[inline]
989    fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
990        (**self).next_back()
991    }
992}
993
994#[cfg(any(feature = "std", feature = "alloc"))]
995impl<I: FallibleIterator + ?Sized> FallibleIterator for Box<I> {
996    type Item = I::Item;
997    type Error = I::Error;
998
999    #[inline]
1000    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
1001        (**self).next()
1002    }
1003
1004    #[inline]
1005    fn size_hint(&self) -> (usize, Option<usize>) {
1006        (**self).size_hint()
1007    }
1008
1009    #[inline]
1010    fn nth(&mut self, n: usize) -> Result<Option<I::Item>, I::Error> {
1011        (**self).nth(n)
1012    }
1013}
1014
1015#[cfg(any(feature = "std", feature = "alloc"))]
1016impl<I: DoubleEndedFallibleIterator + ?Sized> DoubleEndedFallibleIterator for Box<I> {
1017    #[inline]
1018    fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
1019        (**self).next_back()
1020    }
1021}
1022
1023/// A fallible iterator able to yield elements from both ends.
1024pub trait DoubleEndedFallibleIterator: FallibleIterator {
1025    /// Advances the end of the iterator, returning the last value.
1026    fn next_back(&mut self) -> Result<Option<Self::Item>, Self::Error>;
1027
1028    /// Applies a function over the elements of the iterator in reverse order, producing a single final value.
1029    #[inline]
1030    fn rfold<B, F>(mut self, init: B, f: F) -> Result<B, Self::Error>
1031    where
1032        Self: Sized,
1033        F: FnMut(B, Self::Item) -> Result<B, Self::Error>,
1034    {
1035        self.try_rfold(init, f)
1036    }
1037
1038    /// Applies a function over the elements of the iterator in reverse, producing a single final value.
1039    ///
1040    /// This is used as the "base" of many methods on `DoubleEndedFallibleIterator`.
1041    #[inline]
1042    fn try_rfold<B, E, F>(&mut self, mut init: B, mut f: F) -> Result<B, E>
1043    where
1044        Self: Sized,
1045        E: From<Self::Error>,
1046        F: FnMut(B, Self::Item) -> Result<B, E>,
1047    {
1048        while let Some(v) = self.next_back()? {
1049            init = f(init, v)?;
1050        }
1051        Ok(init)
1052    }
1053}
1054
1055/// Conversion from a fallible iterator.
1056pub trait FromFallibleIterator<T>: Sized {
1057    /// Creates a value from a fallible iterator.
1058    fn from_fallible_iter<I>(it: I) -> Result<Self, I::Error>
1059    where
1060        I: IntoFallibleIterator<Item = T>;
1061}
1062
1063#[cfg(any(feature = "std", feature = "alloc"))]
1064impl<T> FromFallibleIterator<T> for Vec<T> {
1065    #[inline]
1066    fn from_fallible_iter<I>(it: I) -> Result<Vec<T>, I::Error>
1067    where
1068        I: IntoFallibleIterator<Item = T>,
1069    {
1070        let it = it.into_fallible_iter();
1071        let mut vec = Vec::with_capacity(it.size_hint().0);
1072        it.for_each(|v| Ok(vec.push(v)))?;
1073        Ok(vec)
1074    }
1075}
1076
1077#[cfg(feature = "std")]
1078impl<T, S> FromFallibleIterator<T> for HashSet<T, S>
1079where
1080    T: Hash + Eq,
1081    S: BuildHasher + Default,
1082{
1083    #[inline]
1084    fn from_fallible_iter<I>(it: I) -> Result<HashSet<T, S>, I::Error>
1085    where
1086        I: IntoFallibleIterator<Item = T>,
1087    {
1088        let it = it.into_fallible_iter();
1089        let mut set = HashSet::default();
1090        set.reserve(it.size_hint().0);
1091        it.for_each(|v| {
1092            set.insert(v);
1093            Ok(())
1094        })?;
1095        Ok(set)
1096    }
1097}
1098
1099#[cfg(feature = "std")]
1100impl<K, V, S> FromFallibleIterator<(K, V)> for HashMap<K, V, S>
1101where
1102    K: Hash + Eq,
1103    S: BuildHasher + Default,
1104{
1105    #[inline]
1106    fn from_fallible_iter<I>(it: I) -> Result<HashMap<K, V, S>, I::Error>
1107    where
1108        I: IntoFallibleIterator<Item = (K, V)>,
1109    {
1110        let it = it.into_fallible_iter();
1111        let mut map = HashMap::default();
1112        map.reserve(it.size_hint().0);
1113        it.for_each(|(k, v)| {
1114            map.insert(k, v);
1115            Ok(())
1116        })?;
1117        Ok(map)
1118    }
1119}
1120
1121#[cfg(any(feature = "std", feature = "alloc"))]
1122impl<T> FromFallibleIterator<T> for BTreeSet<T>
1123where
1124    T: Ord,
1125{
1126    #[inline]
1127    fn from_fallible_iter<I>(it: I) -> Result<BTreeSet<T>, I::Error>
1128    where
1129        I: IntoFallibleIterator<Item = T>,
1130    {
1131        let it = it.into_fallible_iter();
1132        let mut set = BTreeSet::new();
1133        it.for_each(|v| {
1134            set.insert(v);
1135            Ok(())
1136        })?;
1137        Ok(set)
1138    }
1139}
1140
1141#[cfg(any(feature = "std", feature = "alloc"))]
1142impl<K, V> FromFallibleIterator<(K, V)> for BTreeMap<K, V>
1143where
1144    K: Ord,
1145{
1146    #[inline]
1147    fn from_fallible_iter<I>(it: I) -> Result<BTreeMap<K, V>, I::Error>
1148    where
1149        I: IntoFallibleIterator<Item = (K, V)>,
1150    {
1151        let it = it.into_fallible_iter();
1152        let mut map = BTreeMap::new();
1153        it.for_each(|(k, v)| {
1154            map.insert(k, v);
1155            Ok(())
1156        })?;
1157        Ok(map)
1158    }
1159}
1160
1161/// Conversion into a `FallibleIterator`.
1162pub trait IntoFallibleIterator {
1163    /// The elements of the iterator.
1164    type Item;
1165
1166    /// The error value of the iterator.
1167    type Error;
1168
1169    /// The iterator.
1170    type IntoFallibleIter: FallibleIterator<Item = Self::Item, Error = Self::Error>;
1171
1172    /// Creates a fallible iterator from a value.
1173    fn into_fallible_iter(self) -> Self::IntoFallibleIter;
1174}
1175
1176impl<I> IntoFallibleIterator for I
1177where
1178    I: FallibleIterator,
1179{
1180    type Item = I::Item;
1181    type Error = I::Error;
1182    type IntoFallibleIter = I;
1183
1184    #[inline]
1185    fn into_fallible_iter(self) -> I {
1186        self
1187    }
1188}
1189
1190/// An iterator which applies a fallible transform to the elements of the
1191/// underlying iterator.
1192#[derive(Clone, Debug)]
1193pub struct Map<T, F> {
1194    it: T,
1195    f: F,
1196}
1197
1198impl<T, F, B> FallibleIterator for Map<T, F>
1199where
1200    T: FallibleIterator,
1201    F: FnMut(T::Item) -> Result<B, T::Error>,
1202{
1203    type Item = B;
1204    type Error = T::Error;
1205
1206    #[inline]
1207    fn next(&mut self) -> Result<Option<B>, T::Error> {
1208        match self.it.next() {
1209            Ok(Some(v)) => Ok(Some((self.f)(v)?)),
1210            Ok(None) => Ok(None),
1211            Err(e) => Err(e),
1212        }
1213    }
1214
1215    #[inline]
1216    fn size_hint(&self) -> (usize, Option<usize>) {
1217        self.it.size_hint()
1218    }
1219
1220    #[inline]
1221    fn try_fold<C, E, G>(&mut self, init: C, mut f: G) -> Result<C, E>
1222    where
1223        E: From<T::Error>,
1224        G: FnMut(C, B) -> Result<C, E>,
1225    {
1226        let map = &mut self.f;
1227        self.it.try_fold(init, |b, v| f(b, map(v)?))
1228    }
1229}
1230
1231impl<B, F, I> DoubleEndedFallibleIterator for Map<I, F>
1232where
1233    I: DoubleEndedFallibleIterator,
1234    F: FnMut(I::Item) -> Result<B, I::Error>,
1235{
1236    #[inline]
1237    fn next_back(&mut self) -> Result<Option<B>, I::Error> {
1238        match self.it.next_back() {
1239            Ok(Some(v)) => Ok(Some((self.f)(v)?)),
1240            Ok(None) => Ok(None),
1241            Err(e) => Err(e),
1242        }
1243    }
1244
1245    #[inline]
1246    fn try_rfold<C, E, G>(&mut self, init: C, mut f: G) -> Result<C, E>
1247    where
1248        E: From<I::Error>,
1249        G: FnMut(C, B) -> Result<C, E>,
1250    {
1251        let map = &mut self.f;
1252        self.it.try_rfold(init, |acc, v| f(acc, map(v)?))
1253    }
1254}
1255
1256#[derive(Clone, Debug)]
1257enum ChainState {
1258    Both,
1259    Front,
1260    Back,
1261}
1262
1263/// An iterator which yields the elements of one iterator followed by another.
1264#[derive(Clone, Debug)]
1265pub struct Chain<T, U> {
1266    front: T,
1267    back: U,
1268    state: ChainState,
1269}
1270
1271impl<T, U> FallibleIterator for Chain<T, U>
1272where
1273    T: FallibleIterator,
1274    U: FallibleIterator<Item = T::Item, Error = T::Error>,
1275{
1276    type Item = T::Item;
1277    type Error = T::Error;
1278
1279    #[inline]
1280    fn next(&mut self) -> Result<Option<T::Item>, T::Error> {
1281        match self.state {
1282            ChainState::Both => match self.front.next()? {
1283                Some(e) => Ok(Some(e)),
1284                None => {
1285                    self.state = ChainState::Back;
1286                    self.back.next()
1287                }
1288            },
1289            ChainState::Front => self.front.next(),
1290            ChainState::Back => self.back.next(),
1291        }
1292    }
1293
1294    #[inline]
1295    fn size_hint(&self) -> (usize, Option<usize>) {
1296        let front_hint = self.front.size_hint();
1297        let back_hint = self.back.size_hint();
1298
1299        let low = front_hint.0.saturating_add(back_hint.0);
1300        let high = match (front_hint.1, back_hint.1) {
1301            (Some(f), Some(b)) => f.checked_add(b),
1302            _ => None,
1303        };
1304
1305        (low, high)
1306    }
1307
1308    #[inline]
1309    fn count(self) -> Result<usize, T::Error> {
1310        match self.state {
1311            ChainState::Both => Ok(self.front.count()? + self.back.count()?),
1312            ChainState::Front => self.front.count(),
1313            ChainState::Back => self.back.count(),
1314        }
1315    }
1316
1317    #[inline]
1318    fn try_fold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
1319    where
1320        E: From<T::Error>,
1321        F: FnMut(B, T::Item) -> Result<B, E>,
1322    {
1323        match self.state {
1324            ChainState::Both => {
1325                let init = self.front.try_fold(init, &mut f)?;
1326                self.state = ChainState::Back;
1327                self.back.try_fold(init, f)
1328            }
1329            ChainState::Front => self.front.try_fold(init, f),
1330            ChainState::Back => self.back.try_fold(init, f),
1331        }
1332    }
1333
1334    #[inline]
1335    fn find<F>(&mut self, mut f: F) -> Result<Option<T::Item>, T::Error>
1336    where
1337        F: FnMut(&T::Item) -> Result<bool, T::Error>,
1338    {
1339        match self.state {
1340            ChainState::Both => match self.front.find(&mut f)? {
1341                Some(v) => Ok(Some(v)),
1342                None => {
1343                    self.state = ChainState::Back;
1344                    self.back.find(f)
1345                }
1346            },
1347            ChainState::Front => self.front.find(f),
1348            ChainState::Back => self.back.find(f),
1349        }
1350    }
1351
1352    #[inline]
1353    fn last(self) -> Result<Option<T::Item>, T::Error> {
1354        match self.state {
1355            ChainState::Both => {
1356                self.front.last()?;
1357                self.back.last()
1358            }
1359            ChainState::Front => self.front.last(),
1360            ChainState::Back => self.back.last(),
1361        }
1362    }
1363}
1364
1365impl<T, U> DoubleEndedFallibleIterator for Chain<T, U>
1366where
1367    T: DoubleEndedFallibleIterator,
1368    U: DoubleEndedFallibleIterator<Item = T::Item, Error = T::Error>,
1369{
1370    #[inline]
1371    fn next_back(&mut self) -> Result<Option<T::Item>, T::Error> {
1372        match self.state {
1373            ChainState::Both => match self.back.next_back()? {
1374                Some(e) => Ok(Some(e)),
1375                None => {
1376                    self.state = ChainState::Front;
1377                    self.front.next_back()
1378                }
1379            },
1380            ChainState::Front => self.front.next_back(),
1381            ChainState::Back => self.back.next_back(),
1382        }
1383    }
1384
1385    #[inline]
1386    fn try_rfold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
1387    where
1388        E: From<T::Error>,
1389        F: FnMut(B, T::Item) -> Result<B, E>,
1390    {
1391        match self.state {
1392            ChainState::Both => {
1393                let init = self.back.try_rfold(init, &mut f)?;
1394                self.state = ChainState::Front;
1395                self.front.try_rfold(init, f)
1396            }
1397            ChainState::Front => self.front.try_rfold(init, f),
1398            ChainState::Back => self.back.try_rfold(init, f),
1399        }
1400    }
1401}
1402
1403/// An iterator which clones the elements of the underlying iterator.
1404#[derive(Clone, Debug)]
1405pub struct Cloned<I>(I);
1406
1407impl<'a, T, I> FallibleIterator for Cloned<I>
1408where
1409    I: FallibleIterator<Item = &'a T>,
1410    T: 'a + Clone,
1411{
1412    type Item = T;
1413    type Error = I::Error;
1414
1415    #[inline]
1416    fn next(&mut self) -> Result<Option<T>, I::Error> {
1417        self.0.next().map(|o| o.cloned())
1418    }
1419
1420    #[inline]
1421    fn size_hint(&self) -> (usize, Option<usize>) {
1422        self.0.size_hint()
1423    }
1424
1425    #[inline]
1426    fn try_fold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
1427    where
1428        E: From<I::Error>,
1429        F: FnMut(B, T) -> Result<B, E>,
1430    {
1431        self.0.try_fold(init, |acc, v| f(acc, v.clone()))
1432    }
1433}
1434
1435impl<'a, T, I> DoubleEndedFallibleIterator for Cloned<I>
1436where
1437    I: DoubleEndedFallibleIterator<Item = &'a T>,
1438    T: 'a + Clone,
1439{
1440    #[inline]
1441    fn next_back(&mut self) -> Result<Option<T>, I::Error> {
1442        self.0.next_back().map(|o| o.cloned())
1443    }
1444
1445    #[inline]
1446    fn try_rfold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
1447    where
1448        E: From<I::Error>,
1449        F: FnMut(B, T) -> Result<B, E>,
1450    {
1451        self.0.try_rfold(init, |acc, v| f(acc, v.clone()))
1452    }
1453}
1454
1455/// Converts an `Iterator<Item = Result<T, E>>` into a `FallibleIterator<Item = T, Error = E>`.
1456#[inline]
1457pub fn convert<T, E, I>(it: I) -> Convert<I>
1458where
1459    I: iter::Iterator<Item = Result<T, E>>,
1460{
1461    Convert(it)
1462}
1463
1464/// A fallible iterator that wraps a normal iterator over `Result`s.
1465#[derive(Clone, Debug)]
1466pub struct Convert<I>(I);
1467
1468impl<T, E, I> FallibleIterator for Convert<I>
1469where
1470    I: iter::Iterator<Item = Result<T, E>>,
1471{
1472    type Item = T;
1473    type Error = E;
1474
1475    #[inline]
1476    fn next(&mut self) -> Result<Option<T>, E> {
1477        match self.0.next() {
1478            Some(Ok(i)) => Ok(Some(i)),
1479            Some(Err(e)) => Err(e),
1480            None => Ok(None),
1481        }
1482    }
1483
1484    #[inline]
1485    fn size_hint(&self) -> (usize, Option<usize>) {
1486        self.0.size_hint()
1487    }
1488
1489    #[inline]
1490    fn try_fold<B, E2, F>(&mut self, init: B, mut f: F) -> Result<B, E2>
1491    where
1492        E2: From<E>,
1493        F: FnMut(B, T) -> Result<B, E2>,
1494    {
1495        self.0.try_fold(init, |acc, v| f(acc, v?))
1496    }
1497}
1498
1499impl<T, E, I> DoubleEndedFallibleIterator for Convert<I>
1500where
1501    I: DoubleEndedIterator<Item = Result<T, E>>,
1502{
1503    #[inline]
1504    fn next_back(&mut self) -> Result<Option<T>, E> {
1505        match self.0.next_back() {
1506            Some(Ok(i)) => Ok(Some(i)),
1507            Some(Err(e)) => Err(e),
1508            None => Ok(None),
1509        }
1510    }
1511
1512    #[inline]
1513    fn try_rfold<B, E2, F>(&mut self, init: B, mut f: F) -> Result<B, E2>
1514    where
1515        E2: From<E>,
1516        F: FnMut(B, T) -> Result<B, E2>,
1517    {
1518        self.0.try_rfold(init, |acc, v| f(acc, v?))
1519    }
1520}
1521
1522/// An iterator that yields the iteration count as well as the values of the
1523/// underlying iterator.
1524#[derive(Clone, Debug)]
1525pub struct Enumerate<I> {
1526    it: I,
1527    n: usize,
1528}
1529
1530impl<I> FallibleIterator for Enumerate<I>
1531where
1532    I: FallibleIterator,
1533{
1534    type Item = (usize, I::Item);
1535    type Error = I::Error;
1536
1537    #[inline]
1538    fn next(&mut self) -> Result<Option<(usize, I::Item)>, I::Error> {
1539        self.it.next().map(|o| {
1540            o.map(|e| {
1541                let i = self.n;
1542                self.n += 1;
1543                (i, e)
1544            })
1545        })
1546    }
1547
1548    #[inline]
1549    fn size_hint(&self) -> (usize, Option<usize>) {
1550        self.it.size_hint()
1551    }
1552
1553    #[inline]
1554    fn count(self) -> Result<usize, I::Error> {
1555        self.it.count()
1556    }
1557
1558    #[inline]
1559    fn nth(&mut self, n: usize) -> Result<Option<(usize, I::Item)>, I::Error> {
1560        match self.it.nth(n)? {
1561            Some(v) => {
1562                let i = self.n + n;
1563                self.n = i + 1;
1564                Ok(Some((i, v)))
1565            }
1566            None => Ok(None),
1567        }
1568    }
1569
1570    #[inline]
1571    fn try_fold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
1572    where
1573        E: From<I::Error>,
1574        F: FnMut(B, (usize, I::Item)) -> Result<B, E>,
1575    {
1576        let n = &mut self.n;
1577        self.it.try_fold(init, |acc, v| {
1578            let i = *n;
1579            *n += 1;
1580            f(acc, (i, v))
1581        })
1582    }
1583}
1584
1585/// An iterator which uses a fallible predicate to determine which values of the
1586/// underlying iterator should be yielded.
1587#[derive(Clone, Debug)]
1588pub struct Filter<I, F> {
1589    it: I,
1590    f: F,
1591}
1592
1593impl<I, F> FallibleIterator for Filter<I, F>
1594where
1595    I: FallibleIterator,
1596    F: FnMut(&I::Item) -> Result<bool, I::Error>,
1597{
1598    type Item = I::Item;
1599    type Error = I::Error;
1600
1601    #[inline]
1602    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
1603        let filter = &mut self.f;
1604        self.it
1605            .try_fold((), |(), v| {
1606                if filter(&v)? {
1607                    return Err(FoldStop::Break(Some(v)));
1608                }
1609                Ok(())
1610            })
1611            .map(|()| None)
1612            .unpack_fold()
1613    }
1614
1615    #[inline]
1616    fn size_hint(&self) -> (usize, Option<usize>) {
1617        (0, self.it.size_hint().1)
1618    }
1619
1620    #[inline]
1621    fn try_fold<B, E, G>(&mut self, init: B, mut f: G) -> Result<B, E>
1622    where
1623        E: From<I::Error>,
1624        G: FnMut(B, I::Item) -> Result<B, E>,
1625    {
1626        let predicate = &mut self.f;
1627        self.it.try_fold(
1628            init,
1629            |acc, v| {
1630                if predicate(&v)? {
1631                    f(acc, v)
1632                } else {
1633                    Ok(acc)
1634                }
1635            },
1636        )
1637    }
1638}
1639
1640impl<I, F> DoubleEndedFallibleIterator for Filter<I, F>
1641where
1642    I: DoubleEndedFallibleIterator,
1643    F: FnMut(&I::Item) -> Result<bool, I::Error>,
1644{
1645    #[inline]
1646    fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
1647        let filter = &mut self.f;
1648        self.it
1649            .try_rfold((), |(), v| {
1650                if filter(&v)? {
1651                    return Err(FoldStop::Break(Some(v)));
1652                }
1653                Ok(())
1654            })
1655            .map(|()| None)
1656            .unpack_fold()
1657    }
1658
1659    #[inline]
1660    fn try_rfold<B, E, G>(&mut self, init: B, mut f: G) -> Result<B, E>
1661    where
1662        E: From<I::Error>,
1663        G: FnMut(B, I::Item) -> Result<B, E>,
1664    {
1665        let predicate = &mut self.f;
1666        self.it.try_rfold(
1667            init,
1668            |acc, v| {
1669                if predicate(&v)? {
1670                    f(acc, v)
1671                } else {
1672                    Ok(acc)
1673                }
1674            },
1675        )
1676    }
1677}
1678
1679/// An iterator which both filters and maps the values of the underlying
1680/// iterator.
1681#[derive(Clone, Debug)]
1682pub struct FilterMap<I, F> {
1683    it: I,
1684    f: F,
1685}
1686
1687impl<B, I, F> FallibleIterator for FilterMap<I, F>
1688where
1689    I: FallibleIterator,
1690    F: FnMut(I::Item) -> Result<Option<B>, I::Error>,
1691{
1692    type Item = B;
1693    type Error = I::Error;
1694
1695    #[inline]
1696    fn next(&mut self) -> Result<Option<B>, I::Error> {
1697        let map = &mut self.f;
1698        self.it
1699            .try_fold((), |(), v| match map(v)? {
1700                Some(v) => Err(FoldStop::Break(Some(v))),
1701                None => Ok(()),
1702            })
1703            .map(|()| None)
1704            .unpack_fold()
1705    }
1706
1707    #[inline]
1708    fn size_hint(&self) -> (usize, Option<usize>) {
1709        (0, self.it.size_hint().1)
1710    }
1711
1712    #[inline]
1713    fn try_fold<C, E, G>(&mut self, init: C, mut f: G) -> Result<C, E>
1714    where
1715        E: From<I::Error>,
1716        G: FnMut(C, B) -> Result<C, E>,
1717    {
1718        let map = &mut self.f;
1719        self.it.try_fold(init, |acc, v| match map(v)? {
1720            Some(v) => f(acc, v),
1721            None => Ok(acc),
1722        })
1723    }
1724}
1725
1726impl<B, I, F> DoubleEndedFallibleIterator for FilterMap<I, F>
1727where
1728    I: DoubleEndedFallibleIterator,
1729    F: FnMut(I::Item) -> Result<Option<B>, I::Error>,
1730{
1731    #[inline]
1732    fn next_back(&mut self) -> Result<Option<B>, I::Error> {
1733        let map = &mut self.f;
1734        self.it
1735            .try_rfold((), |(), v| match map(v)? {
1736                Some(v) => Err(FoldStop::Break(Some(v))),
1737                None => Ok(()),
1738            })
1739            .map(|()| None)
1740            .unpack_fold()
1741    }
1742
1743    #[inline]
1744    fn try_rfold<C, E, G>(&mut self, init: C, mut f: G) -> Result<C, E>
1745    where
1746        E: From<I::Error>,
1747        G: FnMut(C, B) -> Result<C, E>,
1748    {
1749        let map = &mut self.f;
1750        self.it.try_rfold(init, |acc, v| match map(v)? {
1751            Some(v) => f(acc, v),
1752            None => Ok(acc),
1753        })
1754    }
1755}
1756
1757/// An iterator which maps each element to another iterator, yielding those iterator's elements.
1758#[derive(Clone, Debug)]
1759pub struct FlatMap<I, U, F>
1760where
1761    U: IntoFallibleIterator,
1762{
1763    it: Map<I, F>,
1764    cur: Option<U::IntoFallibleIter>,
1765}
1766
1767impl<I, U, F> FallibleIterator for FlatMap<I, U, F>
1768where
1769    I: FallibleIterator,
1770    U: IntoFallibleIterator<Error = I::Error>,
1771    F: FnMut(I::Item) -> Result<U, I::Error>,
1772{
1773    type Item = U::Item;
1774    type Error = U::Error;
1775
1776    #[inline]
1777    fn next(&mut self) -> Result<Option<U::Item>, U::Error> {
1778        loop {
1779            if let Some(it) = &mut self.cur {
1780                if let Some(v) = it.next()? {
1781                    return Ok(Some(v));
1782                }
1783            }
1784            match self.it.next()? {
1785                Some(it) => self.cur = Some(it.into_fallible_iter()),
1786                None => return Ok(None),
1787            }
1788        }
1789    }
1790
1791    #[inline]
1792    fn try_fold<B, E, G>(&mut self, init: B, mut f: G) -> Result<B, E>
1793    where
1794        E: From<U::Error>,
1795        G: FnMut(B, U::Item) -> Result<B, E>,
1796    {
1797        let mut acc = init;
1798        if let Some(cur) = &mut self.cur {
1799            acc = cur.try_fold(acc, &mut f)?;
1800            self.cur = None;
1801        }
1802
1803        let cur = &mut self.cur;
1804        self.it.try_fold(acc, |acc, v| {
1805            let mut it = v.into_fallible_iter();
1806            match it.try_fold(acc, &mut f) {
1807                Ok(acc) => Ok(acc),
1808                Err(e) => {
1809                    *cur = Some(it);
1810                    Err(e)
1811                }
1812            }
1813        })
1814    }
1815}
1816
1817/// An iterator which flattens an iterator of iterators, yielding those iterators' elements.
1818pub struct Flatten<I>
1819where
1820    I: FallibleIterator,
1821    I::Item: IntoFallibleIterator,
1822{
1823    it: I,
1824    cur: Option<<I::Item as IntoFallibleIterator>::IntoFallibleIter>,
1825}
1826
1827impl<I> Clone for Flatten<I>
1828where
1829    I: FallibleIterator + Clone,
1830    I::Item: IntoFallibleIterator,
1831    <I::Item as IntoFallibleIterator>::IntoFallibleIter: Clone,
1832{
1833    #[inline]
1834    fn clone(&self) -> Flatten<I> {
1835        Flatten {
1836            it: self.it.clone(),
1837            cur: self.cur.clone(),
1838        }
1839    }
1840}
1841
1842impl<I> FallibleIterator for Flatten<I>
1843where
1844    I: FallibleIterator,
1845    I::Item: IntoFallibleIterator<Error = I::Error>,
1846{
1847    type Item = <I::Item as IntoFallibleIterator>::Item;
1848    type Error = <I::Item as IntoFallibleIterator>::Error;
1849
1850    #[inline]
1851    fn next(&mut self) -> Result<Option<Self::Item>, Self::Error> {
1852        loop {
1853            if let Some(it) = &mut self.cur {
1854                if let Some(v) = it.next()? {
1855                    return Ok(Some(v));
1856                }
1857            }
1858            match self.it.next()? {
1859                Some(it) => self.cur = Some(it.into_fallible_iter()),
1860                None => return Ok(None),
1861            }
1862        }
1863    }
1864
1865    #[inline]
1866    fn try_fold<B, E, G>(&mut self, init: B, mut f: G) -> Result<B, E>
1867    where
1868        E: From<Self::Error>,
1869        G: FnMut(B, Self::Item) -> Result<B, E>,
1870    {
1871        let mut acc = init;
1872        if let Some(cur) = &mut self.cur {
1873            acc = cur.try_fold(acc, &mut f)?;
1874            self.cur = None;
1875        }
1876
1877        let cur = &mut self.cur;
1878        self.it.try_fold(acc, |acc, v| {
1879            let mut it = v.into_fallible_iter();
1880            match it.try_fold(acc, &mut f) {
1881                Ok(acc) => Ok(acc),
1882                Err(e) => {
1883                    *cur = Some(it);
1884                    Err(e)
1885                }
1886            }
1887        })
1888    }
1889}
1890
1891/// An iterator that yields `Ok(None)` forever after the underlying iterator
1892/// yields `Ok(None)` once.
1893#[derive(Clone, Debug)]
1894pub struct Fuse<I> {
1895    it: I,
1896    done: bool,
1897}
1898
1899impl<I> FallibleIterator for Fuse<I>
1900where
1901    I: FallibleIterator,
1902{
1903    type Item = I::Item;
1904    type Error = I::Error;
1905
1906    #[inline]
1907    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
1908        if self.done {
1909            return Ok(None);
1910        }
1911
1912        match self.it.next()? {
1913            Some(i) => Ok(Some(i)),
1914            None => {
1915                self.done = true;
1916                Ok(None)
1917            }
1918        }
1919    }
1920
1921    #[inline]
1922    fn size_hint(&self) -> (usize, Option<usize>) {
1923        if self.done {
1924            (0, Some(0))
1925        } else {
1926            self.it.size_hint()
1927        }
1928    }
1929
1930    #[inline]
1931    fn count(self) -> Result<usize, I::Error> {
1932        if self.done {
1933            Ok(0)
1934        } else {
1935            self.it.count()
1936        }
1937    }
1938
1939    #[inline]
1940    fn last(self) -> Result<Option<I::Item>, I::Error> {
1941        if self.done {
1942            Ok(None)
1943        } else {
1944            self.it.last()
1945        }
1946    }
1947
1948    #[inline]
1949    fn nth(&mut self, n: usize) -> Result<Option<I::Item>, I::Error> {
1950        if self.done {
1951            Ok(None)
1952        } else {
1953            let v = self.it.nth(n)?;
1954            if v.is_none() {
1955                self.done = true;
1956            }
1957            Ok(v)
1958        }
1959    }
1960
1961    #[inline]
1962    fn try_fold<B, E, F>(&mut self, init: B, f: F) -> Result<B, E>
1963    where
1964        E: From<I::Error>,
1965        F: FnMut(B, I::Item) -> Result<B, E>,
1966    {
1967        if self.done {
1968            Ok(init)
1969        } else {
1970            self.it.try_fold(init, f)
1971        }
1972    }
1973}
1974
1975/// An iterator which passes each element to a closure before returning it.
1976#[derive(Clone, Debug)]
1977pub struct Inspect<I, F> {
1978    it: I,
1979    f: F,
1980}
1981
1982impl<I, F> FallibleIterator for Inspect<I, F>
1983where
1984    I: FallibleIterator,
1985    F: FnMut(&I::Item) -> Result<(), I::Error>,
1986{
1987    type Item = I::Item;
1988    type Error = I::Error;
1989
1990    #[inline]
1991    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
1992        match self.it.next()? {
1993            Some(i) => {
1994                (self.f)(&i)?;
1995                Ok(Some(i))
1996            }
1997            None => Ok(None),
1998        }
1999    }
2000
2001    #[inline]
2002    fn size_hint(&self) -> (usize, Option<usize>) {
2003        self.it.size_hint()
2004    }
2005
2006    #[inline]
2007    fn try_fold<B, E, G>(&mut self, init: B, mut f: G) -> Result<B, E>
2008    where
2009        E: From<I::Error>,
2010        G: FnMut(B, I::Item) -> Result<B, E>,
2011    {
2012        let inspect = &mut self.f;
2013        self.it.try_fold(init, |acc, v| {
2014            inspect(&v)?;
2015            f(acc, v)
2016        })
2017    }
2018}
2019
2020impl<I, F> DoubleEndedFallibleIterator for Inspect<I, F>
2021where
2022    I: DoubleEndedFallibleIterator,
2023    F: FnMut(&I::Item) -> Result<(), I::Error>,
2024{
2025    #[inline]
2026    fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
2027        match self.it.next_back()? {
2028            Some(i) => {
2029                (self.f)(&i)?;
2030                Ok(Some(i))
2031            }
2032            None => Ok(None),
2033        }
2034    }
2035
2036    #[inline]
2037    fn try_rfold<B, E, G>(&mut self, init: B, mut f: G) -> Result<B, E>
2038    where
2039        E: From<I::Error>,
2040        G: FnMut(B, I::Item) -> Result<B, E>,
2041    {
2042        let inspect = &mut self.f;
2043        self.it.try_rfold(init, |acc, v| {
2044            inspect(&v)?;
2045            f(acc, v)
2046        })
2047    }
2048}
2049
2050/// A normal (non-fallible) iterator which wraps a fallible iterator.
2051#[derive(Clone, Debug)]
2052pub struct Iterator<I>(I);
2053
2054impl<I> iter::Iterator for Iterator<I>
2055where
2056    I: FallibleIterator,
2057{
2058    type Item = Result<I::Item, I::Error>;
2059
2060    #[inline]
2061    fn next(&mut self) -> Option<Result<I::Item, I::Error>> {
2062        match self.0.next() {
2063            Ok(Some(v)) => Some(Ok(v)),
2064            Ok(None) => None,
2065            Err(e) => Some(Err(e)),
2066        }
2067    }
2068
2069    #[inline]
2070    fn size_hint(&self) -> (usize, Option<usize>) {
2071        self.0.size_hint()
2072    }
2073}
2074
2075impl<I> DoubleEndedIterator for Iterator<I>
2076where
2077    I: DoubleEndedFallibleIterator,
2078{
2079    #[inline]
2080    fn next_back(&mut self) -> Option<Result<I::Item, I::Error>> {
2081        match self.0.next_back() {
2082            Ok(Some(v)) => Some(Ok(v)),
2083            Ok(None) => None,
2084            Err(e) => Some(Err(e)),
2085        }
2086    }
2087}
2088
2089/// An iterator which applies a transform to the errors of the underlying
2090/// iterator.
2091#[derive(Clone, Debug)]
2092pub struct MapErr<I, F> {
2093    it: I,
2094    f: F,
2095}
2096
2097impl<B, F, I> FallibleIterator for MapErr<I, F>
2098where
2099    I: FallibleIterator,
2100    F: FnMut(I::Error) -> B,
2101{
2102    type Item = I::Item;
2103    type Error = B;
2104
2105    #[inline]
2106    fn next(&mut self) -> Result<Option<I::Item>, B> {
2107        self.it.next().map_err(&mut self.f)
2108    }
2109
2110    #[inline]
2111    fn size_hint(&self) -> (usize, Option<usize>) {
2112        self.it.size_hint()
2113    }
2114
2115    #[inline]
2116    fn count(mut self) -> Result<usize, B> {
2117        self.it.count().map_err(&mut self.f)
2118    }
2119
2120    #[inline]
2121    fn last(mut self) -> Result<Option<I::Item>, B> {
2122        self.it.last().map_err(&mut self.f)
2123    }
2124
2125    #[inline]
2126    fn nth(&mut self, n: usize) -> Result<Option<I::Item>, B> {
2127        self.it.nth(n).map_err(&mut self.f)
2128    }
2129
2130    #[inline]
2131    fn try_fold<C, E, G>(&mut self, init: C, mut f: G) -> Result<C, E>
2132    where
2133        E: From<B>,
2134        G: FnMut(C, I::Item) -> Result<C, E>,
2135    {
2136        self.it
2137            .try_fold(init, |acc, v| f(acc, v).map_err(MappedErr::Fold))
2138            .map_err(|e| match e {
2139                MappedErr::It(e) => (self.f)(e).into(),
2140                MappedErr::Fold(e) => e,
2141            })
2142    }
2143}
2144
2145impl<B, F, I> DoubleEndedFallibleIterator for MapErr<I, F>
2146where
2147    I: DoubleEndedFallibleIterator,
2148    F: FnMut(I::Error) -> B,
2149{
2150    #[inline]
2151    fn next_back(&mut self) -> Result<Option<I::Item>, B> {
2152        self.it.next_back().map_err(&mut self.f)
2153    }
2154
2155    #[inline]
2156    fn try_rfold<C, E, G>(&mut self, init: C, mut f: G) -> Result<C, E>
2157    where
2158        E: From<B>,
2159        G: FnMut(C, I::Item) -> Result<C, E>,
2160    {
2161        self.it
2162            .try_rfold(init, |acc, v| f(acc, v).map_err(MappedErr::Fold))
2163            .map_err(|e| match e {
2164                MappedErr::It(e) => (self.f)(e).into(),
2165                MappedErr::Fold(e) => e,
2166            })
2167    }
2168}
2169
2170enum MappedErr<T, U> {
2171    It(T),
2172    Fold(U),
2173}
2174
2175impl<T, U> From<T> for MappedErr<T, U> {
2176    #[inline]
2177    fn from(t: T) -> MappedErr<T, U> {
2178        MappedErr::It(t)
2179    }
2180}
2181
2182/// An iterator which can look at the next element without consuming it.
2183#[derive(Clone, Debug)]
2184pub struct Peekable<I: FallibleIterator> {
2185    it: I,
2186    next: Option<I::Item>,
2187}
2188
2189impl<I> Peekable<I>
2190where
2191    I: FallibleIterator,
2192{
2193    /// Returns a reference to the next value without advancing the iterator.
2194    #[inline]
2195    pub fn peek(&mut self) -> Result<Option<&I::Item>, I::Error> {
2196        if self.next.is_none() {
2197            self.next = self.it.next()?;
2198        }
2199
2200        Ok(self.next.as_ref())
2201    }
2202}
2203
2204impl<I> FallibleIterator for Peekable<I>
2205where
2206    I: FallibleIterator,
2207{
2208    type Item = I::Item;
2209    type Error = I::Error;
2210
2211    #[inline]
2212    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2213        if let Some(next) = self.next.take() {
2214            return Ok(Some(next));
2215        }
2216
2217        self.it.next()
2218    }
2219
2220    #[inline]
2221    fn size_hint(&self) -> (usize, Option<usize>) {
2222        let mut hint = self.it.size_hint();
2223        if self.next.is_some() {
2224            hint.0 = hint.0.saturating_add(1);
2225            hint.1 = hint.1.and_then(|h| h.checked_add(1));
2226        }
2227        hint
2228    }
2229
2230    #[inline]
2231    fn try_fold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
2232    where
2233        E: From<I::Error>,
2234        F: FnMut(B, I::Item) -> Result<B, E>,
2235    {
2236        let mut acc = init;
2237        if let Some(v) = self.next.take() {
2238            acc = f(acc, v)?;
2239        }
2240        self.it.try_fold(acc, f)
2241    }
2242}
2243
2244/// An iterator which yields elements of the underlying iterator in reverse
2245/// order.
2246#[derive(Clone, Debug)]
2247pub struct Rev<I>(I);
2248
2249impl<I> FallibleIterator for Rev<I>
2250where
2251    I: DoubleEndedFallibleIterator,
2252{
2253    type Item = I::Item;
2254    type Error = I::Error;
2255
2256    #[inline]
2257    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2258        self.0.next_back()
2259    }
2260
2261    #[inline]
2262    fn size_hint(&self) -> (usize, Option<usize>) {
2263        self.0.size_hint()
2264    }
2265
2266    #[inline]
2267    fn count(self) -> Result<usize, I::Error> {
2268        self.0.count()
2269    }
2270
2271    #[inline]
2272    fn try_fold<B, E, F>(&mut self, init: B, f: F) -> Result<B, E>
2273    where
2274        E: From<I::Error>,
2275        F: FnMut(B, I::Item) -> Result<B, E>,
2276    {
2277        self.0.try_rfold(init, f)
2278    }
2279}
2280
2281impl<I> DoubleEndedFallibleIterator for Rev<I>
2282where
2283    I: DoubleEndedFallibleIterator,
2284{
2285    #[inline]
2286    fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
2287        self.0.next()
2288    }
2289
2290    #[inline]
2291    fn try_rfold<B, E, F>(&mut self, init: B, f: F) -> Result<B, E>
2292    where
2293        E: From<I::Error>,
2294        F: FnMut(B, I::Item) -> Result<B, E>,
2295    {
2296        self.0.try_fold(init, f)
2297    }
2298}
2299
2300/// An iterator which applies a stateful closure.
2301#[derive(Clone, Debug)]
2302pub struct Scan<I, St, F> {
2303    it: I,
2304    f: F,
2305    state: St,
2306}
2307
2308impl<B, I, St, F> FallibleIterator for Scan<I, St, F>
2309where
2310    I: FallibleIterator,
2311    F: FnMut(&mut St, I::Item) -> Result<Option<B>, I::Error>,
2312{
2313    type Item = B;
2314    type Error = I::Error;
2315
2316    #[inline]
2317    fn next(&mut self) -> Result<Option<B>, I::Error> {
2318        match self.it.next()? {
2319            Some(v) => (self.f)(&mut self.state, v),
2320            None => Ok(None),
2321        }
2322    }
2323
2324    #[inline]
2325    fn size_hint(&self) -> (usize, Option<usize>) {
2326        let hint = self.it.size_hint();
2327        (0, hint.1)
2328    }
2329}
2330
2331/// An iterator which skips initial elements.
2332#[derive(Clone, Debug)]
2333pub struct Skip<I> {
2334    it: I,
2335    n: usize,
2336}
2337
2338impl<I> FallibleIterator for Skip<I>
2339where
2340    I: FallibleIterator,
2341{
2342    type Item = I::Item;
2343    type Error = I::Error;
2344
2345    #[inline]
2346    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2347        if self.n == 0 {
2348            self.it.next()
2349        } else {
2350            let n = self.n;
2351            self.n = 0;
2352            self.it.nth(n)
2353        }
2354    }
2355
2356    #[inline]
2357    fn size_hint(&self) -> (usize, Option<usize>) {
2358        let hint = self.it.size_hint();
2359
2360        (
2361            hint.0.saturating_sub(self.n),
2362            hint.1.map(|x| x.saturating_sub(self.n)),
2363        )
2364    }
2365}
2366
2367/// An iterator which skips initial elements based on a predicate.
2368#[derive(Clone, Debug)]
2369pub struct SkipWhile<I, P> {
2370    it: I,
2371    flag: bool,
2372    predicate: P,
2373}
2374
2375impl<I, P> FallibleIterator for SkipWhile<I, P>
2376where
2377    I: FallibleIterator,
2378    P: FnMut(&I::Item) -> Result<bool, I::Error>,
2379{
2380    type Item = I::Item;
2381    type Error = I::Error;
2382
2383    #[inline]
2384    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2385        let flag = &mut self.flag;
2386        let pred = &mut self.predicate;
2387        self.it.find(move |x| {
2388            if *flag || !pred(x)? {
2389                *flag = true;
2390                Ok(true)
2391            } else {
2392                Ok(false)
2393            }
2394        })
2395    }
2396
2397    #[inline]
2398    fn size_hint(&self) -> (usize, Option<usize>) {
2399        let hint = self.it.size_hint();
2400        if self.flag {
2401            hint
2402        } else {
2403            (0, hint.1)
2404        }
2405    }
2406}
2407
2408/// An iterator which steps through the elements of the underlying iterator by a certain amount.
2409#[derive(Clone, Debug)]
2410pub struct StepBy<I> {
2411    it: I,
2412    step: usize,
2413    first_take: bool,
2414}
2415
2416impl<I> FallibleIterator for StepBy<I>
2417where
2418    I: FallibleIterator,
2419{
2420    type Item = I::Item;
2421    type Error = I::Error;
2422
2423    #[inline]
2424    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2425        if self.first_take {
2426            self.first_take = false;
2427            self.it.next()
2428        } else {
2429            self.it.nth(self.step)
2430        }
2431    }
2432
2433    fn size_hint(&self) -> (usize, Option<usize>) {
2434        let inner_hint = self.it.size_hint();
2435
2436        if self.first_take {
2437            let f = |n| {
2438                if n == 0 {
2439                    0
2440                } else {
2441                    1 + (n - 1) / (self.step + 1)
2442                }
2443            };
2444            (f(inner_hint.0), inner_hint.1.map(f))
2445        } else {
2446            let f = |n| n / (self.step + 1);
2447            (f(inner_hint.0), inner_hint.1.map(f))
2448        }
2449    }
2450}
2451
2452/// An iterator which yields a limited number of elements from the underlying
2453/// iterator.
2454#[derive(Clone, Debug)]
2455pub struct Take<I> {
2456    it: I,
2457    remaining: usize,
2458}
2459
2460impl<I> FallibleIterator for Take<I>
2461where
2462    I: FallibleIterator,
2463{
2464    type Item = I::Item;
2465    type Error = I::Error;
2466
2467    #[inline]
2468    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2469        if self.remaining == 0 {
2470            return Ok(None);
2471        }
2472
2473        let next = self.it.next();
2474        if let Ok(Some(_)) = next {
2475            self.remaining -= 1;
2476        }
2477        next
2478    }
2479
2480    #[inline]
2481    fn size_hint(&self) -> (usize, Option<usize>) {
2482        let hint = self.it.size_hint();
2483        (
2484            cmp::min(hint.0, self.remaining),
2485            hint.1.map(|n| cmp::min(n, self.remaining)),
2486        )
2487    }
2488}
2489
2490/// An iterator which yields elements based on a predicate.
2491#[derive(Clone, Debug)]
2492pub struct TakeWhile<I, P> {
2493    it: I,
2494    flag: bool,
2495    predicate: P,
2496}
2497
2498impl<I, P> FallibleIterator for TakeWhile<I, P>
2499where
2500    I: FallibleIterator,
2501    P: FnMut(&I::Item) -> Result<bool, I::Error>,
2502{
2503    type Item = I::Item;
2504    type Error = I::Error;
2505
2506    #[inline]
2507    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2508        if self.flag {
2509            Ok(None)
2510        } else {
2511            match self.it.next()? {
2512                Some(item) => {
2513                    if (self.predicate)(&item)? {
2514                        Ok(Some(item))
2515                    } else {
2516                        self.flag = true;
2517                        Ok(None)
2518                    }
2519                }
2520                None => Ok(None),
2521            }
2522        }
2523    }
2524
2525    #[inline]
2526    fn size_hint(&self) -> (usize, Option<usize>) {
2527        if self.flag {
2528            (0, Some(0))
2529        } else {
2530            let hint = self.it.size_hint();
2531            (0, hint.1)
2532        }
2533    }
2534}
2535
2536/// An iterator which cycles another endlessly.
2537#[derive(Clone, Debug)]
2538pub struct Cycle<I> {
2539    it: I,
2540    cur: I,
2541}
2542
2543impl<I> FallibleIterator for Cycle<I>
2544where
2545    I: FallibleIterator + Clone,
2546{
2547    type Item = I::Item;
2548    type Error = I::Error;
2549
2550    #[inline]
2551    fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
2552        match self.cur.next()? {
2553            None => {
2554                self.cur = self.it.clone();
2555                self.cur.next()
2556            }
2557            Some(v) => Ok(Some(v)),
2558        }
2559    }
2560
2561    #[inline]
2562    fn size_hint(&self) -> (usize, Option<usize>) {
2563        (usize::max_value(), None)
2564    }
2565}
2566
2567/// An iterator that yields pairs of this iterator's and another iterator's
2568/// values.
2569#[derive(Clone, Debug)]
2570pub struct Zip<T, U>(T, U);
2571
2572impl<T, U> FallibleIterator for Zip<T, U>
2573where
2574    T: FallibleIterator,
2575    U: FallibleIterator<Error = T::Error>,
2576{
2577    type Item = (T::Item, U::Item);
2578    type Error = T::Error;
2579
2580    #[inline]
2581    fn next(&mut self) -> Result<Option<(T::Item, U::Item)>, T::Error> {
2582        match (self.0.next()?, self.1.next()?) {
2583            (Some(a), Some(b)) => Ok(Some((a, b))),
2584            _ => Ok(None),
2585        }
2586    }
2587
2588    #[inline]
2589    fn size_hint(&self) -> (usize, Option<usize>) {
2590        let a = self.0.size_hint();
2591        let b = self.1.size_hint();
2592
2593        let low = cmp::min(a.0, b.0);
2594
2595        let high = match (a.1, b.1) {
2596            (Some(a), Some(b)) => Some(cmp::min(a, b)),
2597            (Some(a), None) => Some(a),
2598            (None, Some(b)) => Some(b),
2599            (None, None) => None,
2600        };
2601
2602        (low, high)
2603    }
2604}
2605
2606fn _is_object_safe(_: &dyn DoubleEndedFallibleIterator<Item = (), Error = ()>) {}