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