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