core/iter/traits/
iterator.rs

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