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