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