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