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