]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/traits/iterator.rs
Rollup merge of #73715 - MaulingMonkey:pr-natvis-tuples, r=Amanieu
[rust.git] / src / libcore / iter / traits / iterator.rs
1 // ignore-tidy-filelength
2 // This file almost exclusively consists of the definition of `Iterator`. We
3 // can't split that into multiple files.
4
5 use crate::cmp::{self, Ordering};
6 use crate::ops::{Add, Try};
7
8 use super::super::LoopState;
9 use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
10 use super::super::{FlatMap, Flatten};
11 use super::super::{FromIterator, Product, Sum, Zip};
12 use super::super::{
13     Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
14 };
15
16 fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {}
17
18 /// An interface for dealing with iterators.
19 ///
20 /// This is the main iterator trait. For more about the concept of iterators
21 /// generally, please see the [module-level documentation]. In particular, you
22 /// may want to know how to [implement `Iterator`][impl].
23 ///
24 /// [module-level documentation]: index.html
25 /// [impl]: index.html#implementing-iterator
26 #[stable(feature = "rust1", since = "1.0.0")]
27 #[rustc_on_unimplemented(
28     on(
29         _Self = "[std::ops::Range<Idx>; 1]",
30         label = "if you meant to iterate between two values, remove the square brackets",
31         note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
32                 without the brackets: `start..end`"
33     ),
34     on(
35         _Self = "[std::ops::RangeFrom<Idx>; 1]",
36         label = "if you meant to iterate from a value onwards, remove the square brackets",
37         note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
38               `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
39               unbounded iterator will run forever unless you `break` or `return` from within the \
40               loop"
41     ),
42     on(
43         _Self = "[std::ops::RangeTo<Idx>; 1]",
44         label = "if you meant to iterate until a value, remove the square brackets and add a \
45                  starting value",
46         note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
47                 `Range` without the brackets: `0..end`"
48     ),
49     on(
50         _Self = "[std::ops::RangeInclusive<Idx>; 1]",
51         label = "if you meant to iterate between two values, remove the square brackets",
52         note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
53               `RangeInclusive` without the brackets: `start..=end`"
54     ),
55     on(
56         _Self = "[std::ops::RangeToInclusive<Idx>; 1]",
57         label = "if you meant to iterate until a value (including it), remove the square brackets \
58                  and add a starting value",
59         note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
60                 bounded `RangeInclusive` without the brackets: `0..=end`"
61     ),
62     on(
63         _Self = "std::ops::RangeTo<Idx>",
64         label = "if you meant to iterate until a value, add a starting value",
65         note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
66               bounded `Range`: `0..end`"
67     ),
68     on(
69         _Self = "std::ops::RangeToInclusive<Idx>",
70         label = "if you meant to iterate until a value (including it), add a starting value",
71         note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
72               to have a bounded `RangeInclusive`: `0..=end`"
73     ),
74     on(
75         _Self = "&str",
76         label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
77     ),
78     on(
79         _Self = "std::string::String",
80         label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
81     ),
82     on(
83         _Self = "[]",
84         label = "borrow the array with `&` or call `.iter()` on it to iterate over it",
85         note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
86     ),
87     on(
88         _Self = "{integral}",
89         note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
90               syntax `start..end` or the inclusive range syntax `start..=end`"
91     ),
92     label = "`{Self}` is not an iterator",
93     message = "`{Self}` is not an iterator"
94 )]
95 #[must_use = "iterators are lazy and do nothing unless consumed"]
96 pub trait Iterator {
97     /// The type of the elements being iterated over.
98     #[stable(feature = "rust1", since = "1.0.0")]
99     type Item;
100
101     /// Advances the iterator and returns the next value.
102     ///
103     /// Returns [`None`] when iteration is finished. Individual iterator
104     /// implementations may choose to resume iteration, and so calling `next()`
105     /// again may or may not eventually start returning [`Some(Item)`] again at some
106     /// point.
107     ///
108     /// [`None`]: ../../std/option/enum.Option.html#variant.None
109     /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
110     ///
111     /// # Examples
112     ///
113     /// Basic usage:
114     ///
115     /// ```
116     /// let a = [1, 2, 3];
117     ///
118     /// let mut iter = a.iter();
119     ///
120     /// // A call to next() returns the next value...
121     /// assert_eq!(Some(&1), iter.next());
122     /// assert_eq!(Some(&2), iter.next());
123     /// assert_eq!(Some(&3), iter.next());
124     ///
125     /// // ... and then None once it's over.
126     /// assert_eq!(None, iter.next());
127     ///
128     /// // More calls may or may not return `None`. Here, they always will.
129     /// assert_eq!(None, iter.next());
130     /// assert_eq!(None, iter.next());
131     /// ```
132     #[stable(feature = "rust1", since = "1.0.0")]
133     fn next(&mut self) -> Option<Self::Item>;
134
135     /// Returns the bounds on the remaining length of the iterator.
136     ///
137     /// Specifically, `size_hint()` returns a tuple where the first element
138     /// is the lower bound, and the second element is the upper bound.
139     ///
140     /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
141     /// A [`None`] here means that either there is no known upper bound, or the
142     /// upper bound is larger than [`usize`].
143     ///
144     /// # Implementation notes
145     ///
146     /// It is not enforced that an iterator implementation yields the declared
147     /// number of elements. A buggy iterator may yield less than the lower bound
148     /// or more than the upper bound of elements.
149     ///
150     /// `size_hint()` is primarily intended to be used for optimizations such as
151     /// reserving space for the elements of the iterator, but must not be
152     /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
153     /// implementation of `size_hint()` should not lead to memory safety
154     /// violations.
155     ///
156     /// That said, the implementation should provide a correct estimation,
157     /// because otherwise it would be a violation of the trait's protocol.
158     ///
159     /// The default implementation returns `(0, `[`None`]`)` which is correct for any
160     /// iterator.
161     ///
162     /// [`usize`]: ../../std/primitive.usize.html
163     /// [`Option`]: ../../std/option/enum.Option.html
164     /// [`None`]: ../../std/option/enum.Option.html#variant.None
165     ///
166     /// # Examples
167     ///
168     /// Basic usage:
169     ///
170     /// ```
171     /// let a = [1, 2, 3];
172     /// let iter = a.iter();
173     ///
174     /// assert_eq!((3, Some(3)), iter.size_hint());
175     /// ```
176     ///
177     /// A more complex example:
178     ///
179     /// ```
180     /// // The even numbers from zero to ten.
181     /// let iter = (0..10).filter(|x| x % 2 == 0);
182     ///
183     /// // We might iterate from zero to ten times. Knowing that it's five
184     /// // exactly wouldn't be possible without executing filter().
185     /// assert_eq!((0, Some(10)), iter.size_hint());
186     ///
187     /// // Let's add five more numbers with chain()
188     /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
189     ///
190     /// // now both bounds are increased by five
191     /// assert_eq!((5, Some(15)), iter.size_hint());
192     /// ```
193     ///
194     /// Returning `None` for an upper bound:
195     ///
196     /// ```
197     /// // an infinite iterator has no upper bound
198     /// // and the maximum possible lower bound
199     /// let iter = 0..;
200     ///
201     /// assert_eq!((usize::MAX, None), iter.size_hint());
202     /// ```
203     #[inline]
204     #[stable(feature = "rust1", since = "1.0.0")]
205     fn size_hint(&self) -> (usize, Option<usize>) {
206         (0, None)
207     }
208
209     /// Consumes the iterator, counting the number of iterations and returning it.
210     ///
211     /// This method will call [`next`] repeatedly until [`None`] is encountered,
212     /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
213     /// called at least once even if the iterator does not have any elements.
214     ///
215     /// [`next`]: #tymethod.next
216     /// [`None`]: ../../std/option/enum.Option.html#variant.None
217     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
218     ///
219     /// # Overflow Behavior
220     ///
221     /// The method does no guarding against overflows, so counting elements of
222     /// an iterator with more than [`usize::MAX`] elements either produces the
223     /// wrong result or panics. If debug assertions are enabled, a panic is
224     /// guaranteed.
225     ///
226     /// # Panics
227     ///
228     /// This function might panic if the iterator has more than [`usize::MAX`]
229     /// elements.
230     ///
231     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
232     ///
233     /// # Examples
234     ///
235     /// Basic usage:
236     ///
237     /// ```
238     /// let a = [1, 2, 3];
239     /// assert_eq!(a.iter().count(), 3);
240     ///
241     /// let a = [1, 2, 3, 4, 5];
242     /// assert_eq!(a.iter().count(), 5);
243     /// ```
244     #[inline]
245     #[stable(feature = "rust1", since = "1.0.0")]
246     fn count(self) -> usize
247     where
248         Self: Sized,
249     {
250         #[inline]
251         fn add1<T>(count: usize, _: T) -> usize {
252             // Might overflow.
253             Add::add(count, 1)
254         }
255
256         self.fold(0, add1)
257     }
258
259     /// Consumes the iterator, returning the last element.
260     ///
261     /// This method will evaluate the iterator until it returns [`None`]. While
262     /// doing so, it keeps track of the current element. After [`None`] is
263     /// returned, `last()` will then return the last element it saw.
264     ///
265     /// [`None`]: ../../std/option/enum.Option.html#variant.None
266     ///
267     /// # Examples
268     ///
269     /// Basic usage:
270     ///
271     /// ```
272     /// let a = [1, 2, 3];
273     /// assert_eq!(a.iter().last(), Some(&3));
274     ///
275     /// let a = [1, 2, 3, 4, 5];
276     /// assert_eq!(a.iter().last(), Some(&5));
277     /// ```
278     #[inline]
279     #[stable(feature = "rust1", since = "1.0.0")]
280     fn last(self) -> Option<Self::Item>
281     where
282         Self: Sized,
283     {
284         #[inline]
285         fn some<T>(_: Option<T>, x: T) -> Option<T> {
286             Some(x)
287         }
288
289         self.fold(None, some)
290     }
291
292     /// Returns the `n`th element of the iterator.
293     ///
294     /// Like most indexing operations, the count starts from zero, so `nth(0)`
295     /// returns the first value, `nth(1)` the second, and so on.
296     ///
297     /// Note that all preceding elements, as well as the returned element, will be
298     /// consumed from the iterator. That means that the preceding elements will be
299     /// discarded, and also that calling `nth(0)` multiple times on the same iterator
300     /// will return different elements.
301     ///
302     /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
303     /// iterator.
304     ///
305     /// [`None`]: ../../std/option/enum.Option.html#variant.None
306     ///
307     /// # Examples
308     ///
309     /// Basic usage:
310     ///
311     /// ```
312     /// let a = [1, 2, 3];
313     /// assert_eq!(a.iter().nth(1), Some(&2));
314     /// ```
315     ///
316     /// Calling `nth()` multiple times doesn't rewind the iterator:
317     ///
318     /// ```
319     /// let a = [1, 2, 3];
320     ///
321     /// let mut iter = a.iter();
322     ///
323     /// assert_eq!(iter.nth(1), Some(&2));
324     /// assert_eq!(iter.nth(1), None);
325     /// ```
326     ///
327     /// Returning `None` if there are less than `n + 1` elements:
328     ///
329     /// ```
330     /// let a = [1, 2, 3];
331     /// assert_eq!(a.iter().nth(10), None);
332     /// ```
333     #[inline]
334     #[stable(feature = "rust1", since = "1.0.0")]
335     fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
336         while let Some(x) = self.next() {
337             if n == 0 {
338                 return Some(x);
339             }
340             n -= 1;
341         }
342         None
343     }
344
345     /// Creates an iterator starting at the same point, but stepping by
346     /// the given amount at each iteration.
347     ///
348     /// Note 1: The first element of the iterator will always be returned,
349     /// regardless of the step given.
350     ///
351     /// Note 2: The time at which ignored elements are pulled is not fixed.
352     /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), â€¦`,
353     /// but is also free to behave like the sequence
354     /// `advance_n_and_return_first(step), advance_n_and_return_first(step), â€¦`
355     /// Which way is used may change for some iterators for performance reasons.
356     /// The second way will advance the iterator earlier and may consume more items.
357     ///
358     /// `advance_n_and_return_first` is the equivalent of:
359     /// ```
360     /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
361     /// where
362     ///     I: Iterator,
363     /// {
364     ///     let next = iter.next();
365     ///     if total_step > 1 {
366     ///         iter.nth(total_step-2);
367     ///     }
368     ///     next
369     /// }
370     /// ```
371     ///
372     /// # Panics
373     ///
374     /// The method will panic if the given step is `0`.
375     ///
376     /// # Examples
377     ///
378     /// Basic usage:
379     ///
380     /// ```
381     /// let a = [0, 1, 2, 3, 4, 5];
382     /// let mut iter = a.iter().step_by(2);
383     ///
384     /// assert_eq!(iter.next(), Some(&0));
385     /// assert_eq!(iter.next(), Some(&2));
386     /// assert_eq!(iter.next(), Some(&4));
387     /// assert_eq!(iter.next(), None);
388     /// ```
389     #[inline]
390     #[stable(feature = "iterator_step_by", since = "1.28.0")]
391     fn step_by(self, step: usize) -> StepBy<Self>
392     where
393         Self: Sized,
394     {
395         StepBy::new(self, step)
396     }
397
398     /// Takes two iterators and creates a new iterator over both in sequence.
399     ///
400     /// `chain()` will return a new iterator which will first iterate over
401     /// values from the first iterator and then over values from the second
402     /// iterator.
403     ///
404     /// In other words, it links two iterators together, in a chain. ðŸ”—
405     ///
406     /// [`once`] is commonly used to adapt a single value into a chain of
407     /// other kinds of iteration.
408     ///
409     /// # Examples
410     ///
411     /// Basic usage:
412     ///
413     /// ```
414     /// let a1 = [1, 2, 3];
415     /// let a2 = [4, 5, 6];
416     ///
417     /// let mut iter = a1.iter().chain(a2.iter());
418     ///
419     /// assert_eq!(iter.next(), Some(&1));
420     /// assert_eq!(iter.next(), Some(&2));
421     /// assert_eq!(iter.next(), Some(&3));
422     /// assert_eq!(iter.next(), Some(&4));
423     /// assert_eq!(iter.next(), Some(&5));
424     /// assert_eq!(iter.next(), Some(&6));
425     /// assert_eq!(iter.next(), None);
426     /// ```
427     ///
428     /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
429     /// anything that can be converted into an [`Iterator`], not just an
430     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
431     /// [`IntoIterator`], and so can be passed to `chain()` directly:
432     ///
433     /// ```
434     /// let s1 = &[1, 2, 3];
435     /// let s2 = &[4, 5, 6];
436     ///
437     /// let mut iter = s1.iter().chain(s2);
438     ///
439     /// assert_eq!(iter.next(), Some(&1));
440     /// assert_eq!(iter.next(), Some(&2));
441     /// assert_eq!(iter.next(), Some(&3));
442     /// assert_eq!(iter.next(), Some(&4));
443     /// assert_eq!(iter.next(), Some(&5));
444     /// assert_eq!(iter.next(), Some(&6));
445     /// assert_eq!(iter.next(), None);
446     /// ```
447     ///
448     /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
449     ///
450     /// ```
451     /// #[cfg(windows)]
452     /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
453     ///     use std::os::windows::ffi::OsStrExt;
454     ///     s.encode_wide().chain(std::iter::once(0)).collect()
455     /// }
456     /// ```
457     ///
458     /// [`once`]: fn.once.html
459     /// [`Iterator`]: trait.Iterator.html
460     /// [`IntoIterator`]: trait.IntoIterator.html
461     /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
462     #[inline]
463     #[stable(feature = "rust1", since = "1.0.0")]
464     fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
465     where
466         Self: Sized,
467         U: IntoIterator<Item = Self::Item>,
468     {
469         Chain::new(self, other.into_iter())
470     }
471
472     /// 'Zips up' two iterators into a single iterator of pairs.
473     ///
474     /// `zip()` returns a new iterator that will iterate over two other
475     /// iterators, returning a tuple where the first element comes from the
476     /// first iterator, and the second element comes from the second iterator.
477     ///
478     /// In other words, it zips two iterators together, into a single one.
479     ///
480     /// If either iterator returns [`None`], [`next`] from the zipped iterator
481     /// will return [`None`]. If the first iterator returns [`None`], `zip` will
482     /// short-circuit and `next` will not be called on the second iterator.
483     ///
484     /// # Examples
485     ///
486     /// Basic usage:
487     ///
488     /// ```
489     /// let a1 = [1, 2, 3];
490     /// let a2 = [4, 5, 6];
491     ///
492     /// let mut iter = a1.iter().zip(a2.iter());
493     ///
494     /// assert_eq!(iter.next(), Some((&1, &4)));
495     /// assert_eq!(iter.next(), Some((&2, &5)));
496     /// assert_eq!(iter.next(), Some((&3, &6)));
497     /// assert_eq!(iter.next(), None);
498     /// ```
499     ///
500     /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
501     /// anything that can be converted into an [`Iterator`], not just an
502     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
503     /// [`IntoIterator`], and so can be passed to `zip()` directly:
504     ///
505     /// [`IntoIterator`]: trait.IntoIterator.html
506     /// [`Iterator`]: trait.Iterator.html
507     ///
508     /// ```
509     /// let s1 = &[1, 2, 3];
510     /// let s2 = &[4, 5, 6];
511     ///
512     /// let mut iter = s1.iter().zip(s2);
513     ///
514     /// assert_eq!(iter.next(), Some((&1, &4)));
515     /// assert_eq!(iter.next(), Some((&2, &5)));
516     /// assert_eq!(iter.next(), Some((&3, &6)));
517     /// assert_eq!(iter.next(), None);
518     /// ```
519     ///
520     /// `zip()` is often used to zip an infinite iterator to a finite one.
521     /// This works because the finite iterator will eventually return [`None`],
522     /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
523     ///
524     /// ```
525     /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
526     ///
527     /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
528     ///
529     /// assert_eq!((0, 'f'), enumerate[0]);
530     /// assert_eq!((0, 'f'), zipper[0]);
531     ///
532     /// assert_eq!((1, 'o'), enumerate[1]);
533     /// assert_eq!((1, 'o'), zipper[1]);
534     ///
535     /// assert_eq!((2, 'o'), enumerate[2]);
536     /// assert_eq!((2, 'o'), zipper[2]);
537     /// ```
538     ///
539     /// [`enumerate`]: trait.Iterator.html#method.enumerate
540     /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
541     /// [`None`]: ../../std/option/enum.Option.html#variant.None
542     #[inline]
543     #[stable(feature = "rust1", since = "1.0.0")]
544     fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
545     where
546         Self: Sized,
547         U: IntoIterator,
548     {
549         Zip::new(self, other.into_iter())
550     }
551
552     /// Takes a closure and creates an iterator which calls that closure on each
553     /// element.
554     ///
555     /// `map()` transforms one iterator into another, by means of its argument:
556     /// something that implements [`FnMut`]. It produces a new iterator which
557     /// calls this closure on each element of the original iterator.
558     ///
559     /// If you are good at thinking in types, you can think of `map()` like this:
560     /// If you have an iterator that gives you elements of some type `A`, and
561     /// you want an iterator of some other type `B`, you can use `map()`,
562     /// passing a closure that takes an `A` and returns a `B`.
563     ///
564     /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
565     /// lazy, it is best used when you're already working with other iterators.
566     /// If you're doing some sort of looping for a side effect, it's considered
567     /// more idiomatic to use [`for`] than `map()`.
568     ///
569     /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
570     /// [`FnMut`]: ../../std/ops/trait.FnMut.html
571     ///
572     /// # Examples
573     ///
574     /// Basic usage:
575     ///
576     /// ```
577     /// let a = [1, 2, 3];
578     ///
579     /// let mut iter = a.iter().map(|x| 2 * x);
580     ///
581     /// assert_eq!(iter.next(), Some(2));
582     /// assert_eq!(iter.next(), Some(4));
583     /// assert_eq!(iter.next(), Some(6));
584     /// assert_eq!(iter.next(), None);
585     /// ```
586     ///
587     /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
588     ///
589     /// ```
590     /// # #![allow(unused_must_use)]
591     /// // don't do this:
592     /// (0..5).map(|x| println!("{}", x));
593     ///
594     /// // it won't even execute, as it is lazy. Rust will warn you about this.
595     ///
596     /// // Instead, use for:
597     /// for x in 0..5 {
598     ///     println!("{}", x);
599     /// }
600     /// ```
601     #[inline]
602     #[stable(feature = "rust1", since = "1.0.0")]
603     fn map<B, F>(self, f: F) -> Map<Self, F>
604     where
605         Self: Sized,
606         F: FnMut(Self::Item) -> B,
607     {
608         Map::new(self, f)
609     }
610
611     /// Calls a closure on each element of an iterator.
612     ///
613     /// This is equivalent to using a [`for`] loop on the iterator, although
614     /// `break` and `continue` are not possible from a closure. It's generally
615     /// more idiomatic to use a `for` loop, but `for_each` may be more legible
616     /// when processing items at the end of longer iterator chains. In some
617     /// cases `for_each` may also be faster than a loop, because it will use
618     /// internal iteration on adaptors like `Chain`.
619     ///
620     /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
621     ///
622     /// # Examples
623     ///
624     /// Basic usage:
625     ///
626     /// ```
627     /// use std::sync::mpsc::channel;
628     ///
629     /// let (tx, rx) = channel();
630     /// (0..5).map(|x| x * 2 + 1)
631     ///       .for_each(move |x| tx.send(x).unwrap());
632     ///
633     /// let v: Vec<_> =  rx.iter().collect();
634     /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
635     /// ```
636     ///
637     /// For such a small example, a `for` loop may be cleaner, but `for_each`
638     /// might be preferable to keep a functional style with longer iterators:
639     ///
640     /// ```
641     /// (0..5).flat_map(|x| x * 100 .. x * 110)
642     ///       .enumerate()
643     ///       .filter(|&(i, x)| (i + x) % 3 == 0)
644     ///       .for_each(|(i, x)| println!("{}:{}", i, x));
645     /// ```
646     #[inline]
647     #[stable(feature = "iterator_for_each", since = "1.21.0")]
648     fn for_each<F>(self, f: F)
649     where
650         Self: Sized,
651         F: FnMut(Self::Item),
652     {
653         #[inline]
654         fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
655             move |(), item| f(item)
656         }
657
658         self.fold((), call(f));
659     }
660
661     /// Creates an iterator which uses a closure to determine if an element
662     /// should be yielded.
663     ///
664     /// The closure must return `true` or `false`. `filter()` creates an
665     /// iterator which calls this closure on each element. If the closure
666     /// returns `true`, then the element is returned. If the closure returns
667     /// `false`, it will try again, and call the closure on the next element,
668     /// seeing if it passes the test.
669     ///
670     /// # Examples
671     ///
672     /// Basic usage:
673     ///
674     /// ```
675     /// let a = [0i32, 1, 2];
676     ///
677     /// let mut iter = a.iter().filter(|x| x.is_positive());
678     ///
679     /// assert_eq!(iter.next(), Some(&1));
680     /// assert_eq!(iter.next(), Some(&2));
681     /// assert_eq!(iter.next(), None);
682     /// ```
683     ///
684     /// Because the closure passed to `filter()` takes a reference, and many
685     /// iterators iterate over references, this leads to a possibly confusing
686     /// situation, where the type of the closure is a double reference:
687     ///
688     /// ```
689     /// let a = [0, 1, 2];
690     ///
691     /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s!
692     ///
693     /// assert_eq!(iter.next(), Some(&2));
694     /// assert_eq!(iter.next(), None);
695     /// ```
696     ///
697     /// It's common to instead use destructuring on the argument to strip away
698     /// one:
699     ///
700     /// ```
701     /// let a = [0, 1, 2];
702     ///
703     /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and *
704     ///
705     /// assert_eq!(iter.next(), Some(&2));
706     /// assert_eq!(iter.next(), None);
707     /// ```
708     ///
709     /// or both:
710     ///
711     /// ```
712     /// let a = [0, 1, 2];
713     ///
714     /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s
715     ///
716     /// assert_eq!(iter.next(), Some(&2));
717     /// assert_eq!(iter.next(), None);
718     /// ```
719     ///
720     /// of these layers.
721     ///
722     /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
723     #[inline]
724     #[stable(feature = "rust1", since = "1.0.0")]
725     fn filter<P>(self, predicate: P) -> Filter<Self, P>
726     where
727         Self: Sized,
728         P: FnMut(&Self::Item) -> bool,
729     {
730         Filter::new(self, predicate)
731     }
732
733     /// Creates an iterator that both filters and maps.
734     ///
735     /// The closure must return an [`Option<T>`]. `filter_map` creates an
736     /// iterator which calls this closure on each element. If the closure
737     /// returns [`Some(element)`][`Some`], then that element is returned. If the
738     /// closure returns [`None`], it will try again, and call the closure on the
739     /// next element, seeing if it will return [`Some`].
740     ///
741     /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
742     /// part:
743     ///
744     /// [`filter`]: #method.filter
745     /// [`map`]: #method.map
746     ///
747     /// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
748     ///
749     /// In other words, it removes the [`Option<T>`] layer automatically. If your
750     /// mapping is already returning an [`Option<T>`] and you want to skip over
751     /// [`None`]s, then `filter_map` is much, much nicer to use.
752     ///
753     /// # Examples
754     ///
755     /// Basic usage:
756     ///
757     /// ```
758     /// let a = ["1", "lol", "3", "NaN", "5"];
759     ///
760     /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
761     ///
762     /// assert_eq!(iter.next(), Some(1));
763     /// assert_eq!(iter.next(), Some(3));
764     /// assert_eq!(iter.next(), Some(5));
765     /// assert_eq!(iter.next(), None);
766     /// ```
767     ///
768     /// Here's the same example, but with [`filter`] and [`map`]:
769     ///
770     /// ```
771     /// let a = ["1", "lol", "3", "NaN", "5"];
772     /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
773     /// assert_eq!(iter.next(), Some(1));
774     /// assert_eq!(iter.next(), Some(3));
775     /// assert_eq!(iter.next(), Some(5));
776     /// assert_eq!(iter.next(), None);
777     /// ```
778     ///
779     /// [`Option<T>`]: ../../std/option/enum.Option.html
780     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
781     /// [`None`]: ../../std/option/enum.Option.html#variant.None
782     #[inline]
783     #[stable(feature = "rust1", since = "1.0.0")]
784     fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
785     where
786         Self: Sized,
787         F: FnMut(Self::Item) -> Option<B>,
788     {
789         FilterMap::new(self, f)
790     }
791
792     /// Creates an iterator which gives the current iteration count as well as
793     /// the next value.
794     ///
795     /// The iterator returned yields pairs `(i, val)`, where `i` is the
796     /// current index of iteration and `val` is the value returned by the
797     /// iterator.
798     ///
799     /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
800     /// different sized integer, the [`zip`] function provides similar
801     /// functionality.
802     ///
803     /// # Overflow Behavior
804     ///
805     /// The method does no guarding against overflows, so enumerating more than
806     /// [`usize::MAX`] elements either produces the wrong result or panics. If
807     /// debug assertions are enabled, a panic is guaranteed.
808     ///
809     /// # Panics
810     ///
811     /// The returned iterator might panic if the to-be-returned index would
812     /// overflow a [`usize`].
813     ///
814     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
815     /// [`usize`]: ../../std/primitive.usize.html
816     /// [`zip`]: #method.zip
817     ///
818     /// # Examples
819     ///
820     /// ```
821     /// let a = ['a', 'b', 'c'];
822     ///
823     /// let mut iter = a.iter().enumerate();
824     ///
825     /// assert_eq!(iter.next(), Some((0, &'a')));
826     /// assert_eq!(iter.next(), Some((1, &'b')));
827     /// assert_eq!(iter.next(), Some((2, &'c')));
828     /// assert_eq!(iter.next(), None);
829     /// ```
830     #[inline]
831     #[stable(feature = "rust1", since = "1.0.0")]
832     fn enumerate(self) -> Enumerate<Self>
833     where
834         Self: Sized,
835     {
836         Enumerate::new(self)
837     }
838
839     /// Creates an iterator which can use `peek` to look at the next element of
840     /// the iterator without consuming it.
841     ///
842     /// Adds a [`peek`] method to an iterator. See its documentation for
843     /// more information.
844     ///
845     /// Note that the underlying iterator is still advanced when [`peek`] is
846     /// called for the first time: In order to retrieve the next element,
847     /// [`next`] is called on the underlying iterator, hence any side effects (i.e.
848     /// anything other than fetching the next value) of the [`next`] method
849     /// will occur.
850     ///
851     /// [`peek`]: struct.Peekable.html#method.peek
852     /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
853     ///
854     /// # Examples
855     ///
856     /// Basic usage:
857     ///
858     /// ```
859     /// let xs = [1, 2, 3];
860     ///
861     /// let mut iter = xs.iter().peekable();
862     ///
863     /// // peek() lets us see into the future
864     /// assert_eq!(iter.peek(), Some(&&1));
865     /// assert_eq!(iter.next(), Some(&1));
866     ///
867     /// assert_eq!(iter.next(), Some(&2));
868     ///
869     /// // we can peek() multiple times, the iterator won't advance
870     /// assert_eq!(iter.peek(), Some(&&3));
871     /// assert_eq!(iter.peek(), Some(&&3));
872     ///
873     /// assert_eq!(iter.next(), Some(&3));
874     ///
875     /// // after the iterator is finished, so is peek()
876     /// assert_eq!(iter.peek(), None);
877     /// assert_eq!(iter.next(), None);
878     /// ```
879     #[inline]
880     #[stable(feature = "rust1", since = "1.0.0")]
881     fn peekable(self) -> Peekable<Self>
882     where
883         Self: Sized,
884     {
885         Peekable::new(self)
886     }
887
888     /// Creates an iterator that [`skip`]s elements based on a predicate.
889     ///
890     /// [`skip`]: #method.skip
891     ///
892     /// `skip_while()` takes a closure as an argument. It will call this
893     /// closure on each element of the iterator, and ignore elements
894     /// until it returns `false`.
895     ///
896     /// After `false` is returned, `skip_while()`'s job is over, and the
897     /// rest of the elements are yielded.
898     ///
899     /// # Examples
900     ///
901     /// Basic usage:
902     ///
903     /// ```
904     /// let a = [-1i32, 0, 1];
905     ///
906     /// let mut iter = a.iter().skip_while(|x| x.is_negative());
907     ///
908     /// assert_eq!(iter.next(), Some(&0));
909     /// assert_eq!(iter.next(), Some(&1));
910     /// assert_eq!(iter.next(), None);
911     /// ```
912     ///
913     /// Because the closure passed to `skip_while()` takes a reference, and many
914     /// iterators iterate over references, this leads to a possibly confusing
915     /// situation, where the type of the closure is a double reference:
916     ///
917     /// ```
918     /// let a = [-1, 0, 1];
919     ///
920     /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s!
921     ///
922     /// assert_eq!(iter.next(), Some(&0));
923     /// assert_eq!(iter.next(), Some(&1));
924     /// assert_eq!(iter.next(), None);
925     /// ```
926     ///
927     /// Stopping after an initial `false`:
928     ///
929     /// ```
930     /// let a = [-1, 0, 1, -2];
931     ///
932     /// let mut iter = a.iter().skip_while(|x| **x < 0);
933     ///
934     /// assert_eq!(iter.next(), Some(&0));
935     /// assert_eq!(iter.next(), Some(&1));
936     ///
937     /// // while this would have been false, since we already got a false,
938     /// // skip_while() isn't used any more
939     /// assert_eq!(iter.next(), Some(&-2));
940     ///
941     /// assert_eq!(iter.next(), None);
942     /// ```
943     #[inline]
944     #[stable(feature = "rust1", since = "1.0.0")]
945     fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
946     where
947         Self: Sized,
948         P: FnMut(&Self::Item) -> bool,
949     {
950         SkipWhile::new(self, predicate)
951     }
952
953     /// Creates an iterator that yields elements based on a predicate.
954     ///
955     /// `take_while()` takes a closure as an argument. It will call this
956     /// closure on each element of the iterator, and yield elements
957     /// while it returns `true`.
958     ///
959     /// After `false` is returned, `take_while()`'s job is over, and the
960     /// rest of the elements are ignored.
961     ///
962     /// # Examples
963     ///
964     /// Basic usage:
965     ///
966     /// ```
967     /// let a = [-1i32, 0, 1];
968     ///
969     /// let mut iter = a.iter().take_while(|x| x.is_negative());
970     ///
971     /// assert_eq!(iter.next(), Some(&-1));
972     /// assert_eq!(iter.next(), None);
973     /// ```
974     ///
975     /// Because the closure passed to `take_while()` takes a reference, and many
976     /// iterators iterate over references, this leads to a possibly confusing
977     /// situation, where the type of the closure is a double reference:
978     ///
979     /// ```
980     /// let a = [-1, 0, 1];
981     ///
982     /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s!
983     ///
984     /// assert_eq!(iter.next(), Some(&-1));
985     /// assert_eq!(iter.next(), None);
986     /// ```
987     ///
988     /// Stopping after an initial `false`:
989     ///
990     /// ```
991     /// let a = [-1, 0, 1, -2];
992     ///
993     /// let mut iter = a.iter().take_while(|x| **x < 0);
994     ///
995     /// assert_eq!(iter.next(), Some(&-1));
996     ///
997     /// // We have more elements that are less than zero, but since we already
998     /// // got a false, take_while() isn't used any more
999     /// assert_eq!(iter.next(), None);
1000     /// ```
1001     ///
1002     /// Because `take_while()` needs to look at the value in order to see if it
1003     /// should be included or not, consuming iterators will see that it is
1004     /// removed:
1005     ///
1006     /// ```
1007     /// let a = [1, 2, 3, 4];
1008     /// let mut iter = a.iter();
1009     ///
1010     /// let result: Vec<i32> = iter.by_ref()
1011     ///                            .take_while(|n| **n != 3)
1012     ///                            .cloned()
1013     ///                            .collect();
1014     ///
1015     /// assert_eq!(result, &[1, 2]);
1016     ///
1017     /// let result: Vec<i32> = iter.cloned().collect();
1018     ///
1019     /// assert_eq!(result, &[4]);
1020     /// ```
1021     ///
1022     /// The `3` is no longer there, because it was consumed in order to see if
1023     /// the iteration should stop, but wasn't placed back into the iterator.
1024     #[inline]
1025     #[stable(feature = "rust1", since = "1.0.0")]
1026     fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1027     where
1028         Self: Sized,
1029         P: FnMut(&Self::Item) -> bool,
1030     {
1031         TakeWhile::new(self, predicate)
1032     }
1033
1034     /// Creates an iterator that both yields elements based on a predicate and maps.
1035     ///
1036     /// `map_while()` takes a closure as an argument. It will call this
1037     /// closure on each element of the iterator, and yield elements
1038     /// while it returns [`Some(_)`][`Some`].
1039     ///
1040     /// # Examples
1041     ///
1042     /// Basic usage:
1043     ///
1044     /// ```
1045     /// #![feature(iter_map_while)]
1046     /// let a = [-1i32, 4, 0, 1];
1047     ///
1048     /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x));
1049     ///
1050     /// assert_eq!(iter.next(), Some(-16));
1051     /// assert_eq!(iter.next(), Some(4));
1052     /// assert_eq!(iter.next(), None);
1053     /// ```
1054     ///
1055     /// Here's the same example, but with [`take_while`] and [`map`]:
1056     ///
1057     /// [`take_while`]: #method.take_while
1058     /// [`map`]: #method.map
1059     ///
1060     /// ```
1061     /// let a = [-1i32, 4, 0, 1];
1062     ///
1063     /// let mut iter = a.iter()
1064     ///                 .map(|x| 16i32.checked_div(*x))
1065     ///                 .take_while(|x| x.is_some())
1066     ///                 .map(|x| x.unwrap());
1067     ///
1068     /// assert_eq!(iter.next(), Some(-16));
1069     /// assert_eq!(iter.next(), Some(4));
1070     /// assert_eq!(iter.next(), None);
1071     /// ```
1072     ///
1073     /// Stopping after an initial [`None`]:
1074     ///
1075     /// ```
1076     /// #![feature(iter_map_while)]
1077     /// use std::convert::TryFrom;
1078     ///
1079     /// let a = [0, 1, 2, -3, 4, 5, -6];
1080     ///
1081     /// let iter = a.iter().map_while(|x| u32::try_from(*x).ok());
1082     /// let vec = iter.collect::<Vec<_>>();
1083     ///
1084     /// // We have more elements which could fit in u32 (4, 5), but `map_while` returned `None` for `-3`
1085     /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` entcountered.
1086     /// assert_eq!(vec, vec![0, 1, 2]);
1087     /// ```
1088     ///
1089     /// Because `map_while()` needs to look at the value in order to see if it
1090     /// should be included or not, consuming iterators will see that it is
1091     /// removed:
1092     ///
1093     /// ```
1094     /// #![feature(iter_map_while)]
1095     /// use std::convert::TryFrom;
1096     ///
1097     /// let a = [1, 2, -3, 4];
1098     /// let mut iter = a.iter();
1099     ///
1100     /// let result: Vec<u32> = iter.by_ref()
1101     ///                            .map_while(|n| u32::try_from(*n).ok())
1102     ///                            .collect();
1103     ///
1104     /// assert_eq!(result, &[1, 2]);
1105     ///
1106     /// let result: Vec<i32> = iter.cloned().collect();
1107     ///
1108     /// assert_eq!(result, &[4]);
1109     /// ```
1110     ///
1111     /// The `-3` is no longer there, because it was consumed in order to see if
1112     /// the iteration should stop, but wasn't placed back into the iterator.
1113     ///
1114     /// Note that unlike [`take_while`] this iterator is **not** fused.
1115     /// It is also not specified what this iterator returns after the first` None` is returned.
1116     /// If you need fused iterator, use [`fuse`].
1117     ///
1118     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
1119     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1120     /// [`fuse`]: #method.fuse
1121     #[inline]
1122     #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")]
1123     fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1124     where
1125         Self: Sized,
1126         P: FnMut(Self::Item) -> Option<B>,
1127     {
1128         MapWhile::new(self, predicate)
1129     }
1130
1131     /// Creates an iterator that skips the first `n` elements.
1132     ///
1133     /// After they have been consumed, the rest of the elements are yielded.
1134     /// Rather than overriding this method directly, instead override the `nth` method.
1135     ///
1136     /// # Examples
1137     ///
1138     /// Basic usage:
1139     ///
1140     /// ```
1141     /// let a = [1, 2, 3];
1142     ///
1143     /// let mut iter = a.iter().skip(2);
1144     ///
1145     /// assert_eq!(iter.next(), Some(&3));
1146     /// assert_eq!(iter.next(), None);
1147     /// ```
1148     #[inline]
1149     #[stable(feature = "rust1", since = "1.0.0")]
1150     fn skip(self, n: usize) -> Skip<Self>
1151     where
1152         Self: Sized,
1153     {
1154         Skip::new(self, n)
1155     }
1156
1157     /// Creates an iterator that yields its first `n` elements.
1158     ///
1159     /// # Examples
1160     ///
1161     /// Basic usage:
1162     ///
1163     /// ```
1164     /// let a = [1, 2, 3];
1165     ///
1166     /// let mut iter = a.iter().take(2);
1167     ///
1168     /// assert_eq!(iter.next(), Some(&1));
1169     /// assert_eq!(iter.next(), Some(&2));
1170     /// assert_eq!(iter.next(), None);
1171     /// ```
1172     ///
1173     /// `take()` is often used with an infinite iterator, to make it finite:
1174     ///
1175     /// ```
1176     /// let mut iter = (0..).take(3);
1177     ///
1178     /// assert_eq!(iter.next(), Some(0));
1179     /// assert_eq!(iter.next(), Some(1));
1180     /// assert_eq!(iter.next(), Some(2));
1181     /// assert_eq!(iter.next(), None);
1182     /// ```
1183     ///
1184     /// If less than `n` elements are available,
1185     /// `take` will limit itself to the size of the underlying iterator:
1186     ///
1187     /// ```
1188     /// let v = vec![1, 2];
1189     /// let mut iter = v.into_iter().take(5);
1190     /// assert_eq!(iter.next(), Some(1));
1191     /// assert_eq!(iter.next(), Some(2));
1192     /// assert_eq!(iter.next(), None);
1193     /// ```
1194     #[inline]
1195     #[stable(feature = "rust1", since = "1.0.0")]
1196     fn take(self, n: usize) -> Take<Self>
1197     where
1198         Self: Sized,
1199     {
1200         Take::new(self, n)
1201     }
1202
1203     /// An iterator adaptor similar to [`fold`] that holds internal state and
1204     /// produces a new iterator.
1205     ///
1206     /// [`fold`]: #method.fold
1207     ///
1208     /// `scan()` takes two arguments: an initial value which seeds the internal
1209     /// state, and a closure with two arguments, the first being a mutable
1210     /// reference to the internal state and the second an iterator element.
1211     /// The closure can assign to the internal state to share state between
1212     /// iterations.
1213     ///
1214     /// On iteration, the closure will be applied to each element of the
1215     /// iterator and the return value from the closure, an [`Option`], is
1216     /// yielded by the iterator.
1217     ///
1218     /// [`Option`]: ../../std/option/enum.Option.html
1219     ///
1220     /// # Examples
1221     ///
1222     /// Basic usage:
1223     ///
1224     /// ```
1225     /// let a = [1, 2, 3];
1226     ///
1227     /// let mut iter = a.iter().scan(1, |state, &x| {
1228     ///     // each iteration, we'll multiply the state by the element
1229     ///     *state = *state * x;
1230     ///
1231     ///     // then, we'll yield the negation of the state
1232     ///     Some(-*state)
1233     /// });
1234     ///
1235     /// assert_eq!(iter.next(), Some(-1));
1236     /// assert_eq!(iter.next(), Some(-2));
1237     /// assert_eq!(iter.next(), Some(-6));
1238     /// assert_eq!(iter.next(), None);
1239     /// ```
1240     #[inline]
1241     #[stable(feature = "rust1", since = "1.0.0")]
1242     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1243     where
1244         Self: Sized,
1245         F: FnMut(&mut St, Self::Item) -> Option<B>,
1246     {
1247         Scan::new(self, initial_state, f)
1248     }
1249
1250     /// Creates an iterator that works like map, but flattens nested structure.
1251     ///
1252     /// The [`map`] adapter is very useful, but only when the closure
1253     /// argument produces values. If it produces an iterator instead, there's
1254     /// an extra layer of indirection. `flat_map()` will remove this extra layer
1255     /// on its own.
1256     ///
1257     /// You can think of `flat_map(f)` as the semantic equivalent
1258     /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1259     ///
1260     /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1261     /// one item for each element, and `flat_map()`'s closure returns an
1262     /// iterator for each element.
1263     ///
1264     /// [`map`]: #method.map
1265     /// [`flatten`]: #method.flatten
1266     ///
1267     /// # Examples
1268     ///
1269     /// Basic usage:
1270     ///
1271     /// ```
1272     /// let words = ["alpha", "beta", "gamma"];
1273     ///
1274     /// // chars() returns an iterator
1275     /// let merged: String = words.iter()
1276     ///                           .flat_map(|s| s.chars())
1277     ///                           .collect();
1278     /// assert_eq!(merged, "alphabetagamma");
1279     /// ```
1280     #[inline]
1281     #[stable(feature = "rust1", since = "1.0.0")]
1282     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1283     where
1284         Self: Sized,
1285         U: IntoIterator,
1286         F: FnMut(Self::Item) -> U,
1287     {
1288         FlatMap::new(self, f)
1289     }
1290
1291     /// Creates an iterator that flattens nested structure.
1292     ///
1293     /// This is useful when you have an iterator of iterators or an iterator of
1294     /// things that can be turned into iterators and you want to remove one
1295     /// level of indirection.
1296     ///
1297     /// # Examples
1298     ///
1299     /// Basic usage:
1300     ///
1301     /// ```
1302     /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1303     /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1304     /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1305     /// ```
1306     ///
1307     /// Mapping and then flattening:
1308     ///
1309     /// ```
1310     /// let words = ["alpha", "beta", "gamma"];
1311     ///
1312     /// // chars() returns an iterator
1313     /// let merged: String = words.iter()
1314     ///                           .map(|s| s.chars())
1315     ///                           .flatten()
1316     ///                           .collect();
1317     /// assert_eq!(merged, "alphabetagamma");
1318     /// ```
1319     ///
1320     /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1321     /// in this case since it conveys intent more clearly:
1322     ///
1323     /// ```
1324     /// let words = ["alpha", "beta", "gamma"];
1325     ///
1326     /// // chars() returns an iterator
1327     /// let merged: String = words.iter()
1328     ///                           .flat_map(|s| s.chars())
1329     ///                           .collect();
1330     /// assert_eq!(merged, "alphabetagamma");
1331     /// ```
1332     ///
1333     /// Flattening once only removes one level of nesting:
1334     ///
1335     /// ```
1336     /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1337     ///
1338     /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1339     /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1340     ///
1341     /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1342     /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1343     /// ```
1344     ///
1345     /// Here we see that `flatten()` does not perform a "deep" flatten.
1346     /// Instead, only one level of nesting is removed. That is, if you
1347     /// `flatten()` a three-dimensional array the result will be
1348     /// two-dimensional and not one-dimensional. To get a one-dimensional
1349     /// structure, you have to `flatten()` again.
1350     ///
1351     /// [`flat_map()`]: #method.flat_map
1352     #[inline]
1353     #[stable(feature = "iterator_flatten", since = "1.29.0")]
1354     fn flatten(self) -> Flatten<Self>
1355     where
1356         Self: Sized,
1357         Self::Item: IntoIterator,
1358     {
1359         Flatten::new(self)
1360     }
1361
1362     /// Creates an iterator which ends after the first [`None`].
1363     ///
1364     /// After an iterator returns [`None`], future calls may or may not yield
1365     /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1366     /// [`None`] is given, it will always return [`None`] forever.
1367     ///
1368     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1369     /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1370     ///
1371     /// # Examples
1372     ///
1373     /// Basic usage:
1374     ///
1375     /// ```
1376     /// // an iterator which alternates between Some and None
1377     /// struct Alternate {
1378     ///     state: i32,
1379     /// }
1380     ///
1381     /// impl Iterator for Alternate {
1382     ///     type Item = i32;
1383     ///
1384     ///     fn next(&mut self) -> Option<i32> {
1385     ///         let val = self.state;
1386     ///         self.state = self.state + 1;
1387     ///
1388     ///         // if it's even, Some(i32), else None
1389     ///         if val % 2 == 0 {
1390     ///             Some(val)
1391     ///         } else {
1392     ///             None
1393     ///         }
1394     ///     }
1395     /// }
1396     ///
1397     /// let mut iter = Alternate { state: 0 };
1398     ///
1399     /// // we can see our iterator going back and forth
1400     /// assert_eq!(iter.next(), Some(0));
1401     /// assert_eq!(iter.next(), None);
1402     /// assert_eq!(iter.next(), Some(2));
1403     /// assert_eq!(iter.next(), None);
1404     ///
1405     /// // however, once we fuse it...
1406     /// let mut iter = iter.fuse();
1407     ///
1408     /// assert_eq!(iter.next(), Some(4));
1409     /// assert_eq!(iter.next(), None);
1410     ///
1411     /// // it will always return `None` after the first time.
1412     /// assert_eq!(iter.next(), None);
1413     /// assert_eq!(iter.next(), None);
1414     /// assert_eq!(iter.next(), None);
1415     /// ```
1416     #[inline]
1417     #[stable(feature = "rust1", since = "1.0.0")]
1418     fn fuse(self) -> Fuse<Self>
1419     where
1420         Self: Sized,
1421     {
1422         Fuse::new(self)
1423     }
1424
1425     /// Does something with each element of an iterator, passing the value on.
1426     ///
1427     /// When using iterators, you'll often chain several of them together.
1428     /// While working on such code, you might want to check out what's
1429     /// happening at various parts in the pipeline. To do that, insert
1430     /// a call to `inspect()`.
1431     ///
1432     /// It's more common for `inspect()` to be used as a debugging tool than to
1433     /// exist in your final code, but applications may find it useful in certain
1434     /// situations when errors need to be logged before being discarded.
1435     ///
1436     /// # Examples
1437     ///
1438     /// Basic usage:
1439     ///
1440     /// ```
1441     /// let a = [1, 4, 2, 3];
1442     ///
1443     /// // this iterator sequence is complex.
1444     /// let sum = a.iter()
1445     ///     .cloned()
1446     ///     .filter(|x| x % 2 == 0)
1447     ///     .fold(0, |sum, i| sum + i);
1448     ///
1449     /// println!("{}", sum);
1450     ///
1451     /// // let's add some inspect() calls to investigate what's happening
1452     /// let sum = a.iter()
1453     ///     .cloned()
1454     ///     .inspect(|x| println!("about to filter: {}", x))
1455     ///     .filter(|x| x % 2 == 0)
1456     ///     .inspect(|x| println!("made it through filter: {}", x))
1457     ///     .fold(0, |sum, i| sum + i);
1458     ///
1459     /// println!("{}", sum);
1460     /// ```
1461     ///
1462     /// This will print:
1463     ///
1464     /// ```text
1465     /// 6
1466     /// about to filter: 1
1467     /// about to filter: 4
1468     /// made it through filter: 4
1469     /// about to filter: 2
1470     /// made it through filter: 2
1471     /// about to filter: 3
1472     /// 6
1473     /// ```
1474     ///
1475     /// Logging errors before discarding them:
1476     ///
1477     /// ```
1478     /// let lines = ["1", "2", "a"];
1479     ///
1480     /// let sum: i32 = lines
1481     ///     .iter()
1482     ///     .map(|line| line.parse::<i32>())
1483     ///     .inspect(|num| {
1484     ///         if let Err(ref e) = *num {
1485     ///             println!("Parsing error: {}", e);
1486     ///         }
1487     ///     })
1488     ///     .filter_map(Result::ok)
1489     ///     .sum();
1490     ///
1491     /// println!("Sum: {}", sum);
1492     /// ```
1493     ///
1494     /// This will print:
1495     ///
1496     /// ```text
1497     /// Parsing error: invalid digit found in string
1498     /// Sum: 3
1499     /// ```
1500     #[inline]
1501     #[stable(feature = "rust1", since = "1.0.0")]
1502     fn inspect<F>(self, f: F) -> Inspect<Self, F>
1503     where
1504         Self: Sized,
1505         F: FnMut(&Self::Item),
1506     {
1507         Inspect::new(self, f)
1508     }
1509
1510     /// Borrows an iterator, rather than consuming it.
1511     ///
1512     /// This is useful to allow applying iterator adaptors while still
1513     /// retaining ownership of the original iterator.
1514     ///
1515     /// # Examples
1516     ///
1517     /// Basic usage:
1518     ///
1519     /// ```
1520     /// let a = [1, 2, 3];
1521     ///
1522     /// let iter = a.iter();
1523     ///
1524     /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i);
1525     ///
1526     /// assert_eq!(sum, 6);
1527     ///
1528     /// // if we try to use iter again, it won't work. The following line
1529     /// // gives "error: use of moved value: `iter`
1530     /// // assert_eq!(iter.next(), None);
1531     ///
1532     /// // let's try that again
1533     /// let a = [1, 2, 3];
1534     ///
1535     /// let mut iter = a.iter();
1536     ///
1537     /// // instead, we add in a .by_ref()
1538     /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i);
1539     ///
1540     /// assert_eq!(sum, 3);
1541     ///
1542     /// // now this is just fine:
1543     /// assert_eq!(iter.next(), Some(&3));
1544     /// assert_eq!(iter.next(), None);
1545     /// ```
1546     #[stable(feature = "rust1", since = "1.0.0")]
1547     fn by_ref(&mut self) -> &mut Self
1548     where
1549         Self: Sized,
1550     {
1551         self
1552     }
1553
1554     /// Transforms an iterator into a collection.
1555     ///
1556     /// `collect()` can take anything iterable, and turn it into a relevant
1557     /// collection. This is one of the more powerful methods in the standard
1558     /// library, used in a variety of contexts.
1559     ///
1560     /// The most basic pattern in which `collect()` is used is to turn one
1561     /// collection into another. You take a collection, call [`iter`] on it,
1562     /// do a bunch of transformations, and then `collect()` at the end.
1563     ///
1564     /// One of the keys to `collect()`'s power is that many things you might
1565     /// not think of as 'collections' actually are. For example, a [`String`]
1566     /// is a collection of [`char`]s. And a collection of
1567     /// [`Result<T, E>`][`Result`] can be thought of as single
1568     /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1569     ///
1570     /// Because `collect()` is so general, it can cause problems with type
1571     /// inference. As such, `collect()` is one of the few times you'll see
1572     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1573     /// helps the inference algorithm understand specifically which collection
1574     /// you're trying to collect into.
1575     ///
1576     /// # Examples
1577     ///
1578     /// Basic usage:
1579     ///
1580     /// ```
1581     /// let a = [1, 2, 3];
1582     ///
1583     /// let doubled: Vec<i32> = a.iter()
1584     ///                          .map(|&x| x * 2)
1585     ///                          .collect();
1586     ///
1587     /// assert_eq!(vec![2, 4, 6], doubled);
1588     /// ```
1589     ///
1590     /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1591     /// we could collect into, for example, a [`VecDeque<T>`] instead:
1592     ///
1593     /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1594     ///
1595     /// ```
1596     /// use std::collections::VecDeque;
1597     ///
1598     /// let a = [1, 2, 3];
1599     ///
1600     /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1601     ///
1602     /// assert_eq!(2, doubled[0]);
1603     /// assert_eq!(4, doubled[1]);
1604     /// assert_eq!(6, doubled[2]);
1605     /// ```
1606     ///
1607     /// Using the 'turbofish' instead of annotating `doubled`:
1608     ///
1609     /// ```
1610     /// let a = [1, 2, 3];
1611     ///
1612     /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1613     ///
1614     /// assert_eq!(vec![2, 4, 6], doubled);
1615     /// ```
1616     ///
1617     /// Because `collect()` only cares about what you're collecting into, you can
1618     /// still use a partial type hint, `_`, with the turbofish:
1619     ///
1620     /// ```
1621     /// let a = [1, 2, 3];
1622     ///
1623     /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1624     ///
1625     /// assert_eq!(vec![2, 4, 6], doubled);
1626     /// ```
1627     ///
1628     /// Using `collect()` to make a [`String`]:
1629     ///
1630     /// ```
1631     /// let chars = ['g', 'd', 'k', 'k', 'n'];
1632     ///
1633     /// let hello: String = chars.iter()
1634     ///     .map(|&x| x as u8)
1635     ///     .map(|x| (x + 1) as char)
1636     ///     .collect();
1637     ///
1638     /// assert_eq!("hello", hello);
1639     /// ```
1640     ///
1641     /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1642     /// see if any of them failed:
1643     ///
1644     /// ```
1645     /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1646     ///
1647     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1648     ///
1649     /// // gives us the first error
1650     /// assert_eq!(Err("nope"), result);
1651     ///
1652     /// let results = [Ok(1), Ok(3)];
1653     ///
1654     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1655     ///
1656     /// // gives us the list of answers
1657     /// assert_eq!(Ok(vec![1, 3]), result);
1658     /// ```
1659     ///
1660     /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1661     /// [`String`]: ../../std/string/struct.String.html
1662     /// [`char`]: ../../std/primitive.char.html
1663     /// [`Result`]: ../../std/result/enum.Result.html
1664     #[inline]
1665     #[stable(feature = "rust1", since = "1.0.0")]
1666     #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1667     fn collect<B: FromIterator<Self::Item>>(self) -> B
1668     where
1669         Self: Sized,
1670     {
1671         FromIterator::from_iter(self)
1672     }
1673
1674     /// Consumes an iterator, creating two collections from it.
1675     ///
1676     /// The predicate passed to `partition()` can return `true`, or `false`.
1677     /// `partition()` returns a pair, all of the elements for which it returned
1678     /// `true`, and all of the elements for which it returned `false`.
1679     ///
1680     /// See also [`is_partitioned()`] and [`partition_in_place()`].
1681     ///
1682     /// [`is_partitioned()`]: #method.is_partitioned
1683     /// [`partition_in_place()`]: #method.partition_in_place
1684     ///
1685     /// # Examples
1686     ///
1687     /// Basic usage:
1688     ///
1689     /// ```
1690     /// let a = [1, 2, 3];
1691     ///
1692     /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1693     ///     .iter()
1694     ///     .partition(|&n| n % 2 == 0);
1695     ///
1696     /// assert_eq!(even, vec![2]);
1697     /// assert_eq!(odd, vec![1, 3]);
1698     /// ```
1699     #[stable(feature = "rust1", since = "1.0.0")]
1700     fn partition<B, F>(self, f: F) -> (B, B)
1701     where
1702         Self: Sized,
1703         B: Default + Extend<Self::Item>,
1704         F: FnMut(&Self::Item) -> bool,
1705     {
1706         #[inline]
1707         fn extend<'a, T, B: Extend<T>>(
1708             mut f: impl FnMut(&T) -> bool + 'a,
1709             left: &'a mut B,
1710             right: &'a mut B,
1711         ) -> impl FnMut((), T) + 'a {
1712             move |(), x| {
1713                 if f(&x) {
1714                     left.extend_one(x);
1715                 } else {
1716                     right.extend_one(x);
1717                 }
1718             }
1719         }
1720
1721         let mut left: B = Default::default();
1722         let mut right: B = Default::default();
1723
1724         self.fold((), extend(f, &mut left, &mut right));
1725
1726         (left, right)
1727     }
1728
1729     /// Reorders the elements of this iterator *in-place* according to the given predicate,
1730     /// such that all those that return `true` precede all those that return `false`.
1731     /// Returns the number of `true` elements found.
1732     ///
1733     /// The relative order of partitioned items is not maintained.
1734     ///
1735     /// See also [`is_partitioned()`] and [`partition()`].
1736     ///
1737     /// [`is_partitioned()`]: #method.is_partitioned
1738     /// [`partition()`]: #method.partition
1739     ///
1740     /// # Examples
1741     ///
1742     /// ```
1743     /// #![feature(iter_partition_in_place)]
1744     ///
1745     /// let mut a = [1, 2, 3, 4, 5, 6, 7];
1746     ///
1747     /// // Partition in-place between evens and odds
1748     /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0);
1749     ///
1750     /// assert_eq!(i, 3);
1751     /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens
1752     /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds
1753     /// ```
1754     #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
1755     fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
1756     where
1757         Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
1758         P: FnMut(&T) -> bool,
1759     {
1760         // FIXME: should we worry about the count overflowing? The only way to have more than
1761         // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
1762
1763         // These closure "factory" functions exist to avoid genericity in `Self`.
1764
1765         #[inline]
1766         fn is_false<'a, T>(
1767             predicate: &'a mut impl FnMut(&T) -> bool,
1768             true_count: &'a mut usize,
1769         ) -> impl FnMut(&&mut T) -> bool + 'a {
1770             move |x| {
1771                 let p = predicate(&**x);
1772                 *true_count += p as usize;
1773                 !p
1774             }
1775         }
1776
1777         #[inline]
1778         fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
1779             move |x| predicate(&**x)
1780         }
1781
1782         // Repeatedly find the first `false` and swap it with the last `true`.
1783         let mut true_count = 0;
1784         while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
1785             if let Some(tail) = self.rfind(is_true(predicate)) {
1786                 crate::mem::swap(head, tail);
1787                 true_count += 1;
1788             } else {
1789                 break;
1790             }
1791         }
1792         true_count
1793     }
1794
1795     /// Checks if the elements of this iterator are partitioned according to the given predicate,
1796     /// such that all those that return `true` precede all those that return `false`.
1797     ///
1798     /// See also [`partition()`] and [`partition_in_place()`].
1799     ///
1800     /// [`partition()`]: #method.partition
1801     /// [`partition_in_place()`]: #method.partition_in_place
1802     ///
1803     /// # Examples
1804     ///
1805     /// ```
1806     /// #![feature(iter_is_partitioned)]
1807     ///
1808     /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
1809     /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
1810     /// ```
1811     #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
1812     fn is_partitioned<P>(mut self, mut predicate: P) -> bool
1813     where
1814         Self: Sized,
1815         P: FnMut(Self::Item) -> bool,
1816     {
1817         // Either all items test `true`, or the first clause stops at `false`
1818         // and we check that there are no more `true` items after that.
1819         self.all(&mut predicate) || !self.any(predicate)
1820     }
1821
1822     /// An iterator method that applies a function as long as it returns
1823     /// successfully, producing a single, final value.
1824     ///
1825     /// `try_fold()` takes two arguments: an initial value, and a closure with
1826     /// two arguments: an 'accumulator', and an element. The closure either
1827     /// returns successfully, with the value that the accumulator should have
1828     /// for the next iteration, or it returns failure, with an error value that
1829     /// is propagated back to the caller immediately (short-circuiting).
1830     ///
1831     /// The initial value is the value the accumulator will have on the first
1832     /// call. If applying the closure succeeded against every element of the
1833     /// iterator, `try_fold()` returns the final accumulator as success.
1834     ///
1835     /// Folding is useful whenever you have a collection of something, and want
1836     /// to produce a single value from it.
1837     ///
1838     /// # Note to Implementors
1839     ///
1840     /// Several of the other (forward) methods have default implementations in
1841     /// terms of this one, so try to implement this explicitly if it can
1842     /// do something better than the default `for` loop implementation.
1843     ///
1844     /// In particular, try to have this call `try_fold()` on the internal parts
1845     /// from which this iterator is composed. If multiple calls are needed,
1846     /// the `?` operator may be convenient for chaining the accumulator value
1847     /// along, but beware any invariants that need to be upheld before those
1848     /// early returns. This is a `&mut self` method, so iteration needs to be
1849     /// resumable after hitting an error here.
1850     ///
1851     /// # Examples
1852     ///
1853     /// Basic usage:
1854     ///
1855     /// ```
1856     /// let a = [1, 2, 3];
1857     ///
1858     /// // the checked sum of all of the elements of the array
1859     /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1860     ///
1861     /// assert_eq!(sum, Some(6));
1862     /// ```
1863     ///
1864     /// Short-circuiting:
1865     ///
1866     /// ```
1867     /// let a = [10, 20, 30, 100, 40, 50];
1868     /// let mut it = a.iter();
1869     ///
1870     /// // This sum overflows when adding the 100 element
1871     /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1872     /// assert_eq!(sum, None);
1873     ///
1874     /// // Because it short-circuited, the remaining elements are still
1875     /// // available through the iterator.
1876     /// assert_eq!(it.len(), 2);
1877     /// assert_eq!(it.next(), Some(&40));
1878     /// ```
1879     #[inline]
1880     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1881     fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
1882     where
1883         Self: Sized,
1884         F: FnMut(B, Self::Item) -> R,
1885         R: Try<Ok = B>,
1886     {
1887         let mut accum = init;
1888         while let Some(x) = self.next() {
1889             accum = f(accum, x)?;
1890         }
1891         Try::from_ok(accum)
1892     }
1893
1894     /// An iterator method that applies a fallible function to each item in the
1895     /// iterator, stopping at the first error and returning that error.
1896     ///
1897     /// This can also be thought of as the fallible form of [`for_each()`]
1898     /// or as the stateless version of [`try_fold()`].
1899     ///
1900     /// [`for_each()`]: #method.for_each
1901     /// [`try_fold()`]: #method.try_fold
1902     ///
1903     /// # Examples
1904     ///
1905     /// ```
1906     /// use std::fs::rename;
1907     /// use std::io::{stdout, Write};
1908     /// use std::path::Path;
1909     ///
1910     /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1911     ///
1912     /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1913     /// assert!(res.is_ok());
1914     ///
1915     /// let mut it = data.iter().cloned();
1916     /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1917     /// assert!(res.is_err());
1918     /// // It short-circuited, so the remaining items are still in the iterator:
1919     /// assert_eq!(it.next(), Some("stale_bread.json"));
1920     /// ```
1921     #[inline]
1922     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1923     fn try_for_each<F, R>(&mut self, f: F) -> R
1924     where
1925         Self: Sized,
1926         F: FnMut(Self::Item) -> R,
1927         R: Try<Ok = ()>,
1928     {
1929         #[inline]
1930         fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
1931             move |(), x| f(x)
1932         }
1933
1934         self.try_fold((), call(f))
1935     }
1936
1937     /// An iterator method that applies a function, producing a single, final value.
1938     ///
1939     /// `fold()` takes two arguments: an initial value, and a closure with two
1940     /// arguments: an 'accumulator', and an element. The closure returns the value that
1941     /// the accumulator should have for the next iteration.
1942     ///
1943     /// The initial value is the value the accumulator will have on the first
1944     /// call.
1945     ///
1946     /// After applying this closure to every element of the iterator, `fold()`
1947     /// returns the accumulator.
1948     ///
1949     /// This operation is sometimes called 'reduce' or 'inject'.
1950     ///
1951     /// Folding is useful whenever you have a collection of something, and want
1952     /// to produce a single value from it.
1953     ///
1954     /// Note: `fold()`, and similar methods that traverse the entire iterator,
1955     /// may not terminate for infinite iterators, even on traits for which a
1956     /// result is determinable in finite time.
1957     ///
1958     /// # Note to Implementors
1959     ///
1960     /// Several of the other (forward) methods have default implementations in
1961     /// terms of this one, so try to implement this explicitly if it can
1962     /// do something better than the default `for` loop implementation.
1963     ///
1964     /// In particular, try to have this call `fold()` on the internal parts
1965     /// from which this iterator is composed.
1966     ///
1967     /// # Examples
1968     ///
1969     /// Basic usage:
1970     ///
1971     /// ```
1972     /// let a = [1, 2, 3];
1973     ///
1974     /// // the sum of all of the elements of the array
1975     /// let sum = a.iter().fold(0, |acc, x| acc + x);
1976     ///
1977     /// assert_eq!(sum, 6);
1978     /// ```
1979     ///
1980     /// Let's walk through each step of the iteration here:
1981     ///
1982     /// | element | acc | x | result |
1983     /// |---------|-----|---|--------|
1984     /// |         | 0   |   |        |
1985     /// | 1       | 0   | 1 | 1      |
1986     /// | 2       | 1   | 2 | 3      |
1987     /// | 3       | 3   | 3 | 6      |
1988     ///
1989     /// And so, our final result, `6`.
1990     ///
1991     /// It's common for people who haven't used iterators a lot to
1992     /// use a `for` loop with a list of things to build up a result. Those
1993     /// can be turned into `fold()`s:
1994     ///
1995     /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1996     ///
1997     /// ```
1998     /// let numbers = [1, 2, 3, 4, 5];
1999     ///
2000     /// let mut result = 0;
2001     ///
2002     /// // for loop:
2003     /// for i in &numbers {
2004     ///     result = result + i;
2005     /// }
2006     ///
2007     /// // fold:
2008     /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2009     ///
2010     /// // they're the same
2011     /// assert_eq!(result, result2);
2012     /// ```
2013     #[inline]
2014     #[stable(feature = "rust1", since = "1.0.0")]
2015     fn fold<B, F>(mut self, init: B, mut f: F) -> B
2016     where
2017         Self: Sized,
2018         F: FnMut(B, Self::Item) -> B,
2019     {
2020         let mut accum = init;
2021         while let Some(x) = self.next() {
2022             accum = f(accum, x);
2023         }
2024         accum
2025     }
2026
2027     /// The same as [`fold()`](#method.fold), but uses the first element in the
2028     /// iterator as the initial value, folding every subsequent element into it.
2029     /// If the iterator is empty, return `None`; otherwise, return the result
2030     /// of the fold.
2031     ///
2032     /// # Example
2033     ///
2034     /// Find the maximum value:
2035     ///
2036     /// ```
2037     /// #![feature(iterator_fold_self)]
2038     ///
2039     /// fn find_max<I>(iter: I) -> Option<I::Item>
2040     ///     where I: Iterator,
2041     ///           I::Item: Ord,
2042     /// {
2043     ///     iter.fold_first(|a, b| {
2044     ///         if a >= b { a } else { b }
2045     ///     })
2046     /// }
2047     /// let a = [10, 20, 5, -23, 0];
2048     /// let b: [u32; 0] = [];
2049     ///
2050     /// assert_eq!(find_max(a.iter()), Some(&20));
2051     /// assert_eq!(find_max(b.iter()), None);
2052     /// ```
2053     #[inline]
2054     #[unstable(feature = "iterator_fold_self", issue = "68125")]
2055     fn fold_first<F>(mut self, f: F) -> Option<Self::Item>
2056     where
2057         Self: Sized,
2058         F: FnMut(Self::Item, Self::Item) -> Self::Item,
2059     {
2060         let first = self.next()?;
2061         Some(self.fold(first, f))
2062     }
2063
2064     /// Tests if every element of the iterator matches a predicate.
2065     ///
2066     /// `all()` takes a closure that returns `true` or `false`. It applies
2067     /// this closure to each element of the iterator, and if they all return
2068     /// `true`, then so does `all()`. If any of them return `false`, it
2069     /// returns `false`.
2070     ///
2071     /// `all()` is short-circuiting; in other words, it will stop processing
2072     /// as soon as it finds a `false`, given that no matter what else happens,
2073     /// the result will also be `false`.
2074     ///
2075     /// An empty iterator returns `true`.
2076     ///
2077     /// # Examples
2078     ///
2079     /// Basic usage:
2080     ///
2081     /// ```
2082     /// let a = [1, 2, 3];
2083     ///
2084     /// assert!(a.iter().all(|&x| x > 0));
2085     ///
2086     /// assert!(!a.iter().all(|&x| x > 2));
2087     /// ```
2088     ///
2089     /// Stopping at the first `false`:
2090     ///
2091     /// ```
2092     /// let a = [1, 2, 3];
2093     ///
2094     /// let mut iter = a.iter();
2095     ///
2096     /// assert!(!iter.all(|&x| x != 2));
2097     ///
2098     /// // we can still use `iter`, as there are more elements.
2099     /// assert_eq!(iter.next(), Some(&3));
2100     /// ```
2101     #[inline]
2102     #[stable(feature = "rust1", since = "1.0.0")]
2103     fn all<F>(&mut self, f: F) -> bool
2104     where
2105         Self: Sized,
2106         F: FnMut(Self::Item) -> bool,
2107     {
2108         #[inline]
2109         fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2110             move |(), x| {
2111                 if f(x) { LoopState::Continue(()) } else { LoopState::Break(()) }
2112             }
2113         }
2114         self.try_fold((), check(f)) == LoopState::Continue(())
2115     }
2116
2117     /// Tests if any element of the iterator matches a predicate.
2118     ///
2119     /// `any()` takes a closure that returns `true` or `false`. It applies
2120     /// this closure to each element of the iterator, and if any of them return
2121     /// `true`, then so does `any()`. If they all return `false`, it
2122     /// returns `false`.
2123     ///
2124     /// `any()` is short-circuiting; in other words, it will stop processing
2125     /// as soon as it finds a `true`, given that no matter what else happens,
2126     /// the result will also be `true`.
2127     ///
2128     /// An empty iterator returns `false`.
2129     ///
2130     /// # Examples
2131     ///
2132     /// Basic usage:
2133     ///
2134     /// ```
2135     /// let a = [1, 2, 3];
2136     ///
2137     /// assert!(a.iter().any(|&x| x > 0));
2138     ///
2139     /// assert!(!a.iter().any(|&x| x > 5));
2140     /// ```
2141     ///
2142     /// Stopping at the first `true`:
2143     ///
2144     /// ```
2145     /// let a = [1, 2, 3];
2146     ///
2147     /// let mut iter = a.iter();
2148     ///
2149     /// assert!(iter.any(|&x| x != 2));
2150     ///
2151     /// // we can still use `iter`, as there are more elements.
2152     /// assert_eq!(iter.next(), Some(&2));
2153     /// ```
2154     #[inline]
2155     #[stable(feature = "rust1", since = "1.0.0")]
2156     fn any<F>(&mut self, f: F) -> bool
2157     where
2158         Self: Sized,
2159         F: FnMut(Self::Item) -> bool,
2160     {
2161         #[inline]
2162         fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> {
2163             move |(), x| {
2164                 if f(x) { LoopState::Break(()) } else { LoopState::Continue(()) }
2165             }
2166         }
2167
2168         self.try_fold((), check(f)) == LoopState::Break(())
2169     }
2170
2171     /// Searches for an element of an iterator that satisfies a predicate.
2172     ///
2173     /// `find()` takes a closure that returns `true` or `false`. It applies
2174     /// this closure to each element of the iterator, and if any of them return
2175     /// `true`, then `find()` returns [`Some(element)`]. If they all return
2176     /// `false`, it returns [`None`].
2177     ///
2178     /// `find()` is short-circuiting; in other words, it will stop processing
2179     /// as soon as the closure returns `true`.
2180     ///
2181     /// Because `find()` takes a reference, and many iterators iterate over
2182     /// references, this leads to a possibly confusing situation where the
2183     /// argument is a double reference. You can see this effect in the
2184     /// examples below, with `&&x`.
2185     ///
2186     /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
2187     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2188     ///
2189     /// # Examples
2190     ///
2191     /// Basic usage:
2192     ///
2193     /// ```
2194     /// let a = [1, 2, 3];
2195     ///
2196     /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2197     ///
2198     /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2199     /// ```
2200     ///
2201     /// Stopping at the first `true`:
2202     ///
2203     /// ```
2204     /// let a = [1, 2, 3];
2205     ///
2206     /// let mut iter = a.iter();
2207     ///
2208     /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
2209     ///
2210     /// // we can still use `iter`, as there are more elements.
2211     /// assert_eq!(iter.next(), Some(&3));
2212     /// ```
2213     ///
2214     /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2215     #[inline]
2216     #[stable(feature = "rust1", since = "1.0.0")]
2217     fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2218     where
2219         Self: Sized,
2220         P: FnMut(&Self::Item) -> bool,
2221     {
2222         #[inline]
2223         fn check<T>(
2224             mut predicate: impl FnMut(&T) -> bool,
2225         ) -> impl FnMut((), T) -> LoopState<(), T> {
2226             move |(), x| {
2227                 if predicate(&x) { LoopState::Break(x) } else { LoopState::Continue(()) }
2228             }
2229         }
2230
2231         self.try_fold((), check(predicate)).break_value()
2232     }
2233
2234     /// Applies function to the elements of iterator and returns
2235     /// the first non-none result.
2236     ///
2237     /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2238     ///
2239     ///
2240     /// # Examples
2241     ///
2242     /// ```
2243     /// let a = ["lol", "NaN", "2", "5"];
2244     ///
2245     /// let first_number = a.iter().find_map(|s| s.parse().ok());
2246     ///
2247     /// assert_eq!(first_number, Some(2));
2248     /// ```
2249     #[inline]
2250     #[stable(feature = "iterator_find_map", since = "1.30.0")]
2251     fn find_map<B, F>(&mut self, f: F) -> Option<B>
2252     where
2253         Self: Sized,
2254         F: FnMut(Self::Item) -> Option<B>,
2255     {
2256         #[inline]
2257         fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> LoopState<(), B> {
2258             move |(), x| match f(x) {
2259                 Some(x) => LoopState::Break(x),
2260                 None => LoopState::Continue(()),
2261             }
2262         }
2263
2264         self.try_fold((), check(f)).break_value()
2265     }
2266
2267     /// Applies function to the elements of iterator and returns
2268     /// the first true result or the first error.
2269     ///
2270     /// # Examples
2271     ///
2272     /// ```
2273     /// #![feature(try_find)]
2274     ///
2275     /// let a = ["1", "2", "lol", "NaN", "5"];
2276     ///
2277     /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2278     ///     Ok(s.parse::<i32>()?  == search)
2279     /// };
2280     ///
2281     /// let result = a.iter().try_find(|&&s| is_my_num(s, 2));
2282     /// assert_eq!(result, Ok(Some(&"2")));
2283     ///
2284     /// let result = a.iter().try_find(|&&s| is_my_num(s, 5));
2285     /// assert!(result.is_err());
2286     /// ```
2287     #[inline]
2288     #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2289     fn try_find<F, R>(&mut self, f: F) -> Result<Option<Self::Item>, R::Error>
2290     where
2291         Self: Sized,
2292         F: FnMut(&Self::Item) -> R,
2293         R: Try<Ok = bool>,
2294     {
2295         #[inline]
2296         fn check<F, T, R>(mut f: F) -> impl FnMut((), T) -> LoopState<(), Result<T, R::Error>>
2297         where
2298             F: FnMut(&T) -> R,
2299             R: Try<Ok = bool>,
2300         {
2301             move |(), x| match f(&x).into_result() {
2302                 Ok(false) => LoopState::Continue(()),
2303                 Ok(true) => LoopState::Break(Ok(x)),
2304                 Err(x) => LoopState::Break(Err(x)),
2305             }
2306         }
2307
2308         self.try_fold((), check(f)).break_value().transpose()
2309     }
2310
2311     /// Searches for an element in an iterator, returning its index.
2312     ///
2313     /// `position()` takes a closure that returns `true` or `false`. It applies
2314     /// this closure to each element of the iterator, and if one of them
2315     /// returns `true`, then `position()` returns [`Some(index)`]. If all of
2316     /// them return `false`, it returns [`None`].
2317     ///
2318     /// `position()` is short-circuiting; in other words, it will stop
2319     /// processing as soon as it finds a `true`.
2320     ///
2321     /// # Overflow Behavior
2322     ///
2323     /// The method does no guarding against overflows, so if there are more
2324     /// than [`usize::MAX`] non-matching elements, it either produces the wrong
2325     /// result or panics. If debug assertions are enabled, a panic is
2326     /// guaranteed.
2327     ///
2328     /// # Panics
2329     ///
2330     /// This function might panic if the iterator has more than `usize::MAX`
2331     /// non-matching elements.
2332     ///
2333     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2334     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2335     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
2336     ///
2337     /// # Examples
2338     ///
2339     /// Basic usage:
2340     ///
2341     /// ```
2342     /// let a = [1, 2, 3];
2343     ///
2344     /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
2345     ///
2346     /// assert_eq!(a.iter().position(|&x| x == 5), None);
2347     /// ```
2348     ///
2349     /// Stopping at the first `true`:
2350     ///
2351     /// ```
2352     /// let a = [1, 2, 3, 4];
2353     ///
2354     /// let mut iter = a.iter();
2355     ///
2356     /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
2357     ///
2358     /// // we can still use `iter`, as there are more elements.
2359     /// assert_eq!(iter.next(), Some(&3));
2360     ///
2361     /// // The returned index depends on iterator state
2362     /// assert_eq!(iter.position(|&x| x == 4), Some(0));
2363     ///
2364     /// ```
2365     #[inline]
2366     #[stable(feature = "rust1", since = "1.0.0")]
2367     fn position<P>(&mut self, predicate: P) -> Option<usize>
2368     where
2369         Self: Sized,
2370         P: FnMut(Self::Item) -> bool,
2371     {
2372         #[inline]
2373         fn check<T>(
2374             mut predicate: impl FnMut(T) -> bool,
2375         ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2376             // The addition might panic on overflow
2377             move |i, x| {
2378                 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(Add::add(i, 1)) }
2379             }
2380         }
2381
2382         self.try_fold(0, check(predicate)).break_value()
2383     }
2384
2385     /// Searches for an element in an iterator from the right, returning its
2386     /// index.
2387     ///
2388     /// `rposition()` takes a closure that returns `true` or `false`. It applies
2389     /// this closure to each element of the iterator, starting from the end,
2390     /// and if one of them returns `true`, then `rposition()` returns
2391     /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
2392     ///
2393     /// `rposition()` is short-circuiting; in other words, it will stop
2394     /// processing as soon as it finds a `true`.
2395     ///
2396     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
2397     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2398     ///
2399     /// # Examples
2400     ///
2401     /// Basic usage:
2402     ///
2403     /// ```
2404     /// let a = [1, 2, 3];
2405     ///
2406     /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
2407     ///
2408     /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
2409     /// ```
2410     ///
2411     /// Stopping at the first `true`:
2412     ///
2413     /// ```
2414     /// let a = [1, 2, 3];
2415     ///
2416     /// let mut iter = a.iter();
2417     ///
2418     /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
2419     ///
2420     /// // we can still use `iter`, as there are more elements.
2421     /// assert_eq!(iter.next(), Some(&1));
2422     /// ```
2423     #[inline]
2424     #[stable(feature = "rust1", since = "1.0.0")]
2425     fn rposition<P>(&mut self, predicate: P) -> Option<usize>
2426     where
2427         P: FnMut(Self::Item) -> bool,
2428         Self: Sized + ExactSizeIterator + DoubleEndedIterator,
2429     {
2430         // No need for an overflow check here, because `ExactSizeIterator`
2431         // implies that the number of elements fits into a `usize`.
2432         #[inline]
2433         fn check<T>(
2434             mut predicate: impl FnMut(T) -> bool,
2435         ) -> impl FnMut(usize, T) -> LoopState<usize, usize> {
2436             move |i, x| {
2437                 let i = i - 1;
2438                 if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(i) }
2439             }
2440         }
2441
2442         let n = self.len();
2443         self.try_rfold(n, check(predicate)).break_value()
2444     }
2445
2446     /// Returns the maximum element of an iterator.
2447     ///
2448     /// If several elements are equally maximum, the last element is
2449     /// returned. If the iterator is empty, [`None`] is returned.
2450     ///
2451     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2452     ///
2453     /// # Examples
2454     ///
2455     /// Basic usage:
2456     ///
2457     /// ```
2458     /// let a = [1, 2, 3];
2459     /// let b: Vec<u32> = Vec::new();
2460     ///
2461     /// assert_eq!(a.iter().max(), Some(&3));
2462     /// assert_eq!(b.iter().max(), None);
2463     /// ```
2464     #[inline]
2465     #[stable(feature = "rust1", since = "1.0.0")]
2466     fn max(self) -> Option<Self::Item>
2467     where
2468         Self: Sized,
2469         Self::Item: Ord,
2470     {
2471         self.max_by(Ord::cmp)
2472     }
2473
2474     /// Returns the minimum element of an iterator.
2475     ///
2476     /// If several elements are equally minimum, the first element is
2477     /// returned. If the iterator is empty, [`None`] is returned.
2478     ///
2479     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2480     ///
2481     /// # Examples
2482     ///
2483     /// Basic usage:
2484     ///
2485     /// ```
2486     /// let a = [1, 2, 3];
2487     /// let b: Vec<u32> = Vec::new();
2488     ///
2489     /// assert_eq!(a.iter().min(), Some(&1));
2490     /// assert_eq!(b.iter().min(), None);
2491     /// ```
2492     #[inline]
2493     #[stable(feature = "rust1", since = "1.0.0")]
2494     fn min(self) -> Option<Self::Item>
2495     where
2496         Self: Sized,
2497         Self::Item: Ord,
2498     {
2499         self.min_by(Ord::cmp)
2500     }
2501
2502     /// Returns the element that gives the maximum value from the
2503     /// specified function.
2504     ///
2505     /// If several elements are equally maximum, the last element is
2506     /// returned. If the iterator is empty, [`None`] is returned.
2507     ///
2508     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2509     ///
2510     /// # Examples
2511     ///
2512     /// ```
2513     /// let a = [-3_i32, 0, 1, 5, -10];
2514     /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2515     /// ```
2516     #[inline]
2517     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2518     fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2519     where
2520         Self: Sized,
2521         F: FnMut(&Self::Item) -> B,
2522     {
2523         #[inline]
2524         fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2525             move |x| (f(&x), x)
2526         }
2527
2528         #[inline]
2529         fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2530             x_p.cmp(y_p)
2531         }
2532
2533         let (_, x) = self.map(key(f)).max_by(compare)?;
2534         Some(x)
2535     }
2536
2537     /// Returns the element that gives the maximum value with respect to the
2538     /// specified comparison function.
2539     ///
2540     /// If several elements are equally maximum, the last element is
2541     /// returned. If the iterator is empty, [`None`] is returned.
2542     ///
2543     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2544     ///
2545     /// # Examples
2546     ///
2547     /// ```
2548     /// let a = [-3_i32, 0, 1, 5, -10];
2549     /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2550     /// ```
2551     #[inline]
2552     #[stable(feature = "iter_max_by", since = "1.15.0")]
2553     fn max_by<F>(self, compare: F) -> Option<Self::Item>
2554     where
2555         Self: Sized,
2556         F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2557     {
2558         #[inline]
2559         fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2560             move |x, y| cmp::max_by(x, y, &mut compare)
2561         }
2562
2563         self.fold_first(fold(compare))
2564     }
2565
2566     /// Returns the element that gives the minimum value from the
2567     /// specified function.
2568     ///
2569     /// If several elements are equally minimum, the first element is
2570     /// returned. If the iterator is empty, [`None`] is returned.
2571     ///
2572     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2573     ///
2574     /// # Examples
2575     ///
2576     /// ```
2577     /// let a = [-3_i32, 0, 1, 5, -10];
2578     /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2579     /// ```
2580     #[inline]
2581     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2582     fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
2583     where
2584         Self: Sized,
2585         F: FnMut(&Self::Item) -> B,
2586     {
2587         #[inline]
2588         fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
2589             move |x| (f(&x), x)
2590         }
2591
2592         #[inline]
2593         fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
2594             x_p.cmp(y_p)
2595         }
2596
2597         let (_, x) = self.map(key(f)).min_by(compare)?;
2598         Some(x)
2599     }
2600
2601     /// Returns the element that gives the minimum value with respect to the
2602     /// specified comparison function.
2603     ///
2604     /// If several elements are equally minimum, the first element is
2605     /// returned. If the iterator is empty, [`None`] is returned.
2606     ///
2607     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2608     ///
2609     /// # Examples
2610     ///
2611     /// ```
2612     /// let a = [-3_i32, 0, 1, 5, -10];
2613     /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2614     /// ```
2615     #[inline]
2616     #[stable(feature = "iter_min_by", since = "1.15.0")]
2617     fn min_by<F>(self, compare: F) -> Option<Self::Item>
2618     where
2619         Self: Sized,
2620         F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2621     {
2622         #[inline]
2623         fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
2624             move |x, y| cmp::min_by(x, y, &mut compare)
2625         }
2626
2627         self.fold_first(fold(compare))
2628     }
2629
2630     /// Reverses an iterator's direction.
2631     ///
2632     /// Usually, iterators iterate from left to right. After using `rev()`,
2633     /// an iterator will instead iterate from right to left.
2634     ///
2635     /// This is only possible if the iterator has an end, so `rev()` only
2636     /// works on [`DoubleEndedIterator`]s.
2637     ///
2638     /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2639     ///
2640     /// # Examples
2641     ///
2642     /// ```
2643     /// let a = [1, 2, 3];
2644     ///
2645     /// let mut iter = a.iter().rev();
2646     ///
2647     /// assert_eq!(iter.next(), Some(&3));
2648     /// assert_eq!(iter.next(), Some(&2));
2649     /// assert_eq!(iter.next(), Some(&1));
2650     ///
2651     /// assert_eq!(iter.next(), None);
2652     /// ```
2653     #[inline]
2654     #[stable(feature = "rust1", since = "1.0.0")]
2655     fn rev(self) -> Rev<Self>
2656     where
2657         Self: Sized + DoubleEndedIterator,
2658     {
2659         Rev::new(self)
2660     }
2661
2662     /// Converts an iterator of pairs into a pair of containers.
2663     ///
2664     /// `unzip()` consumes an entire iterator of pairs, producing two
2665     /// collections: one from the left elements of the pairs, and one
2666     /// from the right elements.
2667     ///
2668     /// This function is, in some sense, the opposite of [`zip`].
2669     ///
2670     /// [`zip`]: #method.zip
2671     ///
2672     /// # Examples
2673     ///
2674     /// Basic usage:
2675     ///
2676     /// ```
2677     /// let a = [(1, 2), (3, 4)];
2678     ///
2679     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2680     ///
2681     /// assert_eq!(left, [1, 3]);
2682     /// assert_eq!(right, [2, 4]);
2683     /// ```
2684     #[stable(feature = "rust1", since = "1.0.0")]
2685     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
2686     where
2687         FromA: Default + Extend<A>,
2688         FromB: Default + Extend<B>,
2689         Self: Sized + Iterator<Item = (A, B)>,
2690     {
2691         fn extend<'a, A, B>(
2692             ts: &'a mut impl Extend<A>,
2693             us: &'a mut impl Extend<B>,
2694         ) -> impl FnMut((), (A, B)) + 'a {
2695             move |(), (t, u)| {
2696                 ts.extend_one(t);
2697                 us.extend_one(u);
2698             }
2699         }
2700
2701         let mut ts: FromA = Default::default();
2702         let mut us: FromB = Default::default();
2703
2704         let (lower_bound, _) = self.size_hint();
2705         if lower_bound > 0 {
2706             ts.extend_reserve(lower_bound);
2707             us.extend_reserve(lower_bound);
2708         }
2709
2710         self.fold((), extend(&mut ts, &mut us));
2711
2712         (ts, us)
2713     }
2714
2715     /// Creates an iterator which copies all of its elements.
2716     ///
2717     /// This is useful when you have an iterator over `&T`, but you need an
2718     /// iterator over `T`.
2719     ///
2720     /// # Examples
2721     ///
2722     /// Basic usage:
2723     ///
2724     /// ```
2725     /// let a = [1, 2, 3];
2726     ///
2727     /// let v_copied: Vec<_> = a.iter().copied().collect();
2728     ///
2729     /// // copied is the same as .map(|&x| x)
2730     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2731     ///
2732     /// assert_eq!(v_copied, vec![1, 2, 3]);
2733     /// assert_eq!(v_map, vec![1, 2, 3]);
2734     /// ```
2735     #[stable(feature = "iter_copied", since = "1.36.0")]
2736     fn copied<'a, T: 'a>(self) -> Copied<Self>
2737     where
2738         Self: Sized + Iterator<Item = &'a T>,
2739         T: Copy,
2740     {
2741         Copied::new(self)
2742     }
2743
2744     /// Creates an iterator which [`clone`]s all of its elements.
2745     ///
2746     /// This is useful when you have an iterator over `&T`, but you need an
2747     /// iterator over `T`.
2748     ///
2749     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2750     ///
2751     /// # Examples
2752     ///
2753     /// Basic usage:
2754     ///
2755     /// ```
2756     /// let a = [1, 2, 3];
2757     ///
2758     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2759     ///
2760     /// // cloned is the same as .map(|&x| x), for integers
2761     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2762     ///
2763     /// assert_eq!(v_cloned, vec![1, 2, 3]);
2764     /// assert_eq!(v_map, vec![1, 2, 3]);
2765     /// ```
2766     #[stable(feature = "rust1", since = "1.0.0")]
2767     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2768     where
2769         Self: Sized + Iterator<Item = &'a T>,
2770         T: Clone,
2771     {
2772         Cloned::new(self)
2773     }
2774
2775     /// Repeats an iterator endlessly.
2776     ///
2777     /// Instead of stopping at [`None`], the iterator will instead start again,
2778     /// from the beginning. After iterating again, it will start at the
2779     /// beginning again. And again. And again. Forever.
2780     ///
2781     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2782     ///
2783     /// # Examples
2784     ///
2785     /// Basic usage:
2786     ///
2787     /// ```
2788     /// let a = [1, 2, 3];
2789     ///
2790     /// let mut it = a.iter().cycle();
2791     ///
2792     /// assert_eq!(it.next(), Some(&1));
2793     /// assert_eq!(it.next(), Some(&2));
2794     /// assert_eq!(it.next(), Some(&3));
2795     /// assert_eq!(it.next(), Some(&1));
2796     /// assert_eq!(it.next(), Some(&2));
2797     /// assert_eq!(it.next(), Some(&3));
2798     /// assert_eq!(it.next(), Some(&1));
2799     /// ```
2800     #[stable(feature = "rust1", since = "1.0.0")]
2801     #[inline]
2802     fn cycle(self) -> Cycle<Self>
2803     where
2804         Self: Sized + Clone,
2805     {
2806         Cycle::new(self)
2807     }
2808
2809     /// Sums the elements of an iterator.
2810     ///
2811     /// Takes each element, adds them together, and returns the result.
2812     ///
2813     /// An empty iterator returns the zero value of the type.
2814     ///
2815     /// # Panics
2816     ///
2817     /// When calling `sum()` and a primitive integer type is being returned, this
2818     /// method will panic if the computation overflows and debug assertions are
2819     /// enabled.
2820     ///
2821     /// # Examples
2822     ///
2823     /// Basic usage:
2824     ///
2825     /// ```
2826     /// let a = [1, 2, 3];
2827     /// let sum: i32 = a.iter().sum();
2828     ///
2829     /// assert_eq!(sum, 6);
2830     /// ```
2831     #[stable(feature = "iter_arith", since = "1.11.0")]
2832     fn sum<S>(self) -> S
2833     where
2834         Self: Sized,
2835         S: Sum<Self::Item>,
2836     {
2837         Sum::sum(self)
2838     }
2839
2840     /// Iterates over the entire iterator, multiplying all the elements
2841     ///
2842     /// An empty iterator returns the one value of the type.
2843     ///
2844     /// # Panics
2845     ///
2846     /// When calling `product()` and a primitive integer type is being returned,
2847     /// method will panic if the computation overflows and debug assertions are
2848     /// enabled.
2849     ///
2850     /// # Examples
2851     ///
2852     /// ```
2853     /// fn factorial(n: u32) -> u32 {
2854     ///     (1..=n).product()
2855     /// }
2856     /// assert_eq!(factorial(0), 1);
2857     /// assert_eq!(factorial(1), 1);
2858     /// assert_eq!(factorial(5), 120);
2859     /// ```
2860     #[stable(feature = "iter_arith", since = "1.11.0")]
2861     fn product<P>(self) -> P
2862     where
2863         Self: Sized,
2864         P: Product<Self::Item>,
2865     {
2866         Product::product(self)
2867     }
2868
2869     /// Lexicographically compares the elements of this `Iterator` with those
2870     /// of another.
2871     ///
2872     /// # Examples
2873     ///
2874     /// ```
2875     /// use std::cmp::Ordering;
2876     ///
2877     /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
2878     /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
2879     /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
2880     /// ```
2881     #[stable(feature = "iter_order", since = "1.5.0")]
2882     fn cmp<I>(self, other: I) -> Ordering
2883     where
2884         I: IntoIterator<Item = Self::Item>,
2885         Self::Item: Ord,
2886         Self: Sized,
2887     {
2888         self.cmp_by(other, |x, y| x.cmp(&y))
2889     }
2890
2891     /// Lexicographically compares the elements of this `Iterator` with those
2892     /// of another with respect to the specified comparison function.
2893     ///
2894     /// # Examples
2895     ///
2896     /// Basic usage:
2897     ///
2898     /// ```
2899     /// #![feature(iter_order_by)]
2900     ///
2901     /// use std::cmp::Ordering;
2902     ///
2903     /// let xs = [1, 2, 3, 4];
2904     /// let ys = [1, 4, 9, 16];
2905     ///
2906     /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less);
2907     /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal);
2908     /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater);
2909     /// ```
2910     #[unstable(feature = "iter_order_by", issue = "64295")]
2911     fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering
2912     where
2913         Self: Sized,
2914         I: IntoIterator,
2915         F: FnMut(Self::Item, I::Item) -> Ordering,
2916     {
2917         let mut other = other.into_iter();
2918
2919         loop {
2920             let x = match self.next() {
2921                 None => {
2922                     if other.next().is_none() {
2923                         return Ordering::Equal;
2924                     } else {
2925                         return Ordering::Less;
2926                     }
2927                 }
2928                 Some(val) => val,
2929             };
2930
2931             let y = match other.next() {
2932                 None => return Ordering::Greater,
2933                 Some(val) => val,
2934             };
2935
2936             match cmp(x, y) {
2937                 Ordering::Equal => (),
2938                 non_eq => return non_eq,
2939             }
2940         }
2941     }
2942
2943     /// Lexicographically compares the elements of this `Iterator` with those
2944     /// of another.
2945     ///
2946     /// # Examples
2947     ///
2948     /// ```
2949     /// use std::cmp::Ordering;
2950     ///
2951     /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
2952     /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
2953     /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
2954     ///
2955     /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
2956     /// ```
2957     #[stable(feature = "iter_order", since = "1.5.0")]
2958     fn partial_cmp<I>(self, other: I) -> Option<Ordering>
2959     where
2960         I: IntoIterator,
2961         Self::Item: PartialOrd<I::Item>,
2962         Self: Sized,
2963     {
2964         self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
2965     }
2966
2967     /// Lexicographically compares the elements of this `Iterator` with those
2968     /// of another with respect to the specified comparison function.
2969     ///
2970     /// # Examples
2971     ///
2972     /// Basic usage:
2973     ///
2974     /// ```
2975     /// #![feature(iter_order_by)]
2976     ///
2977     /// use std::cmp::Ordering;
2978     ///
2979     /// let xs = [1.0, 2.0, 3.0, 4.0];
2980     /// let ys = [1.0, 4.0, 9.0, 16.0];
2981     ///
2982     /// assert_eq!(
2983     ///     xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)),
2984     ///     Some(Ordering::Less)
2985     /// );
2986     /// assert_eq!(
2987     ///     xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)),
2988     ///     Some(Ordering::Equal)
2989     /// );
2990     /// assert_eq!(
2991     ///     xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)),
2992     ///     Some(Ordering::Greater)
2993     /// );
2994     /// ```
2995     #[unstable(feature = "iter_order_by", issue = "64295")]
2996     fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>
2997     where
2998         Self: Sized,
2999         I: IntoIterator,
3000         F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3001     {
3002         let mut other = other.into_iter();
3003
3004         loop {
3005             let x = match self.next() {
3006                 None => {
3007                     if other.next().is_none() {
3008                         return Some(Ordering::Equal);
3009                     } else {
3010                         return Some(Ordering::Less);
3011                     }
3012                 }
3013                 Some(val) => val,
3014             };
3015
3016             let y = match other.next() {
3017                 None => return Some(Ordering::Greater),
3018                 Some(val) => val,
3019             };
3020
3021             match partial_cmp(x, y) {
3022                 Some(Ordering::Equal) => (),
3023                 non_eq => return non_eq,
3024             }
3025         }
3026     }
3027
3028     /// Determines if the elements of this `Iterator` are equal to those of
3029     /// another.
3030     ///
3031     /// # Examples
3032     ///
3033     /// ```
3034     /// assert_eq!([1].iter().eq([1].iter()), true);
3035     /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3036     /// ```
3037     #[stable(feature = "iter_order", since = "1.5.0")]
3038     fn eq<I>(self, other: I) -> bool
3039     where
3040         I: IntoIterator,
3041         Self::Item: PartialEq<I::Item>,
3042         Self: Sized,
3043     {
3044         self.eq_by(other, |x, y| x == y)
3045     }
3046
3047     /// Determines if the elements of this `Iterator` are equal to those of
3048     /// another with respect to the specified equality function.
3049     ///
3050     /// # Examples
3051     ///
3052     /// Basic usage:
3053     ///
3054     /// ```
3055     /// #![feature(iter_order_by)]
3056     ///
3057     /// let xs = [1, 2, 3, 4];
3058     /// let ys = [1, 4, 9, 16];
3059     ///
3060     /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y));
3061     /// ```
3062     #[unstable(feature = "iter_order_by", issue = "64295")]
3063     fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool
3064     where
3065         Self: Sized,
3066         I: IntoIterator,
3067         F: FnMut(Self::Item, I::Item) -> bool,
3068     {
3069         let mut other = other.into_iter();
3070
3071         loop {
3072             let x = match self.next() {
3073                 None => return other.next().is_none(),
3074                 Some(val) => val,
3075             };
3076
3077             let y = match other.next() {
3078                 None => return false,
3079                 Some(val) => val,
3080             };
3081
3082             if !eq(x, y) {
3083                 return false;
3084             }
3085         }
3086     }
3087
3088     /// Determines if the elements of this `Iterator` are unequal to those of
3089     /// another.
3090     ///
3091     /// # Examples
3092     ///
3093     /// ```
3094     /// assert_eq!([1].iter().ne([1].iter()), false);
3095     /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3096     /// ```
3097     #[stable(feature = "iter_order", since = "1.5.0")]
3098     fn ne<I>(self, other: I) -> bool
3099     where
3100         I: IntoIterator,
3101         Self::Item: PartialEq<I::Item>,
3102         Self: Sized,
3103     {
3104         !self.eq(other)
3105     }
3106
3107     /// Determines if the elements of this `Iterator` are lexicographically
3108     /// less than those of another.
3109     ///
3110     /// # Examples
3111     ///
3112     /// ```
3113     /// assert_eq!([1].iter().lt([1].iter()), false);
3114     /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3115     /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3116     /// ```
3117     #[stable(feature = "iter_order", since = "1.5.0")]
3118     fn lt<I>(self, other: I) -> bool
3119     where
3120         I: IntoIterator,
3121         Self::Item: PartialOrd<I::Item>,
3122         Self: Sized,
3123     {
3124         self.partial_cmp(other) == Some(Ordering::Less)
3125     }
3126
3127     /// Determines if the elements of this `Iterator` are lexicographically
3128     /// less or equal to those of another.
3129     ///
3130     /// # Examples
3131     ///
3132     /// ```
3133     /// assert_eq!([1].iter().le([1].iter()), true);
3134     /// assert_eq!([1].iter().le([1, 2].iter()), true);
3135     /// assert_eq!([1, 2].iter().le([1].iter()), false);
3136     /// ```
3137     #[stable(feature = "iter_order", since = "1.5.0")]
3138     fn le<I>(self, other: I) -> bool
3139     where
3140         I: IntoIterator,
3141         Self::Item: PartialOrd<I::Item>,
3142         Self: Sized,
3143     {
3144         matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3145     }
3146
3147     /// Determines if the elements of this `Iterator` are lexicographically
3148     /// greater than those of another.
3149     ///
3150     /// # Examples
3151     ///
3152     /// ```
3153     /// assert_eq!([1].iter().gt([1].iter()), false);
3154     /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3155     /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3156     /// ```
3157     #[stable(feature = "iter_order", since = "1.5.0")]
3158     fn gt<I>(self, other: I) -> bool
3159     where
3160         I: IntoIterator,
3161         Self::Item: PartialOrd<I::Item>,
3162         Self: Sized,
3163     {
3164         self.partial_cmp(other) == Some(Ordering::Greater)
3165     }
3166
3167     /// Determines if the elements of this `Iterator` are lexicographically
3168     /// greater than or equal to those of another.
3169     ///
3170     /// # Examples
3171     ///
3172     /// ```
3173     /// assert_eq!([1].iter().ge([1].iter()), true);
3174     /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3175     /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3176     /// ```
3177     #[stable(feature = "iter_order", since = "1.5.0")]
3178     fn ge<I>(self, other: I) -> bool
3179     where
3180         I: IntoIterator,
3181         Self::Item: PartialOrd<I::Item>,
3182         Self: Sized,
3183     {
3184         matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3185     }
3186
3187     /// Checks if the elements of this iterator are sorted.
3188     ///
3189     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3190     /// iterator yields exactly zero or one element, `true` is returned.
3191     ///
3192     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3193     /// implies that this function returns `false` if any two consecutive items are not
3194     /// comparable.
3195     ///
3196     /// # Examples
3197     ///
3198     /// ```
3199     /// #![feature(is_sorted)]
3200     ///
3201     /// assert!([1, 2, 2, 9].iter().is_sorted());
3202     /// assert!(![1, 3, 2, 4].iter().is_sorted());
3203     /// assert!([0].iter().is_sorted());
3204     /// assert!(std::iter::empty::<i32>().is_sorted());
3205     /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3206     /// ```
3207     #[inline]
3208     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3209     fn is_sorted(self) -> bool
3210     where
3211         Self: Sized,
3212         Self::Item: PartialOrd,
3213     {
3214         self.is_sorted_by(PartialOrd::partial_cmp)
3215     }
3216
3217     /// Checks if the elements of this iterator are sorted using the given comparator function.
3218     ///
3219     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3220     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
3221     /// [`is_sorted`]; see its documentation for more information.
3222     ///
3223     /// # Examples
3224     ///
3225     /// ```
3226     /// #![feature(is_sorted)]
3227     ///
3228     /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3229     /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3230     /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3231     /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b)));
3232     /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b)));
3233     /// ```
3234     ///
3235     /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3236     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3237     fn is_sorted_by<F>(mut self, mut compare: F) -> bool
3238     where
3239         Self: Sized,
3240         F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3241     {
3242         let mut last = match self.next() {
3243             Some(e) => e,
3244             None => return true,
3245         };
3246
3247         while let Some(curr) = self.next() {
3248             if let Some(Ordering::Greater) | None = compare(&last, &curr) {
3249                 return false;
3250             }
3251             last = curr;
3252         }
3253
3254         true
3255     }
3256
3257     /// Checks if the elements of this iterator are sorted using the given key extraction
3258     /// function.
3259     ///
3260     /// Instead of comparing the iterator's elements directly, this function compares the keys of
3261     /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
3262     /// its documentation for more information.
3263     ///
3264     /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
3265     ///
3266     /// # Examples
3267     ///
3268     /// ```
3269     /// #![feature(is_sorted)]
3270     ///
3271     /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
3272     /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
3273     /// ```
3274     #[inline]
3275     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
3276     fn is_sorted_by_key<F, K>(self, f: F) -> bool
3277     where
3278         Self: Sized,
3279         F: FnMut(Self::Item) -> K,
3280         K: PartialOrd,
3281     {
3282         self.map(f).is_sorted()
3283     }
3284 }
3285
3286 #[stable(feature = "rust1", since = "1.0.0")]
3287 impl<I: Iterator + ?Sized> Iterator for &mut I {
3288     type Item = I::Item;
3289     fn next(&mut self) -> Option<I::Item> {
3290         (**self).next()
3291     }
3292     fn size_hint(&self) -> (usize, Option<usize>) {
3293         (**self).size_hint()
3294     }
3295     fn nth(&mut self, n: usize) -> Option<Self::Item> {
3296         (**self).nth(n)
3297     }
3298 }