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