Skip to main content

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