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