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