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