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