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