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