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