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