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