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