Movatterモバイル変換


[0]ホーム

URL:


core/iter/traits/
iterator.rs

1usesuper::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};7usecrate::array;8usecrate::cmp::{self, Ordering};9usecrate::num::NonZero;10usecrate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};1112fn_assert_is_dyn_compatible(_:&dynIterator<Item = ()>) {}1314/// A trait for dealing with iterators.15///16/// This is the main iterator trait. For more about the concept of iterators17/// generally, please see the [module-level documentation]. In particular, you18/// may want to know how to [implement `Iterator`][impl].19///20/// [module-level documentation]: crate::iter21/// [impl]: crate::iter#implementing-iterator22#[stable(feature ="rust1", since ="1.0.0")]23#[rustc_on_unimplemented(24    on(25Self="core::ops::range::RangeTo<Idx>",26        note ="you might have meant to use a bounded `Range`"27),28    on(29Self="core::ops::range::RangeToInclusive<Idx>",30        note ="you might have meant to use a bounded `RangeInclusive`"31),32    label ="`{Self}` is not an iterator",33    message ="`{Self}` is not an iterator"34)]35#[doc(notable_trait)]36#[lang ="iterator"]37#[rustc_diagnostic_item ="Iterator"]38#[must_use ="iterators are lazy and do nothing unless consumed"]39pub traitIterator {40/// The type of the elements being iterated over.41#[rustc_diagnostic_item ="IteratorItem"]42    #[stable(feature ="rust1", since ="1.0.0")]43typeItem;4445/// Advances the iterator and returns the next value.46    ///47    /// Returns [`None`] when iteration is finished. Individual iterator48    /// implementations may choose to resume iteration, and so calling `next()`49    /// again may or may not eventually start returning [`Some(Item)`] again at some50    /// point.51    ///52    /// [`Some(Item)`]: Some53    ///54    /// # Examples55    ///56    /// ```57    /// let a = [1, 2, 3];58    ///59    /// let mut iter = a.into_iter();60    ///61    /// // A call to next() returns the next value...62    /// assert_eq!(Some(1), iter.next());63    /// assert_eq!(Some(2), iter.next());64    /// assert_eq!(Some(3), iter.next());65    ///66    /// // ... and then None once it's over.67    /// assert_eq!(None, iter.next());68    ///69    /// // More calls may or may not return `None`. Here, they always will.70    /// assert_eq!(None, iter.next());71    /// assert_eq!(None, iter.next());72    /// ```73#[lang ="next"]74    #[stable(feature ="rust1", since ="1.0.0")]75fnnext(&mutself) ->Option<Self::Item>;7677/// Advances the iterator and returns an array containing the next `N` values.78    ///79    /// If there are not enough elements to fill the array then `Err` is returned80    /// containing an iterator over the remaining elements.81    ///82    /// # Examples83    ///84    /// Basic usage:85    ///86    /// ```87    /// #![feature(iter_next_chunk)]88    ///89    /// let mut iter = "lorem".chars();90    ///91    /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']);              // N is inferred as 292    /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']);         // N is inferred as 393    /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 494    /// ```95    ///96    /// Split a string and get the first three items.97    ///98    /// ```99    /// #![feature(iter_next_chunk)]100    ///101    /// let quote = "not all those who wander are lost";102    /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();103    /// assert_eq!(first, "not");104    /// assert_eq!(second, "all");105    /// assert_eq!(third, "those");106    /// ```107#[inline]108    #[unstable(feature ="iter_next_chunk", reason ="recently added", issue ="98326")]109fnnext_chunk<constN: usize>(110&mutself,111    ) ->Result<[Self::Item; N], array::IntoIter<Self::Item, N>>112where113Self: Sized,114    {115        array::iter_next_chunk(self)116    }117118/// Returns the bounds on the remaining length of the iterator.119    ///120    /// Specifically, `size_hint()` returns a tuple where the first element121    /// is the lower bound, and the second element is the upper bound.122    ///123    /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.124    /// A [`None`] here means that either there is no known upper bound, or the125    /// upper bound is larger than [`usize`].126    ///127    /// # Implementation notes128    ///129    /// It is not enforced that an iterator implementation yields the declared130    /// number of elements. A buggy iterator may yield less than the lower bound131    /// or more than the upper bound of elements.132    ///133    /// `size_hint()` is primarily intended to be used for optimizations such as134    /// reserving space for the elements of the iterator, but must not be135    /// trusted to e.g., omit bounds checks in unsafe code. An incorrect136    /// implementation of `size_hint()` should not lead to memory safety137    /// violations.138    ///139    /// That said, the implementation should provide a correct estimation,140    /// because otherwise it would be a violation of the trait's protocol.141    ///142    /// The default implementation returns <code>(0, [None])</code> which is correct for any143    /// iterator.144    ///145    /// # Examples146    ///147    /// Basic usage:148    ///149    /// ```150    /// let a = [1, 2, 3];151    /// let mut iter = a.iter();152    ///153    /// assert_eq!((3, Some(3)), iter.size_hint());154    /// let _ = iter.next();155    /// assert_eq!((2, Some(2)), iter.size_hint());156    /// ```157    ///158    /// A more complex example:159    ///160    /// ```161    /// // The even numbers in the range of zero to nine.162    /// let iter = (0..10).filter(|x| x % 2 == 0);163    ///164    /// // We might iterate from zero to ten times. Knowing that it's five165    /// // exactly wouldn't be possible without executing filter().166    /// assert_eq!((0, Some(10)), iter.size_hint());167    ///168    /// // Let's add five more numbers with chain()169    /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);170    ///171    /// // now both bounds are increased by five172    /// assert_eq!((5, Some(15)), iter.size_hint());173    /// ```174    ///175    /// Returning `None` for an upper bound:176    ///177    /// ```178    /// // an infinite iterator has no upper bound179    /// // and the maximum possible lower bound180    /// let iter = 0..;181    ///182    /// assert_eq!((usize::MAX, None), iter.size_hint());183    /// ```184#[inline]185    #[stable(feature ="rust1", since ="1.0.0")]186fnsize_hint(&self) -> (usize,Option<usize>) {187        (0,None)188    }189190/// Consumes the iterator, counting the number of iterations and returning it.191    ///192    /// This method will call [`next`] repeatedly until [`None`] is encountered,193    /// returning the number of times it saw [`Some`]. Note that [`next`] has to be194    /// called at least once even if the iterator does not have any elements.195    ///196    /// [`next`]: Iterator::next197    ///198    /// # Overflow Behavior199    ///200    /// The method does no guarding against overflows, so counting elements of201    /// an iterator with more than [`usize::MAX`] elements either produces the202    /// wrong result or panics. If overflow checks are enabled, a panic is203    /// guaranteed.204    ///205    /// # Panics206    ///207    /// This function might panic if the iterator has more than [`usize::MAX`]208    /// elements.209    ///210    /// # Examples211    ///212    /// ```213    /// let a = [1, 2, 3];214    /// assert_eq!(a.iter().count(), 3);215    ///216    /// let a = [1, 2, 3, 4, 5];217    /// assert_eq!(a.iter().count(), 5);218    /// ```219#[inline]220    #[stable(feature ="rust1", since ="1.0.0")]221fncount(self) -> usize222where223Self: Sized,224    {225self.fold(2260,227#[rustc_inherit_overflow_checks]228|count,_| count +1,229        )230    }231232/// Consumes the iterator, returning the last element.233    ///234    /// This method will evaluate the iterator until it returns [`None`]. While235    /// doing so, it keeps track of the current element. After [`None`] is236    /// returned, `last()` will then return the last element it saw.237    ///238    /// # Examples239    ///240    /// ```241    /// let a = [1, 2, 3];242    /// assert_eq!(a.into_iter().last(), Some(3));243    ///244    /// let a = [1, 2, 3, 4, 5];245    /// assert_eq!(a.into_iter().last(), Some(5));246    /// ```247#[inline]248    #[stable(feature ="rust1", since ="1.0.0")]249fnlast(self) ->Option<Self::Item>250where251Self: Sized,252    {253#[inline]254fnsome<T>(_:Option<T>, x: T) ->Option<T> {255Some(x)256        }257258self.fold(None, some)259    }260261/// Advances the iterator by `n` elements.262    ///263    /// This method will eagerly skip `n` elements by calling [`next`] up to `n`264    /// times until [`None`] is encountered.265    ///266    /// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by267    /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,268    /// where `k` is remaining number of steps that could not be advanced because the iterator ran out.269    /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.270    /// Otherwise, `k` is always less than `n`.271    ///272    /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]273    /// can advance its outer iterator until it finds an inner iterator that is not empty, which274    /// then often allows it to return a more accurate `size_hint()` than in its initial state.275    ///276    /// [`Flatten`]: crate::iter::Flatten277    /// [`next`]: Iterator::next278    ///279    /// # Examples280    ///281    /// ```282    /// #![feature(iter_advance_by)]283    ///284    /// use std::num::NonZero;285    ///286    /// let a = [1, 2, 3, 4];287    /// let mut iter = a.into_iter();288    ///289    /// assert_eq!(iter.advance_by(2), Ok(()));290    /// assert_eq!(iter.next(), Some(3));291    /// assert_eq!(iter.advance_by(0), Ok(()));292    /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped293    /// ```294#[inline]295    #[unstable(feature ="iter_advance_by", reason ="recently added", issue ="77404")]296fnadvance_by(&mutself, n: usize) ->Result<(), NonZero<usize>> {297/// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators.298traitSpecAdvanceBy {299fnspec_advance_by(&mutself, n: usize) ->Result<(), NonZero<usize>>;300        }301302impl<I: Iterator +?Sized> SpecAdvanceByforI {303            defaultfnspec_advance_by(&mutself, n: usize) ->Result<(), NonZero<usize>> {304foriin0..n {305ifself.next().is_none() {306// SAFETY: `i` is always less than `n`.307returnErr(unsafe{ NonZero::new_unchecked(n - i) });308                    }309                }310Ok(())311            }312        }313314impl<I: Iterator> SpecAdvanceByforI {315fnspec_advance_by(&mutself, n: usize) ->Result<(), NonZero<usize>> {316letSome(n) = NonZero::new(n)else{317returnOk(());318                };319320letres =self.try_fold(n, |n,_| NonZero::new(n.get() -1));321322matchres {323None=>Ok(()),324Some(n) =>Err(n),325                }326            }327        }328329self.spec_advance_by(n)330    }331332/// Returns the `n`th element of the iterator.333    ///334    /// Like most indexing operations, the count starts from zero, so `nth(0)`335    /// returns the first value, `nth(1)` the second, and so on.336    ///337    /// Note that all preceding elements, as well as the returned element, will be338    /// consumed from the iterator. That means that the preceding elements will be339    /// discarded, and also that calling `nth(0)` multiple times on the same iterator340    /// will return different elements.341    ///342    /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the343    /// iterator.344    ///345    /// # Examples346    ///347    /// Basic usage:348    ///349    /// ```350    /// let a = [1, 2, 3];351    /// assert_eq!(a.into_iter().nth(1), Some(2));352    /// ```353    ///354    /// Calling `nth()` multiple times doesn't rewind the iterator:355    ///356    /// ```357    /// let a = [1, 2, 3];358    ///359    /// let mut iter = a.into_iter();360    ///361    /// assert_eq!(iter.nth(1), Some(2));362    /// assert_eq!(iter.nth(1), None);363    /// ```364    ///365    /// Returning `None` if there are less than `n + 1` elements:366    ///367    /// ```368    /// let a = [1, 2, 3];369    /// assert_eq!(a.into_iter().nth(10), None);370    /// ```371#[inline]372    #[stable(feature ="rust1", since ="1.0.0")]373fnnth(&mutself, n: usize) ->Option<Self::Item> {374self.advance_by(n).ok()?;375self.next()376    }377378/// Creates an iterator starting at the same point, but stepping by379    /// the given amount at each iteration.380    ///381    /// Note 1: The first element of the iterator will always be returned,382    /// regardless of the step given.383    ///384    /// Note 2: The time at which ignored elements are pulled is not fixed.385    /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,386    /// `self.nth(step-1)`, …, but is also free to behave like the sequence387    /// `advance_n_and_return_first(&mut self, step)`,388    /// `advance_n_and_return_first(&mut self, step)`, …389    /// Which way is used may change for some iterators for performance reasons.390    /// The second way will advance the iterator earlier and may consume more items.391    ///392    /// `advance_n_and_return_first` is the equivalent of:393    /// ```394    /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>395    /// where396    ///     I: Iterator,397    /// {398    ///     let next = iter.next();399    ///     if n > 1 {400    ///         iter.nth(n - 2);401    ///     }402    ///     next403    /// }404    /// ```405    ///406    /// # Panics407    ///408    /// The method will panic if the given step is `0`.409    ///410    /// # Examples411    ///412    /// ```413    /// let a = [0, 1, 2, 3, 4, 5];414    /// let mut iter = a.into_iter().step_by(2);415    ///416    /// assert_eq!(iter.next(), Some(0));417    /// assert_eq!(iter.next(), Some(2));418    /// assert_eq!(iter.next(), Some(4));419    /// assert_eq!(iter.next(), None);420    /// ```421#[inline]422    #[stable(feature ="iterator_step_by", since ="1.28.0")]423fnstep_by(self, step: usize) -> StepBy<Self>424where425Self: Sized,426    {427        StepBy::new(self, step)428    }429430/// Takes two iterators and creates a new iterator over both in sequence.431    ///432    /// `chain()` will return a new iterator which will first iterate over433    /// values from the first iterator and then over values from the second434    /// iterator.435    ///436    /// In other words, it links two iterators together, in a chain. 🔗437    ///438    /// [`once`] is commonly used to adapt a single value into a chain of439    /// other kinds of iteration.440    ///441    /// # Examples442    ///443    /// Basic usage:444    ///445    /// ```446    /// let s1 = "abc".chars();447    /// let s2 = "def".chars();448    ///449    /// let mut iter = s1.chain(s2);450    ///451    /// assert_eq!(iter.next(), Some('a'));452    /// assert_eq!(iter.next(), Some('b'));453    /// assert_eq!(iter.next(), Some('c'));454    /// assert_eq!(iter.next(), Some('d'));455    /// assert_eq!(iter.next(), Some('e'));456    /// assert_eq!(iter.next(), Some('f'));457    /// assert_eq!(iter.next(), None);458    /// ```459    ///460    /// Since the argument to `chain()` uses [`IntoIterator`], we can pass461    /// anything that can be converted into an [`Iterator`], not just an462    /// [`Iterator`] itself. For example, arrays (`[T]`) implement463    /// [`IntoIterator`], and so can be passed to `chain()` directly:464    ///465    /// ```466    /// let a1 = [1, 2, 3];467    /// let a2 = [4, 5, 6];468    ///469    /// let mut iter = a1.into_iter().chain(a2);470    ///471    /// assert_eq!(iter.next(), Some(1));472    /// assert_eq!(iter.next(), Some(2));473    /// assert_eq!(iter.next(), Some(3));474    /// assert_eq!(iter.next(), Some(4));475    /// assert_eq!(iter.next(), Some(5));476    /// assert_eq!(iter.next(), Some(6));477    /// assert_eq!(iter.next(), None);478    /// ```479    ///480    /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:481    ///482    /// ```483    /// #[cfg(windows)]484    /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {485    ///     use std::os::windows::ffi::OsStrExt;486    ///     s.encode_wide().chain(std::iter::once(0)).collect()487    /// }488    /// ```489    ///490    /// [`once`]: crate::iter::once491    /// [`OsStr`]: ../../std/ffi/struct.OsStr.html492#[inline]493    #[stable(feature ="rust1", since ="1.0.0")]494fnchain<U>(self, other: U) -> Chain<Self, U::IntoIter>495where496Self: Sized,497        U: IntoIterator<Item =Self::Item>,498    {499        Chain::new(self, other.into_iter())500    }501502/// 'Zips up' two iterators into a single iterator of pairs.503    ///504    /// `zip()` returns a new iterator that will iterate over two other505    /// iterators, returning a tuple where the first element comes from the506    /// first iterator, and the second element comes from the second iterator.507    ///508    /// In other words, it zips two iterators together, into a single one.509    ///510    /// If either iterator returns [`None`], [`next`] from the zipped iterator511    /// will return [`None`].512    /// If the zipped iterator has no more elements to return then each further attempt to advance513    /// it will first try to advance the first iterator at most one time and if it still yielded an item514    /// try to advance the second iterator at most one time.515    ///516    /// To 'undo' the result of zipping up two iterators, see [`unzip`].517    ///518    /// [`unzip`]: Iterator::unzip519    ///520    /// # Examples521    ///522    /// Basic usage:523    ///524    /// ```525    /// let s1 = "abc".chars();526    /// let s2 = "def".chars();527    ///528    /// let mut iter = s1.zip(s2);529    ///530    /// assert_eq!(iter.next(), Some(('a', 'd')));531    /// assert_eq!(iter.next(), Some(('b', 'e')));532    /// assert_eq!(iter.next(), Some(('c', 'f')));533    /// assert_eq!(iter.next(), None);534    /// ```535    ///536    /// Since the argument to `zip()` uses [`IntoIterator`], we can pass537    /// anything that can be converted into an [`Iterator`], not just an538    /// [`Iterator`] itself. For example, arrays (`[T]`) implement539    /// [`IntoIterator`], and so can be passed to `zip()` directly:540    ///541    /// ```542    /// let a1 = [1, 2, 3];543    /// let a2 = [4, 5, 6];544    ///545    /// let mut iter = a1.into_iter().zip(a2);546    ///547    /// assert_eq!(iter.next(), Some((1, 4)));548    /// assert_eq!(iter.next(), Some((2, 5)));549    /// assert_eq!(iter.next(), Some((3, 6)));550    /// assert_eq!(iter.next(), None);551    /// ```552    ///553    /// `zip()` is often used to zip an infinite iterator to a finite one.554    /// This works because the finite iterator will eventually return [`None`],555    /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:556    ///557    /// ```558    /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();559    ///560    /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();561    ///562    /// assert_eq!((0, 'f'), enumerate[0]);563    /// assert_eq!((0, 'f'), zipper[0]);564    ///565    /// assert_eq!((1, 'o'), enumerate[1]);566    /// assert_eq!((1, 'o'), zipper[1]);567    ///568    /// assert_eq!((2, 'o'), enumerate[2]);569    /// assert_eq!((2, 'o'), zipper[2]);570    /// ```571    ///572    /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:573    ///574    /// ```575    /// use std::iter::zip;576    ///577    /// let a = [1, 2, 3];578    /// let b = [2, 3, 4];579    ///580    /// let mut zipped = zip(581    ///     a.into_iter().map(|x| x * 2).skip(1),582    ///     b.into_iter().map(|x| x * 2).skip(1),583    /// );584    ///585    /// assert_eq!(zipped.next(), Some((4, 6)));586    /// assert_eq!(zipped.next(), Some((6, 8)));587    /// assert_eq!(zipped.next(), None);588    /// ```589    ///590    /// compared to:591    ///592    /// ```593    /// # let a = [1, 2, 3];594    /// # let b = [2, 3, 4];595    /// #596    /// let mut zipped = a597    ///     .into_iter()598    ///     .map(|x| x * 2)599    ///     .skip(1)600    ///     .zip(b.into_iter().map(|x| x * 2).skip(1));601    /// #602    /// # assert_eq!(zipped.next(), Some((4, 6)));603    /// # assert_eq!(zipped.next(), Some((6, 8)));604    /// # assert_eq!(zipped.next(), None);605    /// ```606    ///607    /// [`enumerate`]: Iterator::enumerate608    /// [`next`]: Iterator::next609    /// [`zip`]: crate::iter::zip610#[inline]611    #[stable(feature ="rust1", since ="1.0.0")]612fnzip<U>(self, other: U) -> Zip<Self, U::IntoIter>613where614Self: Sized,615        U: IntoIterator,616    {617        Zip::new(self, other.into_iter())618    }619620/// Creates a new iterator which places a copy of `separator` between adjacent621    /// items of the original iterator.622    ///623    /// In case `separator` does not implement [`Clone`] or needs to be624    /// computed every time, use [`intersperse_with`].625    ///626    /// # Examples627    ///628    /// Basic usage:629    ///630    /// ```631    /// #![feature(iter_intersperse)]632    ///633    /// let mut a = [0, 1, 2].into_iter().intersperse(100);634    /// assert_eq!(a.next(), Some(0));   // The first element from `a`.635    /// assert_eq!(a.next(), Some(100)); // The separator.636    /// assert_eq!(a.next(), Some(1));   // The next element from `a`.637    /// assert_eq!(a.next(), Some(100)); // The separator.638    /// assert_eq!(a.next(), Some(2));   // The last element from `a`.639    /// assert_eq!(a.next(), None);       // The iterator is finished.640    /// ```641    ///642    /// `intersperse` can be very useful to join an iterator's items using a common element:643    /// ```644    /// #![feature(iter_intersperse)]645    ///646    /// let words = ["Hello", "World", "!"];647    /// let hello: String = words.into_iter().intersperse(" ").collect();648    /// assert_eq!(hello, "Hello World !");649    /// ```650    ///651    /// [`Clone`]: crate::clone::Clone652    /// [`intersperse_with`]: Iterator::intersperse_with653#[inline]654    #[unstable(feature ="iter_intersperse", reason ="recently added", issue ="79524")]655fnintersperse(self, separator:Self::Item) -> Intersperse<Self>656where657Self: Sized,658Self::Item: Clone,659    {660        Intersperse::new(self, separator)661    }662663/// Creates a new iterator which places an item generated by `separator`664    /// between adjacent items of the original iterator.665    ///666    /// The closure will be called exactly once each time an item is placed667    /// between two adjacent items from the underlying iterator; specifically,668    /// the closure is not called if the underlying iterator yields less than669    /// two items and after the last item is yielded.670    ///671    /// If the iterator's item implements [`Clone`], it may be easier to use672    /// [`intersperse`].673    ///674    /// # Examples675    ///676    /// Basic usage:677    ///678    /// ```679    /// #![feature(iter_intersperse)]680    ///681    /// #[derive(PartialEq, Debug)]682    /// struct NotClone(usize);683    ///684    /// let v = [NotClone(0), NotClone(1), NotClone(2)];685    /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));686    ///687    /// assert_eq!(it.next(), Some(NotClone(0)));  // The first element from `v`.688    /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.689    /// assert_eq!(it.next(), Some(NotClone(1)));  // The next element from `v`.690    /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.691    /// assert_eq!(it.next(), Some(NotClone(2)));  // The last element from `v`.692    /// assert_eq!(it.next(), None);               // The iterator is finished.693    /// ```694    ///695    /// `intersperse_with` can be used in situations where the separator needs696    /// to be computed:697    /// ```698    /// #![feature(iter_intersperse)]699    ///700    /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();701    ///702    /// // The closure mutably borrows its context to generate an item.703    /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();704    /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");705    ///706    /// let result = src.intersperse_with(separator).collect::<String>();707    /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");708    /// ```709    /// [`Clone`]: crate::clone::Clone710    /// [`intersperse`]: Iterator::intersperse711#[inline]712    #[unstable(feature ="iter_intersperse", reason ="recently added", issue ="79524")]713fnintersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>714where715Self: Sized,716        G: FnMut() ->Self::Item,717    {718        IntersperseWith::new(self, separator)719    }720721/// Takes a closure and creates an iterator which calls that closure on each722    /// element.723    ///724    /// `map()` transforms one iterator into another, by means of its argument:725    /// something that implements [`FnMut`]. It produces a new iterator which726    /// calls this closure on each element of the original iterator.727    ///728    /// If you are good at thinking in types, you can think of `map()` like this:729    /// If you have an iterator that gives you elements of some type `A`, and730    /// you want an iterator of some other type `B`, you can use `map()`,731    /// passing a closure that takes an `A` and returns a `B`.732    ///733    /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is734    /// lazy, it is best used when you're already working with other iterators.735    /// If you're doing some sort of looping for a side effect, it's considered736    /// more idiomatic to use [`for`] than `map()`.737    ///738    /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for739    ///740    /// # Examples741    ///742    /// Basic usage:743    ///744    /// ```745    /// let a = [1, 2, 3];746    ///747    /// let mut iter = a.iter().map(|x| 2 * x);748    ///749    /// assert_eq!(iter.next(), Some(2));750    /// assert_eq!(iter.next(), Some(4));751    /// assert_eq!(iter.next(), Some(6));752    /// assert_eq!(iter.next(), None);753    /// ```754    ///755    /// If you're doing some sort of side effect, prefer [`for`] to `map()`:756    ///757    /// ```758    /// # #![allow(unused_must_use)]759    /// // don't do this:760    /// (0..5).map(|x| println!("{x}"));761    ///762    /// // it won't even execute, as it is lazy. Rust will warn you about this.763    ///764    /// // Instead, use a for-loop:765    /// for x in 0..5 {766    ///     println!("{x}");767    /// }768    /// ```769#[rustc_diagnostic_item ="IteratorMap"]770    #[inline]771    #[stable(feature ="rust1", since ="1.0.0")]772fnmap<B, F>(self, f: F) -> Map<Self, F>773where774Self: Sized,775        F: FnMut(Self::Item) -> B,776    {777        Map::new(self, f)778    }779780/// Calls a closure on each element of an iterator.781    ///782    /// This is equivalent to using a [`for`] loop on the iterator, although783    /// `break` and `continue` are not possible from a closure. It's generally784    /// more idiomatic to use a `for` loop, but `for_each` may be more legible785    /// when processing items at the end of longer iterator chains. In some786    /// cases `for_each` may also be faster than a loop, because it will use787    /// internal iteration on adapters like `Chain`.788    ///789    /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for790    ///791    /// # Examples792    ///793    /// Basic usage:794    ///795    /// ```796    /// use std::sync::mpsc::channel;797    ///798    /// let (tx, rx) = channel();799    /// (0..5).map(|x| x * 2 + 1)800    ///       .for_each(move |x| tx.send(x).unwrap());801    ///802    /// let v: Vec<_> = rx.iter().collect();803    /// assert_eq!(v, vec![1, 3, 5, 7, 9]);804    /// ```805    ///806    /// For such a small example, a `for` loop may be cleaner, but `for_each`807    /// might be preferable to keep a functional style with longer iterators:808    ///809    /// ```810    /// (0..5).flat_map(|x| x * 100 .. x * 110)811    ///       .enumerate()812    ///       .filter(|&(i, x)| (i + x) % 3 == 0)813    ///       .for_each(|(i, x)| println!("{i}:{x}"));814    /// ```815#[inline]816    #[stable(feature ="iterator_for_each", since ="1.21.0")]817fnfor_each<F>(self, f: F)818where819Self: Sized,820        F: FnMut(Self::Item),821    {822#[inline]823fncall<T>(mutf:implFnMut(T)) ->implFnMut((), T) {824move|(), item| f(item)825        }826827self.fold((), call(f));828    }829830/// Creates an iterator which uses a closure to determine if an element831    /// should be yielded.832    ///833    /// Given an element the closure must return `true` or `false`. The returned834    /// iterator will yield only the elements for which the closure returns835    /// `true`.836    ///837    /// # Examples838    ///839    /// Basic usage:840    ///841    /// ```842    /// let a = [0i32, 1, 2];843    ///844    /// let mut iter = a.into_iter().filter(|x| x.is_positive());845    ///846    /// assert_eq!(iter.next(), Some(1));847    /// assert_eq!(iter.next(), Some(2));848    /// assert_eq!(iter.next(), None);849    /// ```850    ///851    /// Because the closure passed to `filter()` takes a reference, and many852    /// iterators iterate over references, this leads to a possibly confusing853    /// situation, where the type of the closure is a double reference:854    ///855    /// ```856    /// let s = &[0, 1, 2];857    ///858    /// let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!859    ///860    /// assert_eq!(iter.next(), Some(&2));861    /// assert_eq!(iter.next(), None);862    /// ```863    ///864    /// It's common to instead use destructuring on the argument to strip away one:865    ///866    /// ```867    /// let s = &[0, 1, 2];868    ///869    /// let mut iter = s.iter().filter(|&x| *x > 1); // both & and *870    ///871    /// assert_eq!(iter.next(), Some(&2));872    /// assert_eq!(iter.next(), None);873    /// ```874    ///875    /// or both:876    ///877    /// ```878    /// let s = &[0, 1, 2];879    ///880    /// let mut iter = s.iter().filter(|&&x| x > 1); // two &s881    ///882    /// assert_eq!(iter.next(), Some(&2));883    /// assert_eq!(iter.next(), None);884    /// ```885    ///886    /// of these layers.887    ///888    /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.889#[inline]890    #[stable(feature ="rust1", since ="1.0.0")]891    #[rustc_diagnostic_item ="iter_filter"]892fnfilter<P>(self, predicate: P) -> Filter<Self, P>893where894Self: Sized,895        P: FnMut(&Self::Item) -> bool,896    {897        Filter::new(self, predicate)898    }899900/// Creates an iterator that both filters and maps.901    ///902    /// The returned iterator yields only the `value`s for which the supplied903    /// closure returns `Some(value)`.904    ///905    /// `filter_map` can be used to make chains of [`filter`] and [`map`] more906    /// concise. The example below shows how a `map().filter().map()` can be907    /// shortened to a single call to `filter_map`.908    ///909    /// [`filter`]: Iterator::filter910    /// [`map`]: Iterator::map911    ///912    /// # Examples913    ///914    /// Basic usage:915    ///916    /// ```917    /// let a = ["1", "two", "NaN", "four", "5"];918    ///919    /// let mut iter = a.iter().filter_map(|s| s.parse().ok());920    ///921    /// assert_eq!(iter.next(), Some(1));922    /// assert_eq!(iter.next(), Some(5));923    /// assert_eq!(iter.next(), None);924    /// ```925    ///926    /// Here's the same example, but with [`filter`] and [`map`]:927    ///928    /// ```929    /// let a = ["1", "two", "NaN", "four", "5"];930    /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());931    /// assert_eq!(iter.next(), Some(1));932    /// assert_eq!(iter.next(), Some(5));933    /// assert_eq!(iter.next(), None);934    /// ```935#[inline]936    #[stable(feature ="rust1", since ="1.0.0")]937fnfilter_map<B, F>(self, f: F) -> FilterMap<Self, F>938where939Self: Sized,940        F: FnMut(Self::Item) ->Option<B>,941    {942        FilterMap::new(self, f)943    }944945/// Creates an iterator which gives the current iteration count as well as946    /// the next value.947    ///948    /// The iterator returned yields pairs `(i, val)`, where `i` is the949    /// current index of iteration and `val` is the value returned by the950    /// iterator.951    ///952    /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a953    /// different sized integer, the [`zip`] function provides similar954    /// functionality.955    ///956    /// # Overflow Behavior957    ///958    /// The method does no guarding against overflows, so enumerating more than959    /// [`usize::MAX`] elements either produces the wrong result or panics. If960    /// overflow checks are enabled, a panic is guaranteed.961    ///962    /// # Panics963    ///964    /// The returned iterator might panic if the to-be-returned index would965    /// overflow a [`usize`].966    ///967    /// [`zip`]: Iterator::zip968    ///969    /// # Examples970    ///971    /// ```972    /// let a = ['a', 'b', 'c'];973    ///974    /// let mut iter = a.into_iter().enumerate();975    ///976    /// assert_eq!(iter.next(), Some((0, 'a')));977    /// assert_eq!(iter.next(), Some((1, 'b')));978    /// assert_eq!(iter.next(), Some((2, 'c')));979    /// assert_eq!(iter.next(), None);980    /// ```981#[inline]982    #[stable(feature ="rust1", since ="1.0.0")]983    #[rustc_diagnostic_item ="enumerate_method"]984fnenumerate(self) -> Enumerate<Self>985where986Self: Sized,987    {988        Enumerate::new(self)989    }990991/// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods992    /// to look at the next element of the iterator without consuming it. See993    /// their documentation for more information.994    ///995    /// Note that the underlying iterator is still advanced when [`peek`] or996    /// [`peek_mut`] are called for the first time: In order to retrieve the997    /// next element, [`next`] is called on the underlying iterator, hence any998    /// side effects (i.e. anything other than fetching the next value) of999    /// the [`next`] method will occur.1000    ///1001    ///1002    /// # Examples1003    ///1004    /// Basic usage:1005    ///1006    /// ```1007    /// let xs = [1, 2, 3];1008    ///1009    /// let mut iter = xs.into_iter().peekable();1010    ///1011    /// // peek() lets us see into the future1012    /// assert_eq!(iter.peek(), Some(&1));1013    /// assert_eq!(iter.next(), Some(1));1014    ///1015    /// assert_eq!(iter.next(), Some(2));1016    ///1017    /// // we can peek() multiple times, the iterator won't advance1018    /// assert_eq!(iter.peek(), Some(&3));1019    /// assert_eq!(iter.peek(), Some(&3));1020    ///1021    /// assert_eq!(iter.next(), Some(3));1022    ///1023    /// // after the iterator is finished, so is peek()1024    /// assert_eq!(iter.peek(), None);1025    /// assert_eq!(iter.next(), None);1026    /// ```1027    ///1028    /// Using [`peek_mut`] to mutate the next item without advancing the1029    /// iterator:1030    ///1031    /// ```1032    /// let xs = [1, 2, 3];1033    ///1034    /// let mut iter = xs.into_iter().peekable();1035    ///1036    /// // `peek_mut()` lets us see into the future1037    /// assert_eq!(iter.peek_mut(), Some(&mut 1));1038    /// assert_eq!(iter.peek_mut(), Some(&mut 1));1039    /// assert_eq!(iter.next(), Some(1));1040    ///1041    /// if let Some(p) = iter.peek_mut() {1042    ///     assert_eq!(*p, 2);1043    ///     // put a value into the iterator1044    ///     *p = 1000;1045    /// }1046    ///1047    /// // The value reappears as the iterator continues1048    /// assert_eq!(iter.collect::<Vec<_>>(), vec![1000, 3]);1049    /// ```1050    /// [`peek`]: Peekable::peek1051    /// [`peek_mut`]: Peekable::peek_mut1052    /// [`next`]: Iterator::next1053#[inline]1054    #[stable(feature ="rust1", since ="1.0.0")]1055fnpeekable(self) -> Peekable<Self>1056where1057Self: Sized,1058    {1059        Peekable::new(self)1060    }10611062/// Creates an iterator that [`skip`]s elements based on a predicate.1063    ///1064    /// [`skip`]: Iterator::skip1065    ///1066    /// `skip_while()` takes a closure as an argument. It will call this1067    /// closure on each element of the iterator, and ignore elements1068    /// until it returns `false`.1069    ///1070    /// After `false` is returned, `skip_while()`'s job is over, and the1071    /// rest of the elements are yielded.1072    ///1073    /// # Examples1074    ///1075    /// Basic usage:1076    ///1077    /// ```1078    /// let a = [-1i32, 0, 1];1079    ///1080    /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());1081    ///1082    /// assert_eq!(iter.next(), Some(0));1083    /// assert_eq!(iter.next(), Some(1));1084    /// assert_eq!(iter.next(), None);1085    /// ```1086    ///1087    /// Because the closure passed to `skip_while()` takes a reference, and many1088    /// iterators iterate over references, this leads to a possibly confusing1089    /// situation, where the type of the closure argument is a double reference:1090    ///1091    /// ```1092    /// let s = &[-1, 0, 1];1093    ///1094    /// let mut iter = s.iter().skip_while(|x| **x < 0); // need two *s!1095    ///1096    /// assert_eq!(iter.next(), Some(&0));1097    /// assert_eq!(iter.next(), Some(&1));1098    /// assert_eq!(iter.next(), None);1099    /// ```1100    ///1101    /// Stopping after an initial `false`:1102    ///1103    /// ```1104    /// let a = [-1, 0, 1, -2];1105    ///1106    /// let mut iter = a.into_iter().skip_while(|&x| x < 0);1107    ///1108    /// assert_eq!(iter.next(), Some(0));1109    /// assert_eq!(iter.next(), Some(1));1110    ///1111    /// // while this would have been false, since we already got a false,1112    /// // skip_while() isn't used any more1113    /// assert_eq!(iter.next(), Some(-2));1114    ///1115    /// assert_eq!(iter.next(), None);1116    /// ```1117#[inline]1118    #[doc(alias ="drop_while")]1119    #[stable(feature ="rust1", since ="1.0.0")]1120fnskip_while<P>(self, predicate: P) -> SkipWhile<Self, P>1121where1122Self: Sized,1123        P: FnMut(&Self::Item) -> bool,1124    {1125        SkipWhile::new(self, predicate)1126    }11271128/// Creates an iterator that yields elements based on a predicate.1129    ///1130    /// `take_while()` takes a closure as an argument. It will call this1131    /// closure on each element of the iterator, and yield elements1132    /// while it returns `true`.1133    ///1134    /// After `false` is returned, `take_while()`'s job is over, and the1135    /// rest of the elements are ignored.1136    ///1137    /// # Examples1138    ///1139    /// Basic usage:1140    ///1141    /// ```1142    /// let a = [-1i32, 0, 1];1143    ///1144    /// let mut iter = a.into_iter().take_while(|x| x.is_negative());1145    ///1146    /// assert_eq!(iter.next(), Some(-1));1147    /// assert_eq!(iter.next(), None);1148    /// ```1149    ///1150    /// Because the closure passed to `take_while()` takes a reference, and many1151    /// iterators iterate over references, this leads to a possibly confusing1152    /// situation, where the type of the closure is a double reference:1153    ///1154    /// ```1155    /// let s = &[-1, 0, 1];1156    ///1157    /// let mut iter = s.iter().take_while(|x| **x < 0); // need two *s!1158    ///1159    /// assert_eq!(iter.next(), Some(&-1));1160    /// assert_eq!(iter.next(), None);1161    /// ```1162    ///1163    /// Stopping after an initial `false`:1164    ///1165    /// ```1166    /// let a = [-1, 0, 1, -2];1167    ///1168    /// let mut iter = a.into_iter().take_while(|&x| x < 0);1169    ///1170    /// assert_eq!(iter.next(), Some(-1));1171    ///1172    /// // We have more elements that are less than zero, but since we already1173    /// // got a false, take_while() ignores the remaining elements.1174    /// assert_eq!(iter.next(), None);1175    /// ```1176    ///1177    /// Because `take_while()` needs to look at the value in order to see if it1178    /// should be included or not, consuming iterators will see that it is1179    /// removed:1180    ///1181    /// ```1182    /// let a = [1, 2, 3, 4];1183    /// let mut iter = a.into_iter();1184    ///1185    /// let result: Vec<i32> = iter.by_ref().take_while(|&n| n != 3).collect();1186    ///1187    /// assert_eq!(result, [1, 2]);1188    ///1189    /// let result: Vec<i32> = iter.collect();1190    ///1191    /// assert_eq!(result, [4]);1192    /// ```1193    ///1194    /// The `3` is no longer there, because it was consumed in order to see if1195    /// the iteration should stop, but wasn't placed back into the iterator.1196#[inline]1197    #[stable(feature ="rust1", since ="1.0.0")]1198fntake_while<P>(self, predicate: P) -> TakeWhile<Self, P>1199where1200Self: Sized,1201        P: FnMut(&Self::Item) -> bool,1202    {1203        TakeWhile::new(self, predicate)1204    }12051206/// Creates an iterator that both yields elements based on a predicate and maps.1207    ///1208    /// `map_while()` takes a closure as an argument. It will call this1209    /// closure on each element of the iterator, and yield elements1210    /// while it returns [`Some(_)`][`Some`].1211    ///1212    /// # Examples1213    ///1214    /// Basic usage:1215    ///1216    /// ```1217    /// let a = [-1i32, 4, 0, 1];1218    ///1219    /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));1220    ///1221    /// assert_eq!(iter.next(), Some(-16));1222    /// assert_eq!(iter.next(), Some(4));1223    /// assert_eq!(iter.next(), None);1224    /// ```1225    ///1226    /// Here's the same example, but with [`take_while`] and [`map`]:1227    ///1228    /// [`take_while`]: Iterator::take_while1229    /// [`map`]: Iterator::map1230    ///1231    /// ```1232    /// let a = [-1i32, 4, 0, 1];1233    ///1234    /// let mut iter = a.into_iter()1235    ///                 .map(|x| 16i32.checked_div(x))1236    ///                 .take_while(|x| x.is_some())1237    ///                 .map(|x| x.unwrap());1238    ///1239    /// assert_eq!(iter.next(), Some(-16));1240    /// assert_eq!(iter.next(), Some(4));1241    /// assert_eq!(iter.next(), None);1242    /// ```1243    ///1244    /// Stopping after an initial [`None`]:1245    ///1246    /// ```1247    /// let a = [0, 1, 2, -3, 4, 5, -6];1248    ///1249    /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());1250    /// let vec: Vec<_> = iter.collect();1251    ///1252    /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`1253    /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.1254    /// assert_eq!(vec, [0, 1, 2]);1255    /// ```1256    ///1257    /// Because `map_while()` needs to look at the value in order to see if it1258    /// should be included or not, consuming iterators will see that it is1259    /// removed:1260    ///1261    /// ```1262    /// let a = [1, 2, -3, 4];1263    /// let mut iter = a.into_iter();1264    ///1265    /// let result: Vec<u32> = iter.by_ref()1266    ///                            .map_while(|n| u32::try_from(n).ok())1267    ///                            .collect();1268    ///1269    /// assert_eq!(result, [1, 2]);1270    ///1271    /// let result: Vec<i32> = iter.collect();1272    ///1273    /// assert_eq!(result, [4]);1274    /// ```1275    ///1276    /// The `-3` is no longer there, because it was consumed in order to see if1277    /// the iteration should stop, but wasn't placed back into the iterator.1278    ///1279    /// Note that unlike [`take_while`] this iterator is **not** fused.1280    /// It is also not specified what this iterator returns after the first [`None`] is returned.1281    /// If you need a fused iterator, use [`fuse`].1282    ///1283    /// [`fuse`]: Iterator::fuse1284#[inline]1285    #[stable(feature ="iter_map_while", since ="1.57.0")]1286fnmap_while<B, P>(self, predicate: P) -> MapWhile<Self, P>1287where1288Self: Sized,1289        P: FnMut(Self::Item) ->Option<B>,1290    {1291        MapWhile::new(self, predicate)1292    }12931294/// Creates an iterator that skips the first `n` elements.1295    ///1296    /// `skip(n)` skips elements until `n` elements are skipped or the end of the1297    /// iterator is reached (whichever happens first). After that, all the remaining1298    /// elements are yielded. In particular, if the original iterator is too short,1299    /// then the returned iterator is empty.1300    ///1301    /// Rather than overriding this method directly, instead override the `nth` method.1302    ///1303    /// # Examples1304    ///1305    /// ```1306    /// let a = [1, 2, 3];1307    ///1308    /// let mut iter = a.into_iter().skip(2);1309    ///1310    /// assert_eq!(iter.next(), Some(3));1311    /// assert_eq!(iter.next(), None);1312    /// ```1313#[inline]1314    #[stable(feature ="rust1", since ="1.0.0")]1315fnskip(self, n: usize) -> Skip<Self>1316where1317Self: Sized,1318    {1319        Skip::new(self, n)1320    }13211322/// Creates an iterator that yields the first `n` elements, or fewer1323    /// if the underlying iterator ends sooner.1324    ///1325    /// `take(n)` yields elements until `n` elements are yielded or the end of1326    /// the iterator is reached (whichever happens first).1327    /// The returned iterator is a prefix of length `n` if the original iterator1328    /// contains at least `n` elements, otherwise it contains all of the1329    /// (fewer than `n`) elements of the original iterator.1330    ///1331    /// # Examples1332    ///1333    /// Basic usage:1334    ///1335    /// ```1336    /// let a = [1, 2, 3];1337    ///1338    /// let mut iter = a.into_iter().take(2);1339    ///1340    /// assert_eq!(iter.next(), Some(1));1341    /// assert_eq!(iter.next(), Some(2));1342    /// assert_eq!(iter.next(), None);1343    /// ```1344    ///1345    /// `take()` is often used with an infinite iterator, to make it finite:1346    ///1347    /// ```1348    /// let mut iter = (0..).take(3);1349    ///1350    /// assert_eq!(iter.next(), Some(0));1351    /// assert_eq!(iter.next(), Some(1));1352    /// assert_eq!(iter.next(), Some(2));1353    /// assert_eq!(iter.next(), None);1354    /// ```1355    ///1356    /// If less than `n` elements are available,1357    /// `take` will limit itself to the size of the underlying iterator:1358    ///1359    /// ```1360    /// let v = [1, 2];1361    /// let mut iter = v.into_iter().take(5);1362    /// assert_eq!(iter.next(), Some(1));1363    /// assert_eq!(iter.next(), Some(2));1364    /// assert_eq!(iter.next(), None);1365    /// ```1366    ///1367    /// Use [`by_ref`] to take from the iterator without consuming it, and then1368    /// continue using the original iterator:1369    ///1370    /// ```1371    /// let mut words = ["hello", "world", "of", "Rust"].into_iter();1372    ///1373    /// // Take the first two words.1374    /// let hello_world: Vec<_> = words.by_ref().take(2).collect();1375    /// assert_eq!(hello_world, vec!["hello", "world"]);1376    ///1377    /// // Collect the rest of the words.1378    /// // We can only do this because we used `by_ref` earlier.1379    /// let of_rust: Vec<_> = words.collect();1380    /// assert_eq!(of_rust, vec!["of", "Rust"]);1381    /// ```1382    ///1383    /// [`by_ref`]: Iterator::by_ref1384#[doc(alias ="limit")]1385    #[inline]1386    #[stable(feature ="rust1", since ="1.0.0")]1387fntake(self, n: usize) -> Take<Self>1388where1389Self: Sized,1390    {1391        Take::new(self, n)1392    }13931394/// An iterator adapter which, like [`fold`], holds internal state, but1395    /// unlike [`fold`], produces a new iterator.1396    ///1397    /// [`fold`]: Iterator::fold1398    ///1399    /// `scan()` takes two arguments: an initial value which seeds the internal1400    /// state, and a closure with two arguments, the first being a mutable1401    /// reference to the internal state and the second an iterator element.1402    /// The closure can assign to the internal state to share state between1403    /// iterations.1404    ///1405    /// On iteration, the closure will be applied to each element of the1406    /// iterator and the return value from the closure, an [`Option`], is1407    /// returned by the `next` method. Thus the closure can return1408    /// `Some(value)` to yield `value`, or `None` to end the iteration.1409    ///1410    /// # Examples1411    ///1412    /// ```1413    /// let a = [1, 2, 3, 4];1414    ///1415    /// let mut iter = a.into_iter().scan(1, |state, x| {1416    ///     // each iteration, we'll multiply the state by the element ...1417    ///     *state = *state * x;1418    ///1419    ///     // ... and terminate if the state exceeds 61420    ///     if *state > 6 {1421    ///         return None;1422    ///     }1423    ///     // ... else yield the negation of the state1424    ///     Some(-*state)1425    /// });1426    ///1427    /// assert_eq!(iter.next(), Some(-1));1428    /// assert_eq!(iter.next(), Some(-2));1429    /// assert_eq!(iter.next(), Some(-6));1430    /// assert_eq!(iter.next(), None);1431    /// ```1432#[inline]1433    #[stable(feature ="rust1", since ="1.0.0")]1434fnscan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>1435where1436Self: Sized,1437        F: FnMut(&mutSt,Self::Item) ->Option<B>,1438    {1439        Scan::new(self, initial_state, f)1440    }14411442/// Creates an iterator that works like map, but flattens nested structure.1443    ///1444    /// The [`map`] adapter is very useful, but only when the closure1445    /// argument produces values. If it produces an iterator instead, there's1446    /// an extra layer of indirection. `flat_map()` will remove this extra layer1447    /// on its own.1448    ///1449    /// You can think of `flat_map(f)` as the semantic equivalent1450    /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.1451    ///1452    /// Another way of thinking about `flat_map()`: [`map`]'s closure returns1453    /// one item for each element, and `flat_map()`'s closure returns an1454    /// iterator for each element.1455    ///1456    /// [`map`]: Iterator::map1457    /// [`flatten`]: Iterator::flatten1458    ///1459    /// # Examples1460    ///1461    /// ```1462    /// let words = ["alpha", "beta", "gamma"];1463    ///1464    /// // chars() returns an iterator1465    /// let merged: String = words.iter()1466    ///                           .flat_map(|s| s.chars())1467    ///                           .collect();1468    /// assert_eq!(merged, "alphabetagamma");1469    /// ```1470#[inline]1471    #[stable(feature ="rust1", since ="1.0.0")]1472fnflat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>1473where1474Self: Sized,1475        U: IntoIterator,1476        F: FnMut(Self::Item) -> U,1477    {1478        FlatMap::new(self, f)1479    }14801481/// Creates an iterator that flattens nested structure.1482    ///1483    /// This is useful when you have an iterator of iterators or an iterator of1484    /// things that can be turned into iterators and you want to remove one1485    /// level of indirection.1486    ///1487    /// # Examples1488    ///1489    /// Basic usage:1490    ///1491    /// ```1492    /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];1493    /// let flattened: Vec<_> = data.into_iter().flatten().collect();1494    /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);1495    /// ```1496    ///1497    /// Mapping and then flattening:1498    ///1499    /// ```1500    /// let words = ["alpha", "beta", "gamma"];1501    ///1502    /// // chars() returns an iterator1503    /// let merged: String = words.iter()1504    ///                           .map(|s| s.chars())1505    ///                           .flatten()1506    ///                           .collect();1507    /// assert_eq!(merged, "alphabetagamma");1508    /// ```1509    ///1510    /// You can also rewrite this in terms of [`flat_map()`], which is preferable1511    /// in this case since it conveys intent more clearly:1512    ///1513    /// ```1514    /// let words = ["alpha", "beta", "gamma"];1515    ///1516    /// // chars() returns an iterator1517    /// let merged: String = words.iter()1518    ///                           .flat_map(|s| s.chars())1519    ///                           .collect();1520    /// assert_eq!(merged, "alphabetagamma");1521    /// ```1522    ///1523    /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:1524    ///1525    /// ```1526    /// let options = vec![Some(123), Some(321), None, Some(231)];1527    /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();1528    /// assert_eq!(flattened_options, [123, 321, 231]);1529    ///1530    /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];1531    /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();1532    /// assert_eq!(flattened_results, [123, 321, 231]);1533    /// ```1534    ///1535    /// Flattening only removes one level of nesting at a time:1536    ///1537    /// ```1538    /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];1539    ///1540    /// let d2: Vec<_> = d3.into_iter().flatten().collect();1541    /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);1542    ///1543    /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();1544    /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);1545    /// ```1546    ///1547    /// Here we see that `flatten()` does not perform a "deep" flatten.1548    /// Instead, only one level of nesting is removed. That is, if you1549    /// `flatten()` a three-dimensional array, the result will be1550    /// two-dimensional and not one-dimensional. To get a one-dimensional1551    /// structure, you have to `flatten()` again.1552    ///1553    /// [`flat_map()`]: Iterator::flat_map1554#[inline]1555    #[stable(feature ="iterator_flatten", since ="1.29.0")]1556fnflatten(self) -> Flatten<Self>1557where1558Self: Sized,1559Self::Item: IntoIterator,1560    {1561        Flatten::new(self)1562    }15631564/// Calls the given function `f` for each contiguous window of size `N` over1565    /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],1566    /// the windows during mapping overlap as well.1567    ///1568    /// In the following example, the closure is called three times with the1569    /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.1570    ///1571    /// ```1572    /// #![feature(iter_map_windows)]1573    ///1574    /// let strings = "abcd".chars()1575    ///     .map_windows(|[x, y]| format!("{}+{}", x, y))1576    ///     .collect::<Vec<String>>();1577    ///1578    /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);1579    /// ```1580    ///1581    /// Note that the const parameter `N` is usually inferred by the1582    /// destructured argument in the closure.1583    ///1584    /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of1585    /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an1586    /// empty iterator.1587    ///1588    /// The returned iterator implements [`FusedIterator`], because once `self`1589    /// returns `None`, even if it returns a `Some(T)` again in the next iterations,1590    /// we cannot put it into a contiguous array buffer, and thus the returned iterator1591    /// should be fused.1592    ///1593    /// [`slice::windows()`]: slice::windows1594    /// [`FusedIterator`]: crate::iter::FusedIterator1595    ///1596    /// # Panics1597    ///1598    /// Panics if `N` is zero. This check will most probably get changed to a1599    /// compile time error before this method gets stabilized.1600    ///1601    /// ```should_panic1602    /// #![feature(iter_map_windows)]1603    ///1604    /// let iter = std::iter::repeat(0).map_windows(|&[]| ());1605    /// ```1606    ///1607    /// # Examples1608    ///1609    /// Building the sums of neighboring numbers.1610    ///1611    /// ```1612    /// #![feature(iter_map_windows)]1613    ///1614    /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);1615    /// assert_eq!(it.next(), Some(4));  // 1 + 31616    /// assert_eq!(it.next(), Some(11)); // 3 + 81617    /// assert_eq!(it.next(), Some(9));  // 8 + 11618    /// assert_eq!(it.next(), None);1619    /// ```1620    ///1621    /// Since the elements in the following example implement `Copy`, we can1622    /// just copy the array and get an iterator over the windows.1623    ///1624    /// ```1625    /// #![feature(iter_map_windows)]1626    ///1627    /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);1628    /// assert_eq!(it.next(), Some(['f', 'e', 'r']));1629    /// assert_eq!(it.next(), Some(['e', 'r', 'r']));1630    /// assert_eq!(it.next(), Some(['r', 'r', 'i']));1631    /// assert_eq!(it.next(), Some(['r', 'i', 's']));1632    /// assert_eq!(it.next(), None);1633    /// ```1634    ///1635    /// You can also use this function to check the sortedness of an iterator.1636    /// For the simple case, rather use [`Iterator::is_sorted`].1637    ///1638    /// ```1639    /// #![feature(iter_map_windows)]1640    ///1641    /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()1642    ///     .map_windows(|[a, b]| a <= b);1643    ///1644    /// assert_eq!(it.next(), Some(true));  // 0.5 <= 1.01645    /// assert_eq!(it.next(), Some(true));  // 1.0 <= 3.51646    /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.01647    /// assert_eq!(it.next(), Some(true));  // 3.0 <= 8.51648    /// assert_eq!(it.next(), Some(true));  // 8.5 <= 8.51649    /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN1650    /// assert_eq!(it.next(), None);1651    /// ```1652    ///1653    /// For non-fused iterators, they are fused after `map_windows`.1654    ///1655    /// ```1656    /// #![feature(iter_map_windows)]1657    ///1658    /// #[derive(Default)]1659    /// struct NonFusedIterator {1660    ///     state: i32,1661    /// }1662    ///1663    /// impl Iterator for NonFusedIterator {1664    ///     type Item = i32;1665    ///1666    ///     fn next(&mut self) -> Option<i32> {1667    ///         let val = self.state;1668    ///         self.state = self.state + 1;1669    ///1670    ///         // yields `0..5` first, then only even numbers since `6..`.1671    ///         if val < 5 || val % 2 == 0 {1672    ///             Some(val)1673    ///         } else {1674    ///             None1675    ///         }1676    ///     }1677    /// }1678    ///1679    ///1680    /// let mut iter = NonFusedIterator::default();1681    ///1682    /// // yields 0..5 first.1683    /// assert_eq!(iter.next(), Some(0));1684    /// assert_eq!(iter.next(), Some(1));1685    /// assert_eq!(iter.next(), Some(2));1686    /// assert_eq!(iter.next(), Some(3));1687    /// assert_eq!(iter.next(), Some(4));1688    /// // then we can see our iterator going back and forth1689    /// assert_eq!(iter.next(), None);1690    /// assert_eq!(iter.next(), Some(6));1691    /// assert_eq!(iter.next(), None);1692    /// assert_eq!(iter.next(), Some(8));1693    /// assert_eq!(iter.next(), None);1694    ///1695    /// // however, with `.map_windows()`, it is fused.1696    /// let mut iter = NonFusedIterator::default()1697    ///     .map_windows(|arr: &[_; 2]| *arr);1698    ///1699    /// assert_eq!(iter.next(), Some([0, 1]));1700    /// assert_eq!(iter.next(), Some([1, 2]));1701    /// assert_eq!(iter.next(), Some([2, 3]));1702    /// assert_eq!(iter.next(), Some([3, 4]));1703    /// assert_eq!(iter.next(), None);1704    ///1705    /// // it will always return `None` after the first time.1706    /// assert_eq!(iter.next(), None);1707    /// assert_eq!(iter.next(), None);1708    /// assert_eq!(iter.next(), None);1709    /// ```1710#[inline]1711    #[unstable(feature ="iter_map_windows", reason ="recently added", issue ="87155")]1712fnmap_windows<F, R,constN: usize>(self, f: F) -> MapWindows<Self, F, N>1713where1714Self: Sized,1715        F: FnMut(&[Self::Item; N]) -> R,1716    {1717        MapWindows::new(self, f)1718    }17191720/// Creates an iterator which ends after the first [`None`].1721    ///1722    /// After an iterator returns [`None`], future calls may or may not yield1723    /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a1724    /// [`None`] is given, it will always return [`None`] forever.1725    ///1726    /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement1727    /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly1728    /// if the [`FusedIterator`] trait is improperly implemented.1729    ///1730    /// [`Some(T)`]: Some1731    /// [`FusedIterator`]: crate::iter::FusedIterator1732    ///1733    /// # Examples1734    ///1735    /// ```1736    /// // an iterator which alternates between Some and None1737    /// struct Alternate {1738    ///     state: i32,1739    /// }1740    ///1741    /// impl Iterator for Alternate {1742    ///     type Item = i32;1743    ///1744    ///     fn next(&mut self) -> Option<i32> {1745    ///         let val = self.state;1746    ///         self.state = self.state + 1;1747    ///1748    ///         // if it's even, Some(i32), else None1749    ///         (val % 2 == 0).then_some(val)1750    ///     }1751    /// }1752    ///1753    /// let mut iter = Alternate { state: 0 };1754    ///1755    /// // we can see our iterator going back and forth1756    /// assert_eq!(iter.next(), Some(0));1757    /// assert_eq!(iter.next(), None);1758    /// assert_eq!(iter.next(), Some(2));1759    /// assert_eq!(iter.next(), None);1760    ///1761    /// // however, once we fuse it...1762    /// let mut iter = iter.fuse();1763    ///1764    /// assert_eq!(iter.next(), Some(4));1765    /// assert_eq!(iter.next(), None);1766    ///1767    /// // it will always return `None` after the first time.1768    /// assert_eq!(iter.next(), None);1769    /// assert_eq!(iter.next(), None);1770    /// assert_eq!(iter.next(), None);1771    /// ```1772#[inline]1773    #[stable(feature ="rust1", since ="1.0.0")]1774fnfuse(self) -> Fuse<Self>1775where1776Self: Sized,1777    {1778        Fuse::new(self)1779    }17801781/// Does something with each element of an iterator, passing the value on.1782    ///1783    /// When using iterators, you'll often chain several of them together.1784    /// While working on such code, you might want to check out what's1785    /// happening at various parts in the pipeline. To do that, insert1786    /// a call to `inspect()`.1787    ///1788    /// It's more common for `inspect()` to be used as a debugging tool than to1789    /// exist in your final code, but applications may find it useful in certain1790    /// situations when errors need to be logged before being discarded.1791    ///1792    /// # Examples1793    ///1794    /// Basic usage:1795    ///1796    /// ```1797    /// let a = [1, 4, 2, 3];1798    ///1799    /// // this iterator sequence is complex.1800    /// let sum = a.iter()1801    ///     .cloned()1802    ///     .filter(|x| x % 2 == 0)1803    ///     .fold(0, |sum, i| sum + i);1804    ///1805    /// println!("{sum}");1806    ///1807    /// // let's add some inspect() calls to investigate what's happening1808    /// let sum = a.iter()1809    ///     .cloned()1810    ///     .inspect(|x| println!("about to filter: {x}"))1811    ///     .filter(|x| x % 2 == 0)1812    ///     .inspect(|x| println!("made it through filter: {x}"))1813    ///     .fold(0, |sum, i| sum + i);1814    ///1815    /// println!("{sum}");1816    /// ```1817    ///1818    /// This will print:1819    ///1820    /// ```text1821    /// 61822    /// about to filter: 11823    /// about to filter: 41824    /// made it through filter: 41825    /// about to filter: 21826    /// made it through filter: 21827    /// about to filter: 31828    /// 61829    /// ```1830    ///1831    /// Logging errors before discarding them:1832    ///1833    /// ```1834    /// let lines = ["1", "2", "a"];1835    ///1836    /// let sum: i32 = lines1837    ///     .iter()1838    ///     .map(|line| line.parse::<i32>())1839    ///     .inspect(|num| {1840    ///         if let Err(ref e) = *num {1841    ///             println!("Parsing error: {e}");1842    ///         }1843    ///     })1844    ///     .filter_map(Result::ok)1845    ///     .sum();1846    ///1847    /// println!("Sum: {sum}");1848    /// ```1849    ///1850    /// This will print:1851    ///1852    /// ```text1853    /// Parsing error: invalid digit found in string1854    /// Sum: 31855    /// ```1856#[inline]1857    #[stable(feature ="rust1", since ="1.0.0")]1858fninspect<F>(self, f: F) -> Inspect<Self, F>1859where1860Self: Sized,1861        F: FnMut(&Self::Item),1862    {1863        Inspect::new(self, f)1864    }18651866/// Creates a "by reference" adapter for this instance of `Iterator`.1867    ///1868    /// Consuming method calls (direct or indirect calls to `next`)1869    /// on the "by reference" adapter will consume the original iterator,1870    /// but ownership-taking methods (those with a `self` parameter)1871    /// only take ownership of the "by reference" iterator.1872    ///1873    /// This is useful for applying ownership-taking methods1874    /// (such as `take` in the example below)1875    /// without giving up ownership of the original iterator,1876    /// so you can use the original iterator afterwards.1877    ///1878    /// Uses [impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#impl-Iterator-for-%26mut+I).1879    ///1880    /// # Examples1881    ///1882    /// ```1883    /// let mut words = ["hello", "world", "of", "Rust"].into_iter();1884    ///1885    /// // Take the first two words.1886    /// let hello_world: Vec<_> = words.by_ref().take(2).collect();1887    /// assert_eq!(hello_world, vec!["hello", "world"]);1888    ///1889    /// // Collect the rest of the words.1890    /// // We can only do this because we used `by_ref` earlier.1891    /// let of_rust: Vec<_> = words.collect();1892    /// assert_eq!(of_rust, vec!["of", "Rust"]);1893    /// ```1894#[stable(feature ="rust1", since ="1.0.0")]1895fnby_ref(&mutself) ->&mutSelf1896where1897Self: Sized,1898    {1899self1900}19011902/// Transforms an iterator into a collection.1903    ///1904    /// `collect()` can take anything iterable, and turn it into a relevant1905    /// collection. This is one of the more powerful methods in the standard1906    /// library, used in a variety of contexts.1907    ///1908    /// The most basic pattern in which `collect()` is used is to turn one1909    /// collection into another. You take a collection, call [`iter`] on it,1910    /// do a bunch of transformations, and then `collect()` at the end.1911    ///1912    /// `collect()` can also create instances of types that are not typical1913    /// collections. For example, a [`String`] can be built from [`char`]s,1914    /// and an iterator of [`Result<T, E>`][`Result`] items can be collected1915    /// into `Result<Collection<T>, E>`. See the examples below for more.1916    ///1917    /// Because `collect()` is so general, it can cause problems with type1918    /// inference. As such, `collect()` is one of the few times you'll see1919    /// the syntax affectionately known as the 'turbofish': `::<>`. This1920    /// helps the inference algorithm understand specifically which collection1921    /// you're trying to collect into.1922    ///1923    /// # Examples1924    ///1925    /// Basic usage:1926    ///1927    /// ```1928    /// let a = [1, 2, 3];1929    ///1930    /// let doubled: Vec<i32> = a.iter()1931    ///                          .map(|x| x * 2)1932    ///                          .collect();1933    ///1934    /// assert_eq!(vec![2, 4, 6], doubled);1935    /// ```1936    ///1937    /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because1938    /// we could collect into, for example, a [`VecDeque<T>`] instead:1939    ///1940    /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html1941    ///1942    /// ```1943    /// use std::collections::VecDeque;1944    ///1945    /// let a = [1, 2, 3];1946    ///1947    /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();1948    ///1949    /// assert_eq!(2, doubled[0]);1950    /// assert_eq!(4, doubled[1]);1951    /// assert_eq!(6, doubled[2]);1952    /// ```1953    ///1954    /// Using the 'turbofish' instead of annotating `doubled`:1955    ///1956    /// ```1957    /// let a = [1, 2, 3];1958    ///1959    /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();1960    ///1961    /// assert_eq!(vec![2, 4, 6], doubled);1962    /// ```1963    ///1964    /// Because `collect()` only cares about what you're collecting into, you can1965    /// still use a partial type hint, `_`, with the turbofish:1966    ///1967    /// ```1968    /// let a = [1, 2, 3];1969    ///1970    /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();1971    ///1972    /// assert_eq!(vec![2, 4, 6], doubled);1973    /// ```1974    ///1975    /// Using `collect()` to make a [`String`]:1976    ///1977    /// ```1978    /// let chars = ['g', 'd', 'k', 'k', 'n'];1979    ///1980    /// let hello: String = chars.into_iter()1981    ///     .map(|x| x as u8)1982    ///     .map(|x| (x + 1) as char)1983    ///     .collect();1984    ///1985    /// assert_eq!("hello", hello);1986    /// ```1987    ///1988    /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to1989    /// see if any of them failed:1990    ///1991    /// ```1992    /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];1993    ///1994    /// let result: Result<Vec<_>, &str> = results.into_iter().collect();1995    ///1996    /// // gives us the first error1997    /// assert_eq!(Err("nope"), result);1998    ///1999    /// let results = [Ok(1), Ok(3)];2000    ///2001    /// let result: Result<Vec<_>, &str> = results.into_iter().collect();2002    ///2003    /// // gives us the list of answers2004    /// assert_eq!(Ok(vec![1, 3]), result);2005    /// ```2006    ///2007    /// [`iter`]: Iterator::next2008    /// [`String`]: ../../std/string/struct.String.html2009    /// [`char`]: type@char2010#[inline]2011    #[stable(feature ="rust1", since ="1.0.0")]2012    #[must_use ="if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]2013    #[rustc_diagnostic_item ="iterator_collect_fn"]2014fncollect<B: FromIterator<Self::Item>>(self) -> B2015where2016Self: Sized,2017    {2018// This is too aggressive to turn on for everything all the time, but PR#1379082019        // accidentally noticed that some rustc iterators had malformed `size_hint`s,2020        // so this will help catch such things in debug-assertions-std runners,2021        // even if users won't actually ever see it.2022ifcfg!(debug_assertions) {2023lethint =self.size_hint();2024assert!(hint.1.is_none_or(|high| high >= hint.0),"Malformed size_hint {hint:?}");2025        }20262027        FromIterator::from_iter(self)2028    }20292030/// Fallibly transforms an iterator into a collection, short circuiting if2031    /// a failure is encountered.2032    ///2033    /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible2034    /// conversions during collection. Its main use case is simplifying conversions from2035    /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]2036    /// types (e.g. [`Result`]).2037    ///2038    /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];2039    /// only the inner type produced on `Try::Output` must implement it. Concretely,2040    /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements2041    /// [`FromIterator`], even though [`ControlFlow`] doesn't.2042    ///2043    /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and2044    /// may continue to be used, in which case it will continue iterating starting after the element that2045    /// triggered the failure. See the last example below for an example of how this works.2046    ///2047    /// # Examples2048    /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:2049    /// ```2050    /// #![feature(iterator_try_collect)]2051    ///2052    /// let u = vec![Some(1), Some(2), Some(3)];2053    /// let v = u.into_iter().try_collect::<Vec<i32>>();2054    /// assert_eq!(v, Some(vec![1, 2, 3]));2055    /// ```2056    ///2057    /// Failing to collect in the same way:2058    /// ```2059    /// #![feature(iterator_try_collect)]2060    ///2061    /// let u = vec![Some(1), Some(2), None, Some(3)];2062    /// let v = u.into_iter().try_collect::<Vec<i32>>();2063    /// assert_eq!(v, None);2064    /// ```2065    ///2066    /// A similar example, but with `Result`:2067    /// ```2068    /// #![feature(iterator_try_collect)]2069    ///2070    /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];2071    /// let v = u.into_iter().try_collect::<Vec<i32>>();2072    /// assert_eq!(v, Ok(vec![1, 2, 3]));2073    ///2074    /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];2075    /// let v = u.into_iter().try_collect::<Vec<i32>>();2076    /// assert_eq!(v, Err(()));2077    /// ```2078    ///2079    /// Finally, even [`ControlFlow`] works, despite the fact that it2080    /// doesn't implement [`FromIterator`]. Note also that the iterator can2081    /// continue to be used, even if a failure is encountered:2082    ///2083    /// ```2084    /// #![feature(iterator_try_collect)]2085    ///2086    /// use core::ops::ControlFlow::{Break, Continue};2087    ///2088    /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];2089    /// let mut it = u.into_iter();2090    ///2091    /// let v = it.try_collect::<Vec<_>>();2092    /// assert_eq!(v, Break(3));2093    ///2094    /// let v = it.try_collect::<Vec<_>>();2095    /// assert_eq!(v, Continue(vec![4, 5]));2096    /// ```2097    ///2098    /// [`collect`]: Iterator::collect2099#[inline]2100    #[unstable(feature ="iterator_try_collect", issue ="94047")]2101fntry_collect<B>(&mutself) -> ChangeOutputType<Self::Item, B>2102where2103Self: Sized,2104Self::Item: Try<Residual: Residual<B>>,2105        B: FromIterator<<Self::ItemasTry>::Output>,2106    {2107        try_process(ByRefSized(self), |i| i.collect())2108    }21092110/// Collects all the items from an iterator into a collection.2111    ///2112    /// This method consumes the iterator and adds all its items to the2113    /// passed collection. The collection is then returned, so the call chain2114    /// can be continued.2115    ///2116    /// This is useful when you already have a collection and want to add2117    /// the iterator items to it.2118    ///2119    /// This method is a convenience method to call [Extend::extend](trait.Extend.html),2120    /// but instead of being called on a collection, it's called on an iterator.2121    ///2122    /// # Examples2123    ///2124    /// Basic usage:2125    ///2126    /// ```2127    /// #![feature(iter_collect_into)]2128    ///2129    /// let a = [1, 2, 3];2130    /// let mut vec: Vec::<i32> = vec![0, 1];2131    ///2132    /// a.iter().map(|x| x * 2).collect_into(&mut vec);2133    /// a.iter().map(|x| x * 10).collect_into(&mut vec);2134    ///2135    /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);2136    /// ```2137    ///2138    /// `Vec` can have a manual set capacity to avoid reallocating it:2139    ///2140    /// ```2141    /// #![feature(iter_collect_into)]2142    ///2143    /// let a = [1, 2, 3];2144    /// let mut vec: Vec::<i32> = Vec::with_capacity(6);2145    ///2146    /// a.iter().map(|x| x * 2).collect_into(&mut vec);2147    /// a.iter().map(|x| x * 10).collect_into(&mut vec);2148    ///2149    /// assert_eq!(6, vec.capacity());2150    /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);2151    /// ```2152    ///2153    /// The returned mutable reference can be used to continue the call chain:2154    ///2155    /// ```2156    /// #![feature(iter_collect_into)]2157    ///2158    /// let a = [1, 2, 3];2159    /// let mut vec: Vec::<i32> = Vec::with_capacity(6);2160    ///2161    /// let count = a.iter().collect_into(&mut vec).iter().count();2162    ///2163    /// assert_eq!(count, vec.len());2164    /// assert_eq!(vec, vec![1, 2, 3]);2165    ///2166    /// let count = a.iter().collect_into(&mut vec).iter().count();2167    ///2168    /// assert_eq!(count, vec.len());2169    /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);2170    /// ```2171#[inline]2172    #[unstable(feature ="iter_collect_into", reason ="new API", issue ="94780")]2173fncollect_into<E: Extend<Self::Item>>(self, collection:&mutE) ->&mutE2174where2175Self: Sized,2176    {2177        collection.extend(self);2178        collection2179    }21802181/// Consumes an iterator, creating two collections from it.2182    ///2183    /// The predicate passed to `partition()` can return `true`, or `false`.2184    /// `partition()` returns a pair, all of the elements for which it returned2185    /// `true`, and all of the elements for which it returned `false`.2186    ///2187    /// See also [`is_partitioned()`] and [`partition_in_place()`].2188    ///2189    /// [`is_partitioned()`]: Iterator::is_partitioned2190    /// [`partition_in_place()`]: Iterator::partition_in_place2191    ///2192    /// # Examples2193    ///2194    /// ```2195    /// let a = [1, 2, 3];2196    ///2197    /// let (even, odd): (Vec<_>, Vec<_>) = a2198    ///     .into_iter()2199    ///     .partition(|n| n % 2 == 0);2200    ///2201    /// assert_eq!(even, [2]);2202    /// assert_eq!(odd, [1, 3]);2203    /// ```2204#[stable(feature ="rust1", since ="1.0.0")]2205fnpartition<B, F>(self, f: F) -> (B, B)2206where2207Self: Sized,2208        B: Default + Extend<Self::Item>,2209        F: FnMut(&Self::Item) -> bool,2210    {2211#[inline]2212fnextend<'a, T, B: Extend<T>>(2213mutf:implFnMut(&T) -> bool +'a,2214            left:&'amutB,2215            right:&'amutB,2216        ) ->implFnMut((), T) +'a{2217move|(), x| {2218iff(&x) {2219                    left.extend_one(x);2220                }else{2221                    right.extend_one(x);2222                }2223            }2224        }22252226letmutleft: B = Default::default();2227letmutright: B = Default::default();22282229self.fold((), extend(f,&mutleft,&mutright));22302231        (left, right)2232    }22332234/// Reorders the elements of this iterator *in-place* according to the given predicate,2235    /// such that all those that return `true` precede all those that return `false`.2236    /// Returns the number of `true` elements found.2237    ///2238    /// The relative order of partitioned items is not maintained.2239    ///2240    /// # Current implementation2241    ///2242    /// The current algorithm tries to find the first element for which the predicate evaluates2243    /// to false and the last element for which it evaluates to true, and repeatedly swaps them.2244    ///2245    /// Time complexity: *O*(*n*)2246    ///2247    /// See also [`is_partitioned()`] and [`partition()`].2248    ///2249    /// [`is_partitioned()`]: Iterator::is_partitioned2250    /// [`partition()`]: Iterator::partition2251    ///2252    /// # Examples2253    ///2254    /// ```2255    /// #![feature(iter_partition_in_place)]2256    ///2257    /// let mut a = [1, 2, 3, 4, 5, 6, 7];2258    ///2259    /// // Partition in-place between evens and odds2260    /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);2261    ///2262    /// assert_eq!(i, 3);2263    /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens2264    /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds2265    /// ```2266#[unstable(feature ="iter_partition_in_place", reason ="new API", issue ="62543")]2267fnpartition_in_place<'a, T:'a, P>(mutself,ref mutpredicate: P) -> usize2268where2269Self: Sized + DoubleEndedIterator<Item =&'amutT>,2270        P: FnMut(&T) -> bool,2271    {2272// FIXME: should we worry about the count overflowing? The only way to have more than2273        // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...22742275        // These closure "factory" functions exist to avoid genericity in `Self`.22762277#[inline]2278fnis_false<'a, T>(2279            predicate:&'amutimplFnMut(&T) -> bool,2280            true_count:&'amutusize,2281        ) ->implFnMut(&&mutT) -> bool +'a{2282move|x| {2283letp = predicate(&**x);2284*true_count += pasusize;2285                !p2286            }2287        }22882289#[inline]2290fnis_true<T>(predicate:&mutimplFnMut(&T) -> bool) ->implFnMut(&&mutT) -> bool +'_{2291move|x| predicate(&**x)2292        }22932294// Repeatedly find the first `false` and swap it with the last `true`.2295letmuttrue_count =0;2296while letSome(head) =self.find(is_false(predicate,&muttrue_count)) {2297if letSome(tail) =self.rfind(is_true(predicate)) {2298crate::mem::swap(head, tail);2299                true_count +=1;2300            }else{2301break;2302            }2303        }2304        true_count2305    }23062307/// Checks if the elements of this iterator are partitioned according to the given predicate,2308    /// such that all those that return `true` precede all those that return `false`.2309    ///2310    /// See also [`partition()`] and [`partition_in_place()`].2311    ///2312    /// [`partition()`]: Iterator::partition2313    /// [`partition_in_place()`]: Iterator::partition_in_place2314    ///2315    /// # Examples2316    ///2317    /// ```2318    /// #![feature(iter_is_partitioned)]2319    ///2320    /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));2321    /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));2322    /// ```2323#[unstable(feature ="iter_is_partitioned", reason ="new API", issue ="62544")]2324fnis_partitioned<P>(mutself,mutpredicate: P) -> bool2325where2326Self: Sized,2327        P: FnMut(Self::Item) -> bool,2328    {2329// Either all items test `true`, or the first clause stops at `false`2330        // and we check that there are no more `true` items after that.2331self.all(&mutpredicate) || !self.any(predicate)2332    }23332334/// An iterator method that applies a function as long as it returns2335    /// successfully, producing a single, final value.2336    ///2337    /// `try_fold()` takes two arguments: an initial value, and a closure with2338    /// two arguments: an 'accumulator', and an element. The closure either2339    /// returns successfully, with the value that the accumulator should have2340    /// for the next iteration, or it returns failure, with an error value that2341    /// is propagated back to the caller immediately (short-circuiting).2342    ///2343    /// The initial value is the value the accumulator will have on the first2344    /// call. If applying the closure succeeded against every element of the2345    /// iterator, `try_fold()` returns the final accumulator as success.2346    ///2347    /// Folding is useful whenever you have a collection of something, and want2348    /// to produce a single value from it.2349    ///2350    /// # Note to Implementors2351    ///2352    /// Several of the other (forward) methods have default implementations in2353    /// terms of this one, so try to implement this explicitly if it can2354    /// do something better than the default `for` loop implementation.2355    ///2356    /// In particular, try to have this call `try_fold()` on the internal parts2357    /// from which this iterator is composed. If multiple calls are needed,2358    /// the `?` operator may be convenient for chaining the accumulator value2359    /// along, but beware any invariants that need to be upheld before those2360    /// early returns. This is a `&mut self` method, so iteration needs to be2361    /// resumable after hitting an error here.2362    ///2363    /// # Examples2364    ///2365    /// Basic usage:2366    ///2367    /// ```2368    /// let a = [1, 2, 3];2369    ///2370    /// // the checked sum of all of the elements of the array2371    /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));2372    ///2373    /// assert_eq!(sum, Some(6));2374    /// ```2375    ///2376    /// Short-circuiting:2377    ///2378    /// ```2379    /// let a = [10, 20, 30, 100, 40, 50];2380    /// let mut iter = a.into_iter();2381    ///2382    /// // This sum overflows when adding the 100 element2383    /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));2384    /// assert_eq!(sum, None);2385    ///2386    /// // Because it short-circuited, the remaining elements are still2387    /// // available through the iterator.2388    /// assert_eq!(iter.len(), 2);2389    /// assert_eq!(iter.next(), Some(40));2390    /// ```2391    ///2392    /// While you cannot `break` from a closure, the [`ControlFlow`] type allows2393    /// a similar idea:2394    ///2395    /// ```2396    /// use std::ops::ControlFlow;2397    ///2398    /// let triangular = (1..30).try_fold(0_i8, |prev, x| {2399    ///     if let Some(next) = prev.checked_add(x) {2400    ///         ControlFlow::Continue(next)2401    ///     } else {2402    ///         ControlFlow::Break(prev)2403    ///     }2404    /// });2405    /// assert_eq!(triangular, ControlFlow::Break(120));2406    ///2407    /// let triangular = (1..30).try_fold(0_u64, |prev, x| {2408    ///     if let Some(next) = prev.checked_add(x) {2409    ///         ControlFlow::Continue(next)2410    ///     } else {2411    ///         ControlFlow::Break(prev)2412    ///     }2413    /// });2414    /// assert_eq!(triangular, ControlFlow::Continue(435));2415    /// ```2416#[inline]2417    #[stable(feature ="iterator_try_fold", since ="1.27.0")]2418fntry_fold<B, F, R>(&mutself, init: B,mutf: F) -> R2419where2420Self: Sized,2421        F: FnMut(B,Self::Item) -> R,2422        R: Try<Output = B>,2423    {2424letmutaccum = init;2425while letSome(x) =self.next() {2426            accum = f(accum, x)?;2427        }2428try{ accum }2429    }24302431/// An iterator method that applies a fallible function to each item in the2432    /// iterator, stopping at the first error and returning that error.2433    ///2434    /// This can also be thought of as the fallible form of [`for_each()`]2435    /// or as the stateless version of [`try_fold()`].2436    ///2437    /// [`for_each()`]: Iterator::for_each2438    /// [`try_fold()`]: Iterator::try_fold2439    ///2440    /// # Examples2441    ///2442    /// ```2443    /// use std::fs::rename;2444    /// use std::io::{stdout, Write};2445    /// use std::path::Path;2446    ///2447    /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];2448    ///2449    /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));2450    /// assert!(res.is_ok());2451    ///2452    /// let mut it = data.iter().cloned();2453    /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));2454    /// assert!(res.is_err());2455    /// // It short-circuited, so the remaining items are still in the iterator:2456    /// assert_eq!(it.next(), Some("stale_bread.json"));2457    /// ```2458    ///2459    /// The [`ControlFlow`] type can be used with this method for the situations2460    /// in which you'd use `break` and `continue` in a normal loop:2461    ///2462    /// ```2463    /// use std::ops::ControlFlow;2464    ///2465    /// let r = (2..100).try_for_each(|x| {2466    ///     if 323 % x == 0 {2467    ///         return ControlFlow::Break(x)2468    ///     }2469    ///2470    ///     ControlFlow::Continue(())2471    /// });2472    /// assert_eq!(r, ControlFlow::Break(17));2473    /// ```2474#[inline]2475    #[stable(feature ="iterator_try_fold", since ="1.27.0")]2476fntry_for_each<F, R>(&mutself, f: F) -> R2477where2478Self: Sized,2479        F: FnMut(Self::Item) -> R,2480        R: Try<Output = ()>,2481    {2482#[inline]2483fncall<T, R>(mutf:implFnMut(T) -> R) ->implFnMut((), T) -> R {2484move|(), x| f(x)2485        }24862487self.try_fold((), call(f))2488    }24892490/// Folds every element into an accumulator by applying an operation,2491    /// returning the final result.2492    ///2493    /// `fold()` takes two arguments: an initial value, and a closure with two2494    /// arguments: an 'accumulator', and an element. The closure returns the value that2495    /// the accumulator should have for the next iteration.2496    ///2497    /// The initial value is the value the accumulator will have on the first2498    /// call.2499    ///2500    /// After applying this closure to every element of the iterator, `fold()`2501    /// returns the accumulator.2502    ///2503    /// This operation is sometimes called 'reduce' or 'inject'.2504    ///2505    /// Folding is useful whenever you have a collection of something, and want2506    /// to produce a single value from it.2507    ///2508    /// Note: `fold()`, and similar methods that traverse the entire iterator,2509    /// might not terminate for infinite iterators, even on traits for which a2510    /// result is determinable in finite time.2511    ///2512    /// Note: [`reduce()`] can be used to use the first element as the initial2513    /// value, if the accumulator type and item type is the same.2514    ///2515    /// Note: `fold()` combines elements in a *left-associative* fashion. For associative2516    /// operators like `+`, the order the elements are combined in is not important, but for non-associative2517    /// operators like `-` the order will affect the final result.2518    /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].2519    ///2520    /// # Note to Implementors2521    ///2522    /// Several of the other (forward) methods have default implementations in2523    /// terms of this one, so try to implement this explicitly if it can2524    /// do something better than the default `for` loop implementation.2525    ///2526    /// In particular, try to have this call `fold()` on the internal parts2527    /// from which this iterator is composed.2528    ///2529    /// # Examples2530    ///2531    /// Basic usage:2532    ///2533    /// ```2534    /// let a = [1, 2, 3];2535    ///2536    /// // the sum of all of the elements of the array2537    /// let sum = a.iter().fold(0, |acc, x| acc + x);2538    ///2539    /// assert_eq!(sum, 6);2540    /// ```2541    ///2542    /// Let's walk through each step of the iteration here:2543    ///2544    /// | element | acc | x | result |2545    /// |---------|-----|---|--------|2546    /// |         | 0   |   |        |2547    /// | 1       | 0   | 1 | 1      |2548    /// | 2       | 1   | 2 | 3      |2549    /// | 3       | 3   | 3 | 6      |2550    ///2551    /// And so, our final result, `6`.2552    ///2553    /// This example demonstrates the left-associative nature of `fold()`:2554    /// it builds a string, starting with an initial value2555    /// and continuing with each element from the front until the back:2556    ///2557    /// ```2558    /// let numbers = [1, 2, 3, 4, 5];2559    ///2560    /// let zero = "0".to_string();2561    ///2562    /// let result = numbers.iter().fold(zero, |acc, &x| {2563    ///     format!("({acc} + {x})")2564    /// });2565    ///2566    /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");2567    /// ```2568    /// It's common for people who haven't used iterators a lot to2569    /// use a `for` loop with a list of things to build up a result. Those2570    /// can be turned into `fold()`s:2571    ///2572    /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for2573    ///2574    /// ```2575    /// let numbers = [1, 2, 3, 4, 5];2576    ///2577    /// let mut result = 0;2578    ///2579    /// // for loop:2580    /// for i in &numbers {2581    ///     result = result + i;2582    /// }2583    ///2584    /// // fold:2585    /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);2586    ///2587    /// // they're the same2588    /// assert_eq!(result, result2);2589    /// ```2590    ///2591    /// [`reduce()`]: Iterator::reduce2592#[doc(alias ="inject", alias ="foldl")]2593    #[inline]2594    #[stable(feature ="rust1", since ="1.0.0")]2595fnfold<B, F>(mutself, init: B,mutf: F) -> B2596where2597Self: Sized,2598        F: FnMut(B,Self::Item) -> B,2599    {2600letmutaccum = init;2601while letSome(x) =self.next() {2602            accum = f(accum, x);2603        }2604        accum2605    }26062607/// Reduces the elements to a single one, by repeatedly applying a reducing2608    /// operation.2609    ///2610    /// If the iterator is empty, returns [`None`]; otherwise, returns the2611    /// result of the reduction.2612    ///2613    /// The reducing function is a closure with two arguments: an 'accumulator', and an element.2614    /// For iterators with at least one element, this is the same as [`fold()`]2615    /// with the first element of the iterator as the initial accumulator value, folding2616    /// every subsequent element into it.2617    ///2618    /// [`fold()`]: Iterator::fold2619    ///2620    /// # Example2621    ///2622    /// ```2623    /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);2624    /// assert_eq!(reduced, 45);2625    ///2626    /// // Which is equivalent to doing it with `fold`:2627    /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);2628    /// assert_eq!(reduced, folded);2629    /// ```2630#[inline]2631    #[stable(feature ="iterator_fold_self", since ="1.51.0")]2632fnreduce<F>(mutself, f: F) ->Option<Self::Item>2633where2634Self: Sized,2635        F: FnMut(Self::Item,Self::Item) ->Self::Item,2636    {2637letfirst =self.next()?;2638Some(self.fold(first, f))2639    }26402641/// Reduces the elements to a single one by repeatedly applying a reducing operation. If the2642    /// closure returns a failure, the failure is propagated back to the caller immediately.2643    ///2644    /// The return type of this method depends on the return type of the closure. If the closure2645    /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,2646    /// E>`. If the closure returns `Option<Self::Item>`, then this function will return2647    /// `Option<Option<Self::Item>>`.2648    ///2649    /// When called on an empty iterator, this function will return either `Some(None)` or2650    /// `Ok(None)` depending on the type of the provided closure.2651    ///2652    /// For iterators with at least one element, this is essentially the same as calling2653    /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.2654    ///2655    /// [`try_fold()`]: Iterator::try_fold2656    ///2657    /// # Examples2658    ///2659    /// Safely calculate the sum of a series of numbers:2660    ///2661    /// ```2662    /// #![feature(iterator_try_reduce)]2663    ///2664    /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];2665    /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));2666    /// assert_eq!(sum, Some(Some(58)));2667    /// ```2668    ///2669    /// Determine when a reduction short circuited:2670    ///2671    /// ```2672    /// #![feature(iterator_try_reduce)]2673    ///2674    /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];2675    /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));2676    /// assert_eq!(sum, None);2677    /// ```2678    ///2679    /// Determine when a reduction was not performed because there are no elements:2680    ///2681    /// ```2682    /// #![feature(iterator_try_reduce)]2683    ///2684    /// let numbers: Vec<usize> = Vec::new();2685    /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));2686    /// assert_eq!(sum, Some(None));2687    /// ```2688    ///2689    /// Use a [`Result`] instead of an [`Option`]:2690    ///2691    /// ```2692    /// #![feature(iterator_try_reduce)]2693    ///2694    /// let numbers = vec!["1", "2", "3", "4", "5"];2695    /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =2696    ///     numbers.into_iter().try_reduce(|x, y| {2697    ///         if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }2698    ///     });2699    /// assert_eq!(max, Ok(Some("5")));2700    /// ```2701#[inline]2702    #[unstable(feature ="iterator_try_reduce", reason ="new API", issue ="87053")]2703fntry_reduce<R>(2704&mutself,2705        f:implFnMut(Self::Item,Self::Item) -> R,2706    ) -> ChangeOutputType<R,Option<R::Output>>2707where2708Self: Sized,2709        R: Try<Output =Self::Item, Residual: Residual<Option<Self::Item>>>,2710    {2711letfirst =matchself.next() {2712Some(i) => i,2713None=>returnTry::from_output(None),2714        };27152716matchself.try_fold(first, f).branch() {2717            ControlFlow::Break(r) => FromResidual::from_residual(r),2718            ControlFlow::Continue(i) => Try::from_output(Some(i)),2719        }2720    }27212722/// Tests if every element of the iterator matches a predicate.2723    ///2724    /// `all()` takes a closure that returns `true` or `false`. It applies2725    /// this closure to each element of the iterator, and if they all return2726    /// `true`, then so does `all()`. If any of them return `false`, it2727    /// returns `false`.2728    ///2729    /// `all()` is short-circuiting; in other words, it will stop processing2730    /// as soon as it finds a `false`, given that no matter what else happens,2731    /// the result will also be `false`.2732    ///2733    /// An empty iterator returns `true`.2734    ///2735    /// # Examples2736    ///2737    /// Basic usage:2738    ///2739    /// ```2740    /// let a = [1, 2, 3];2741    ///2742    /// assert!(a.into_iter().all(|x| x > 0));2743    ///2744    /// assert!(!a.into_iter().all(|x| x > 2));2745    /// ```2746    ///2747    /// Stopping at the first `false`:2748    ///2749    /// ```2750    /// let a = [1, 2, 3];2751    ///2752    /// let mut iter = a.into_iter();2753    ///2754    /// assert!(!iter.all(|x| x != 2));2755    ///2756    /// // we can still use `iter`, as there are more elements.2757    /// assert_eq!(iter.next(), Some(3));2758    /// ```2759#[inline]2760    #[stable(feature ="rust1", since ="1.0.0")]2761fnall<F>(&mutself, f: F) -> bool2762where2763Self: Sized,2764        F: FnMut(Self::Item) -> bool,2765    {2766#[inline]2767fncheck<T>(mutf:implFnMut(T) -> bool) ->implFnMut((), T) -> ControlFlow<()> {2768move|(), x| {2769iff(x) { ControlFlow::Continue(()) }else{ ControlFlow::Break(()) }2770            }2771        }2772self.try_fold((), check(f)) == ControlFlow::Continue(())2773    }27742775/// Tests if any element of the iterator matches a predicate.2776    ///2777    /// `any()` takes a closure that returns `true` or `false`. It applies2778    /// this closure to each element of the iterator, and if any of them return2779    /// `true`, then so does `any()`. If they all return `false`, it2780    /// returns `false`.2781    ///2782    /// `any()` is short-circuiting; in other words, it will stop processing2783    /// as soon as it finds a `true`, given that no matter what else happens,2784    /// the result will also be `true`.2785    ///2786    /// An empty iterator returns `false`.2787    ///2788    /// # Examples2789    ///2790    /// Basic usage:2791    ///2792    /// ```2793    /// let a = [1, 2, 3];2794    ///2795    /// assert!(a.into_iter().any(|x| x > 0));2796    ///2797    /// assert!(!a.into_iter().any(|x| x > 5));2798    /// ```2799    ///2800    /// Stopping at the first `true`:2801    ///2802    /// ```2803    /// let a = [1, 2, 3];2804    ///2805    /// let mut iter = a.into_iter();2806    ///2807    /// assert!(iter.any(|x| x != 2));2808    ///2809    /// // we can still use `iter`, as there are more elements.2810    /// assert_eq!(iter.next(), Some(2));2811    /// ```2812#[inline]2813    #[stable(feature ="rust1", since ="1.0.0")]2814fnany<F>(&mutself, f: F) -> bool2815where2816Self: Sized,2817        F: FnMut(Self::Item) -> bool,2818    {2819#[inline]2820fncheck<T>(mutf:implFnMut(T) -> bool) ->implFnMut((), T) -> ControlFlow<()> {2821move|(), x| {2822iff(x) { ControlFlow::Break(()) }else{ ControlFlow::Continue(()) }2823            }2824        }28252826self.try_fold((), check(f)) == ControlFlow::Break(())2827    }28282829/// Searches for an element of an iterator that satisfies a predicate.2830    ///2831    /// `find()` takes a closure that returns `true` or `false`. It applies2832    /// this closure to each element of the iterator, and if any of them return2833    /// `true`, then `find()` returns [`Some(element)`]. If they all return2834    /// `false`, it returns [`None`].2835    ///2836    /// `find()` is short-circuiting; in other words, it will stop processing2837    /// as soon as the closure returns `true`.2838    ///2839    /// Because `find()` takes a reference, and many iterators iterate over2840    /// references, this leads to a possibly confusing situation where the2841    /// argument is a double reference. You can see this effect in the2842    /// examples below, with `&&x`.2843    ///2844    /// If you need the index of the element, see [`position()`].2845    ///2846    /// [`Some(element)`]: Some2847    /// [`position()`]: Iterator::position2848    ///2849    /// # Examples2850    ///2851    /// Basic usage:2852    ///2853    /// ```2854    /// let a = [1, 2, 3];2855    ///2856    /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));2857    /// assert_eq!(a.into_iter().find(|&x| x == 5), None);2858    /// ```2859    ///2860    /// Stopping at the first `true`:2861    ///2862    /// ```2863    /// let a = [1, 2, 3];2864    ///2865    /// let mut iter = a.into_iter();2866    ///2867    /// assert_eq!(iter.find(|&x| x == 2), Some(2));2868    ///2869    /// // we can still use `iter`, as there are more elements.2870    /// assert_eq!(iter.next(), Some(3));2871    /// ```2872    ///2873    /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.2874#[inline]2875    #[stable(feature ="rust1", since ="1.0.0")]2876fnfind<P>(&mutself, predicate: P) ->Option<Self::Item>2877where2878Self: Sized,2879        P: FnMut(&Self::Item) -> bool,2880    {2881#[inline]2882fncheck<T>(mutpredicate:implFnMut(&T) -> bool) ->implFnMut((), T) -> ControlFlow<T> {2883move|(), x| {2884ifpredicate(&x) { ControlFlow::Break(x) }else{ ControlFlow::Continue(()) }2885            }2886        }28872888self.try_fold((), check(predicate)).break_value()2889    }28902891/// Applies function to the elements of iterator and returns2892    /// the first non-none result.2893    ///2894    /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.2895    ///2896    /// # Examples2897    ///2898    /// ```2899    /// let a = ["lol", "NaN", "2", "5"];2900    ///2901    /// let first_number = a.iter().find_map(|s| s.parse().ok());2902    ///2903    /// assert_eq!(first_number, Some(2));2904    /// ```2905#[inline]2906    #[stable(feature ="iterator_find_map", since ="1.30.0")]2907fnfind_map<B, F>(&mutself, f: F) ->Option<B>2908where2909Self: Sized,2910        F: FnMut(Self::Item) ->Option<B>,2911    {2912#[inline]2913fncheck<T, B>(mutf:implFnMut(T) ->Option<B>) ->implFnMut((), T) -> ControlFlow<B> {2914move|(), x|matchf(x) {2915Some(x) => ControlFlow::Break(x),2916None=> ControlFlow::Continue(()),2917            }2918        }29192920self.try_fold((), check(f)).break_value()2921    }29222923/// Applies function to the elements of iterator and returns2924    /// the first true result or the first error.2925    ///2926    /// The return type of this method depends on the return type of the closure.2927    /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.2928    /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.2929    ///2930    /// # Examples2931    ///2932    /// ```2933    /// #![feature(try_find)]2934    ///2935    /// let a = ["1", "2", "lol", "NaN", "5"];2936    ///2937    /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {2938    ///     Ok(s.parse::<i32>()? == search)2939    /// };2940    ///2941    /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));2942    /// assert_eq!(result, Ok(Some("2")));2943    ///2944    /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));2945    /// assert!(result.is_err());2946    /// ```2947    ///2948    /// This also supports other types which implement [`Try`], not just [`Result`].2949    ///2950    /// ```2951    /// #![feature(try_find)]2952    ///2953    /// use std::num::NonZero;2954    ///2955    /// let a = [3, 5, 7, 4, 9, 0, 11u32];2956    /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));2957    /// assert_eq!(result, Some(Some(4)));2958    /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));2959    /// assert_eq!(result, Some(None));2960    /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));2961    /// assert_eq!(result, None);2962    /// ```2963#[inline]2964    #[unstable(feature ="try_find", reason ="new API", issue ="63178")]2965fntry_find<R>(2966&mutself,2967        f:implFnMut(&Self::Item) -> R,2968    ) -> ChangeOutputType<R,Option<Self::Item>>2969where2970Self: Sized,2971        R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,2972    {2973#[inline]2974fncheck<I, V, R>(2975mutf:implFnMut(&I) -> V,2976        ) ->implFnMut((), I) -> ControlFlow<R::TryType>2977where2978V: Try<Output = bool, Residual = R>,2979            R: Residual<Option<I>>,2980        {2981move|(), x|matchf(&x).branch() {2982                ControlFlow::Continue(false) => ControlFlow::Continue(()),2983                ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),2984                ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),2985            }2986        }29872988matchself.try_fold((), check(f)) {2989            ControlFlow::Break(x) => x,2990            ControlFlow::Continue(()) => Try::from_output(None),2991        }2992    }29932994/// Searches for an element in an iterator, returning its index.2995    ///2996    /// `position()` takes a closure that returns `true` or `false`. It applies2997    /// this closure to each element of the iterator, and if one of them2998    /// returns `true`, then `position()` returns [`Some(index)`]. If all of2999    /// them return `false`, it returns [`None`].3000    ///3001    /// `position()` is short-circuiting; in other words, it will stop3002    /// processing as soon as it finds a `true`.3003    ///3004    /// # Overflow Behavior3005    ///3006    /// The method does no guarding against overflows, so if there are more3007    /// than [`usize::MAX`] non-matching elements, it either produces the wrong3008    /// result or panics. If overflow checks are enabled, a panic is3009    /// guaranteed.3010    ///3011    /// # Panics3012    ///3013    /// This function might panic if the iterator has more than `usize::MAX`3014    /// non-matching elements.3015    ///3016    /// [`Some(index)`]: Some3017    ///3018    /// # Examples3019    ///3020    /// Basic usage:3021    ///3022    /// ```3023    /// let a = [1, 2, 3];3024    ///3025    /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));3026    ///3027    /// assert_eq!(a.into_iter().position(|x| x == 5), None);3028    /// ```3029    ///3030    /// Stopping at the first `true`:3031    ///3032    /// ```3033    /// let a = [1, 2, 3, 4];3034    ///3035    /// let mut iter = a.into_iter();3036    ///3037    /// assert_eq!(iter.position(|x| x >= 2), Some(1));3038    ///3039    /// // we can still use `iter`, as there are more elements.3040    /// assert_eq!(iter.next(), Some(3));3041    ///3042    /// // The returned index depends on iterator state3043    /// assert_eq!(iter.position(|x| x == 4), Some(0));3044    ///3045    /// ```3046#[inline]3047    #[stable(feature ="rust1", since ="1.0.0")]3048fnposition<P>(&mutself, predicate: P) ->Option<usize>3049where3050Self: Sized,3051        P: FnMut(Self::Item) -> bool,3052    {3053#[inline]3054fncheck<'a, T>(3055mutpredicate:implFnMut(T) -> bool +'a,3056            acc:&'amutusize,3057        ) ->implFnMut((), T) -> ControlFlow<usize, ()> +'a{3058#[rustc_inherit_overflow_checks]3059move|_, x| {3060ifpredicate(x) {3061                    ControlFlow::Break(*acc)3062                }else{3063*acc +=1;3064                    ControlFlow::Continue(())3065                }3066            }3067        }30683069letmutacc =0;3070self.try_fold((), check(predicate,&mutacc)).break_value()3071    }30723073/// Searches for an element in an iterator from the right, returning its3074    /// index.3075    ///3076    /// `rposition()` takes a closure that returns `true` or `false`. It applies3077    /// this closure to each element of the iterator, starting from the end,3078    /// and if one of them returns `true`, then `rposition()` returns3079    /// [`Some(index)`]. If all of them return `false`, it returns [`None`].3080    ///3081    /// `rposition()` is short-circuiting; in other words, it will stop3082    /// processing as soon as it finds a `true`.3083    ///3084    /// [`Some(index)`]: Some3085    ///3086    /// # Examples3087    ///3088    /// Basic usage:3089    ///3090    /// ```3091    /// let a = [1, 2, 3];3092    ///3093    /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));3094    ///3095    /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);3096    /// ```3097    ///3098    /// Stopping at the first `true`:3099    ///3100    /// ```3101    /// let a = [-1, 2, 3, 4];3102    ///3103    /// let mut iter = a.into_iter();3104    ///3105    /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));3106    ///3107    /// // we can still use `iter`, as there are more elements.3108    /// assert_eq!(iter.next(), Some(-1));3109    /// assert_eq!(iter.next_back(), Some(3));3110    /// ```3111#[inline]3112    #[stable(feature ="rust1", since ="1.0.0")]3113fnrposition<P>(&mutself, predicate: P) ->Option<usize>3114where3115P: FnMut(Self::Item) -> bool,3116Self: Sized + ExactSizeIterator + DoubleEndedIterator,3117    {3118// No need for an overflow check here, because `ExactSizeIterator`3119        // implies that the number of elements fits into a `usize`.3120#[inline]3121fncheck<T>(3122mutpredicate:implFnMut(T) -> bool,3123        ) ->implFnMut(usize, T) -> ControlFlow<usize, usize> {3124move|i, x| {3125leti = i -1;3126ifpredicate(x) { ControlFlow::Break(i) }else{ ControlFlow::Continue(i) }3127            }3128        }31293130letn =self.len();3131self.try_rfold(n, check(predicate)).break_value()3132    }31333134/// Returns the maximum element of an iterator.3135    ///3136    /// If several elements are equally maximum, the last element is3137    /// returned. If the iterator is empty, [`None`] is returned.3138    ///3139    /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being3140    /// incomparable. You can work around this by using [`Iterator::reduce`]:3141    /// ```3142    /// assert_eq!(3143    ///     [2.4, f32::NAN, 1.3]3144    ///         .into_iter()3145    ///         .reduce(f32::max)3146    ///         .unwrap_or(0.),3147    ///     2.43148    /// );3149    /// ```3150    ///3151    /// # Examples3152    ///3153    /// ```3154    /// let a = [1, 2, 3];3155    /// let b: [u32; 0] = [];3156    ///3157    /// assert_eq!(a.into_iter().max(), Some(3));3158    /// assert_eq!(b.into_iter().max(), None);3159    /// ```3160#[inline]3161    #[stable(feature ="rust1", since ="1.0.0")]3162fnmax(self) ->Option<Self::Item>3163where3164Self: Sized,3165Self::Item: Ord,3166    {3167self.max_by(Ord::cmp)3168    }31693170/// Returns the minimum element of an iterator.3171    ///3172    /// If several elements are equally minimum, the first element is returned.3173    /// If the iterator is empty, [`None`] is returned.3174    ///3175    /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being3176    /// incomparable. You can work around this by using [`Iterator::reduce`]:3177    /// ```3178    /// assert_eq!(3179    ///     [2.4, f32::NAN, 1.3]3180    ///         .into_iter()3181    ///         .reduce(f32::min)3182    ///         .unwrap_or(0.),3183    ///     1.33184    /// );3185    /// ```3186    ///3187    /// # Examples3188    ///3189    /// ```3190    /// let a = [1, 2, 3];3191    /// let b: [u32; 0] = [];3192    ///3193    /// assert_eq!(a.into_iter().min(), Some(1));3194    /// assert_eq!(b.into_iter().min(), None);3195    /// ```3196#[inline]3197    #[stable(feature ="rust1", since ="1.0.0")]3198fnmin(self) ->Option<Self::Item>3199where3200Self: Sized,3201Self::Item: Ord,3202    {3203self.min_by(Ord::cmp)3204    }32053206/// Returns the element that gives the maximum value from the3207    /// specified function.3208    ///3209    /// If several elements are equally maximum, the last element is3210    /// returned. If the iterator is empty, [`None`] is returned.3211    ///3212    /// # Examples3213    ///3214    /// ```3215    /// let a = [-3_i32, 0, 1, 5, -10];3216    /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);3217    /// ```3218#[inline]3219    #[stable(feature ="iter_cmp_by_key", since ="1.6.0")]3220fnmax_by_key<B: Ord, F>(self, f: F) ->Option<Self::Item>3221where3222Self: Sized,3223        F: FnMut(&Self::Item) -> B,3224    {3225#[inline]3226fnkey<T, B>(mutf:implFnMut(&T) -> B) ->implFnMut(T) -> (B, T) {3227move|x| (f(&x), x)3228        }32293230#[inline]3231fncompare<T, B: Ord>((x_p,_):&(B, T), (y_p,_):&(B, T)) -> Ordering {3232            x_p.cmp(y_p)3233        }32343235let(_, x) =self.map(key(f)).max_by(compare)?;3236Some(x)3237    }32383239/// Returns the element that gives the maximum value with respect to the3240    /// specified comparison function.3241    ///3242    /// If several elements are equally maximum, the last element is3243    /// returned. If the iterator is empty, [`None`] is returned.3244    ///3245    /// # Examples3246    ///3247    /// ```3248    /// let a = [-3_i32, 0, 1, 5, -10];3249    /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);3250    /// ```3251#[inline]3252    #[stable(feature ="iter_max_by", since ="1.15.0")]3253fnmax_by<F>(self, compare: F) ->Option<Self::Item>3254where3255Self: Sized,3256        F: FnMut(&Self::Item,&Self::Item) -> Ordering,3257    {3258#[inline]3259fnfold<T>(mutcompare:implFnMut(&T,&T) -> Ordering) ->implFnMut(T, T) -> T {3260move|x, y| cmp::max_by(x, y,&mutcompare)3261        }32623263self.reduce(fold(compare))3264    }32653266/// Returns the element that gives the minimum value from the3267    /// specified function.3268    ///3269    /// If several elements are equally minimum, the first element is3270    /// returned. If the iterator is empty, [`None`] is returned.3271    ///3272    /// # Examples3273    ///3274    /// ```3275    /// let a = [-3_i32, 0, 1, 5, -10];3276    /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);3277    /// ```3278#[inline]3279    #[stable(feature ="iter_cmp_by_key", since ="1.6.0")]3280fnmin_by_key<B: Ord, F>(self, f: F) ->Option<Self::Item>3281where3282Self: Sized,3283        F: FnMut(&Self::Item) -> B,3284    {3285#[inline]3286fnkey<T, B>(mutf:implFnMut(&T) -> B) ->implFnMut(T) -> (B, T) {3287move|x| (f(&x), x)3288        }32893290#[inline]3291fncompare<T, B: Ord>((x_p,_):&(B, T), (y_p,_):&(B, T)) -> Ordering {3292            x_p.cmp(y_p)3293        }32943295let(_, x) =self.map(key(f)).min_by(compare)?;3296Some(x)3297    }32983299/// Returns the element that gives the minimum value with respect to the3300    /// specified comparison function.3301    ///3302    /// If several elements are equally minimum, the first element is3303    /// returned. If the iterator is empty, [`None`] is returned.3304    ///3305    /// # Examples3306    ///3307    /// ```3308    /// let a = [-3_i32, 0, 1, 5, -10];3309    /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);3310    /// ```3311#[inline]3312    #[stable(feature ="iter_min_by", since ="1.15.0")]3313fnmin_by<F>(self, compare: F) ->Option<Self::Item>3314where3315Self: Sized,3316        F: FnMut(&Self::Item,&Self::Item) -> Ordering,3317    {3318#[inline]3319fnfold<T>(mutcompare:implFnMut(&T,&T) -> Ordering) ->implFnMut(T, T) -> T {3320move|x, y| cmp::min_by(x, y,&mutcompare)3321        }33223323self.reduce(fold(compare))3324    }33253326/// Reverses an iterator's direction.3327    ///3328    /// Usually, iterators iterate from left to right. After using `rev()`,3329    /// an iterator will instead iterate from right to left.3330    ///3331    /// This is only possible if the iterator has an end, so `rev()` only3332    /// works on [`DoubleEndedIterator`]s.3333    ///3334    /// # Examples3335    ///3336    /// ```3337    /// let a = [1, 2, 3];3338    ///3339    /// let mut iter = a.into_iter().rev();3340    ///3341    /// assert_eq!(iter.next(), Some(3));3342    /// assert_eq!(iter.next(), Some(2));3343    /// assert_eq!(iter.next(), Some(1));3344    ///3345    /// assert_eq!(iter.next(), None);3346    /// ```3347#[inline]3348    #[doc(alias ="reverse")]3349    #[stable(feature ="rust1", since ="1.0.0")]3350fnrev(self) -> Rev<Self>3351where3352Self: Sized + DoubleEndedIterator,3353    {3354        Rev::new(self)3355    }33563357/// Converts an iterator of pairs into a pair of containers.3358    ///3359    /// `unzip()` consumes an entire iterator of pairs, producing two3360    /// collections: one from the left elements of the pairs, and one3361    /// from the right elements.3362    ///3363    /// This function is, in some sense, the opposite of [`zip`].3364    ///3365    /// [`zip`]: Iterator::zip3366    ///3367    /// # Examples3368    ///3369    /// ```3370    /// let a = [(1, 2), (3, 4), (5, 6)];3371    ///3372    /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();3373    ///3374    /// assert_eq!(left, [1, 3, 5]);3375    /// assert_eq!(right, [2, 4, 6]);3376    ///3377    /// // you can also unzip multiple nested tuples at once3378    /// let a = [(1, (2, 3)), (4, (5, 6))];3379    ///3380    /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();3381    /// assert_eq!(x, [1, 4]);3382    /// assert_eq!(y, [2, 5]);3383    /// assert_eq!(z, [3, 6]);3384    /// ```3385#[stable(feature ="rust1", since ="1.0.0")]3386fnunzip<A, B, FromA, FromB>(self) -> (FromA, FromB)3387where3388FromA: Default + Extend<A>,3389        FromB: Default + Extend<B>,3390Self: Sized + Iterator<Item = (A, B)>,3391    {3392letmutunzipped: (FromA, FromB) = Default::default();3393        unzipped.extend(self);3394        unzipped3395    }33963397/// Creates an iterator which copies all of its elements.3398    ///3399    /// This is useful when you have an iterator over `&T`, but you need an3400    /// iterator over `T`.3401    ///3402    /// # Examples3403    ///3404    /// ```3405    /// let a = [1, 2, 3];3406    ///3407    /// let v_copied: Vec<_> = a.iter().copied().collect();3408    ///3409    /// // copied is the same as .map(|&x| x)3410    /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();3411    ///3412    /// assert_eq!(v_copied, [1, 2, 3]);3413    /// assert_eq!(v_map, [1, 2, 3]);3414    /// ```3415#[stable(feature ="iter_copied", since ="1.36.0")]3416    #[rustc_diagnostic_item ="iter_copied"]3417fncopied<'a, T:'a>(self) -> Copied<Self>3418where3419Self: Sized + Iterator<Item =&'aT>,3420        T: Copy,3421    {3422        Copied::new(self)3423    }34243425/// Creates an iterator which [`clone`]s all of its elements.3426    ///3427    /// This is useful when you have an iterator over `&T`, but you need an3428    /// iterator over `T`.3429    ///3430    /// There is no guarantee whatsoever about the `clone` method actually3431    /// being called *or* optimized away. So code should not depend on3432    /// either.3433    ///3434    /// [`clone`]: Clone::clone3435    ///3436    /// # Examples3437    ///3438    /// Basic usage:3439    ///3440    /// ```3441    /// let a = [1, 2, 3];3442    ///3443    /// let v_cloned: Vec<_> = a.iter().cloned().collect();3444    ///3445    /// // cloned is the same as .map(|&x| x), for integers3446    /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();3447    ///3448    /// assert_eq!(v_cloned, [1, 2, 3]);3449    /// assert_eq!(v_map, [1, 2, 3]);3450    /// ```3451    ///3452    /// To get the best performance, try to clone late:3453    ///3454    /// ```3455    /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];3456    /// // don't do this:3457    /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();3458    /// assert_eq!(&[vec![23]], &slower[..]);3459    /// // instead call `cloned` late3460    /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();3461    /// assert_eq!(&[vec![23]], &faster[..]);3462    /// ```3463#[stable(feature ="rust1", since ="1.0.0")]3464    #[rustc_diagnostic_item ="iter_cloned"]3465fncloned<'a, T:'a>(self) -> Cloned<Self>3466where3467Self: Sized + Iterator<Item =&'aT>,3468        T: Clone,3469    {3470        Cloned::new(self)3471    }34723473/// Repeats an iterator endlessly.3474    ///3475    /// Instead of stopping at [`None`], the iterator will instead start again,3476    /// from the beginning. After iterating again, it will start at the3477    /// beginning again. And again. And again. Forever. Note that in case the3478    /// original iterator is empty, the resulting iterator will also be empty.3479    ///3480    /// # Examples3481    ///3482    /// ```3483    /// let a = [1, 2, 3];3484    ///3485    /// let mut iter = a.into_iter().cycle();3486    ///3487    /// loop {3488    ///     assert_eq!(iter.next(), Some(1));3489    ///     assert_eq!(iter.next(), Some(2));3490    ///     assert_eq!(iter.next(), Some(3));3491    /// #   break;3492    /// }3493    /// ```3494#[stable(feature ="rust1", since ="1.0.0")]3495    #[inline]3496fncycle(self) -> Cycle<Self>3497where3498Self: Sized + Clone,3499    {3500        Cycle::new(self)3501    }35023503/// Returns an iterator over `N` elements of the iterator at a time.3504    ///3505    /// The chunks do not overlap. If `N` does not divide the length of the3506    /// iterator, then the last up to `N-1` elements will be omitted and can be3507    /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]3508    /// function of the iterator.3509    ///3510    /// # Panics3511    ///3512    /// Panics if `N` is zero.3513    ///3514    /// # Examples3515    ///3516    /// Basic usage:3517    ///3518    /// ```3519    /// #![feature(iter_array_chunks)]3520    ///3521    /// let mut iter = "lorem".chars().array_chunks();3522    /// assert_eq!(iter.next(), Some(['l', 'o']));3523    /// assert_eq!(iter.next(), Some(['r', 'e']));3524    /// assert_eq!(iter.next(), None);3525    /// assert_eq!(iter.into_remainder().unwrap().as_slice(), &['m']);3526    /// ```3527    ///3528    /// ```3529    /// #![feature(iter_array_chunks)]3530    ///3531    /// let data = [1, 1, 2, -2, 6, 0, 3, 1];3532    /// //          ^-----^  ^------^3533    /// for [x, y, z] in data.iter().array_chunks() {3534    ///     assert_eq!(x + y + z, 4);3535    /// }3536    /// ```3537#[track_caller]3538    #[unstable(feature ="iter_array_chunks", reason ="recently added", issue ="100450")]3539fnarray_chunks<constN: usize>(self) -> ArrayChunks<Self, N>3540where3541Self: Sized,3542    {3543        ArrayChunks::new(self)3544    }35453546/// Sums the elements of an iterator.3547    ///3548    /// Takes each element, adds them together, and returns the result.3549    ///3550    /// An empty iterator returns the *additive identity* ("zero") of the type,3551    /// which is `0` for integers and `-0.0` for floats.3552    ///3553    /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],3554    /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].3555    ///3556    /// # Panics3557    ///3558    /// When calling `sum()` and a primitive integer type is being returned, this3559    /// method will panic if the computation overflows and overflow checks are3560    /// enabled.3561    ///3562    /// # Examples3563    ///3564    /// ```3565    /// let a = [1, 2, 3];3566    /// let sum: i32 = a.iter().sum();3567    ///3568    /// assert_eq!(sum, 6);3569    ///3570    /// let b: Vec<f32> = vec![];3571    /// let sum: f32 = b.iter().sum();3572    /// assert_eq!(sum, -0.0_f32);3573    /// ```3574#[stable(feature ="iter_arith", since ="1.11.0")]3575fnsum<S>(self) -> S3576where3577Self: Sized,3578        S: Sum<Self::Item>,3579    {3580        Sum::sum(self)3581    }35823583/// Iterates over the entire iterator, multiplying all the elements3584    ///3585    /// An empty iterator returns the one value of the type.3586    ///3587    /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],3588    /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].3589    ///3590    /// # Panics3591    ///3592    /// When calling `product()` and a primitive integer type is being returned,3593    /// method will panic if the computation overflows and overflow checks are3594    /// enabled.3595    ///3596    /// # Examples3597    ///3598    /// ```3599    /// fn factorial(n: u32) -> u32 {3600    ///     (1..=n).product()3601    /// }3602    /// assert_eq!(factorial(0), 1);3603    /// assert_eq!(factorial(1), 1);3604    /// assert_eq!(factorial(5), 120);3605    /// ```3606#[stable(feature ="iter_arith", since ="1.11.0")]3607fnproduct<P>(self) -> P3608where3609Self: Sized,3610        P: Product<Self::Item>,3611    {3612        Product::product(self)3613    }36143615/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those3616    /// of another.3617    ///3618    /// # Examples3619    ///3620    /// ```3621    /// use std::cmp::Ordering;3622    ///3623    /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);3624    /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);3625    /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);3626    /// ```3627#[stable(feature ="iter_order", since ="1.5.0")]3628fncmp<I>(self, other: I) -> Ordering3629where3630I: IntoIterator<Item =Self::Item>,3631Self::Item: Ord,3632Self: Sized,3633    {3634self.cmp_by(other, |x, y| x.cmp(&y))3635    }36363637/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those3638    /// of another with respect to the specified comparison function.3639    ///3640    /// # Examples3641    ///3642    /// ```3643    /// #![feature(iter_order_by)]3644    ///3645    /// use std::cmp::Ordering;3646    ///3647    /// let xs = [1, 2, 3, 4];3648    /// let ys = [1, 4, 9, 16];3649    ///3650    /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);3651    /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);3652    /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);3653    /// ```3654#[unstable(feature ="iter_order_by", issue ="64295")]3655fncmp_by<I, F>(self, other: I, cmp: F) -> Ordering3656where3657Self: Sized,3658        I: IntoIterator,3659        F: FnMut(Self::Item, I::Item) -> Ordering,3660    {3661#[inline]3662fncompare<X, Y, F>(mutcmp: F) ->implFnMut(X, Y) -> ControlFlow<Ordering>3663where3664F: FnMut(X, Y) -> Ordering,3665        {3666move|x, y|matchcmp(x, y) {3667                Ordering::Equal => ControlFlow::Continue(()),3668                non_eq => ControlFlow::Break(non_eq),3669            }3670        }36713672matchiter_compare(self, other.into_iter(), compare(cmp)) {3673            ControlFlow::Continue(ord) => ord,3674            ControlFlow::Break(ord) => ord,3675        }3676    }36773678/// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of3679    /// this [`Iterator`] with those of another. The comparison works like short-circuit3680    /// evaluation, returning a result without comparing the remaining elements.3681    /// As soon as an order can be determined, the evaluation stops and a result is returned.3682    ///3683    /// # Examples3684    ///3685    /// ```3686    /// use std::cmp::Ordering;3687    ///3688    /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));3689    /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));3690    /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));3691    /// ```3692    ///3693    /// For floating-point numbers, NaN does not have a total order and will result3694    /// in `None` when compared:3695    ///3696    /// ```3697    /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);3698    /// ```3699    ///3700    /// The results are determined by the order of evaluation.3701    ///3702    /// ```3703    /// use std::cmp::Ordering;3704    ///3705    /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));3706    /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));3707    /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);3708    /// ```3709    ///3710#[stable(feature ="iter_order", since ="1.5.0")]3711fnpartial_cmp<I>(self, other: I) ->Option<Ordering>3712where3713I: IntoIterator,3714Self::Item: PartialOrd<I::Item>,3715Self: Sized,3716    {3717self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))3718    }37193720/// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those3721    /// of another with respect to the specified comparison function.3722    ///3723    /// # Examples3724    ///3725    /// ```3726    /// #![feature(iter_order_by)]3727    ///3728    /// use std::cmp::Ordering;3729    ///3730    /// let xs = [1.0, 2.0, 3.0, 4.0];3731    /// let ys = [1.0, 4.0, 9.0, 16.0];3732    ///3733    /// assert_eq!(3734    ///     xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),3735    ///     Some(Ordering::Less)3736    /// );3737    /// assert_eq!(3738    ///     xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),3739    ///     Some(Ordering::Equal)3740    /// );3741    /// assert_eq!(3742    ///     xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),3743    ///     Some(Ordering::Greater)3744    /// );3745    /// ```3746#[unstable(feature ="iter_order_by", issue ="64295")]3747fnpartial_cmp_by<I, F>(self, other: I, partial_cmp: F) ->Option<Ordering>3748where3749Self: Sized,3750        I: IntoIterator,3751        F: FnMut(Self::Item, I::Item) ->Option<Ordering>,3752    {3753#[inline]3754fncompare<X, Y, F>(mutpartial_cmp: F) ->implFnMut(X, Y) -> ControlFlow<Option<Ordering>>3755where3756F: FnMut(X, Y) ->Option<Ordering>,3757        {3758move|x, y|matchpartial_cmp(x, y) {3759Some(Ordering::Equal) => ControlFlow::Continue(()),3760                non_eq => ControlFlow::Break(non_eq),3761            }3762        }37633764matchiter_compare(self, other.into_iter(), compare(partial_cmp)) {3765            ControlFlow::Continue(ord) =>Some(ord),3766            ControlFlow::Break(ord) => ord,3767        }3768    }37693770/// Determines if the elements of this [`Iterator`] are equal to those of3771    /// another.3772    ///3773    /// # Examples3774    ///3775    /// ```3776    /// assert_eq!([1].iter().eq([1].iter()), true);3777    /// assert_eq!([1].iter().eq([1, 2].iter()), false);3778    /// ```3779#[stable(feature ="iter_order", since ="1.5.0")]3780fneq<I>(self, other: I) -> bool3781where3782I: IntoIterator,3783Self::Item: PartialEq<I::Item>,3784Self: Sized,3785    {3786self.eq_by(other, |x, y| x == y)3787    }37883789/// Determines if the elements of this [`Iterator`] are equal to those of3790    /// another with respect to the specified equality function.3791    ///3792    /// # Examples3793    ///3794    /// ```3795    /// #![feature(iter_order_by)]3796    ///3797    /// let xs = [1, 2, 3, 4];3798    /// let ys = [1, 4, 9, 16];3799    ///3800    /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));3801    /// ```3802#[unstable(feature ="iter_order_by", issue ="64295")]3803fneq_by<I, F>(self, other: I, eq: F) -> bool3804where3805Self: Sized,3806        I: IntoIterator,3807        F: FnMut(Self::Item, I::Item) -> bool,3808    {3809#[inline]3810fncompare<X, Y, F>(muteq: F) ->implFnMut(X, Y) -> ControlFlow<()>3811where3812F: FnMut(X, Y) -> bool,3813        {3814move|x, y| {3815ifeq(x, y) { ControlFlow::Continue(()) }else{ ControlFlow::Break(()) }3816            }3817        }38183819matchiter_compare(self, other.into_iter(), compare(eq)) {3820            ControlFlow::Continue(ord) => ord == Ordering::Equal,3821            ControlFlow::Break(()) =>false,3822        }3823    }38243825/// Determines if the elements of this [`Iterator`] are not equal to those of3826    /// another.3827    ///3828    /// # Examples3829    ///3830    /// ```3831    /// assert_eq!([1].iter().ne([1].iter()), false);3832    /// assert_eq!([1].iter().ne([1, 2].iter()), true);3833    /// ```3834#[stable(feature ="iter_order", since ="1.5.0")]3835fnne<I>(self, other: I) -> bool3836where3837I: IntoIterator,3838Self::Item: PartialEq<I::Item>,3839Self: Sized,3840    {3841        !self.eq(other)3842    }38433844/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)3845    /// less than those of another.3846    ///3847    /// # Examples3848    ///3849    /// ```3850    /// assert_eq!([1].iter().lt([1].iter()), false);3851    /// assert_eq!([1].iter().lt([1, 2].iter()), true);3852    /// assert_eq!([1, 2].iter().lt([1].iter()), false);3853    /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);3854    /// ```3855#[stable(feature ="iter_order", since ="1.5.0")]3856fnlt<I>(self, other: I) -> bool3857where3858I: IntoIterator,3859Self::Item: PartialOrd<I::Item>,3860Self: Sized,3861    {3862self.partial_cmp(other) ==Some(Ordering::Less)3863    }38643865/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)3866    /// less or equal to those of another.3867    ///3868    /// # Examples3869    ///3870    /// ```3871    /// assert_eq!([1].iter().le([1].iter()), true);3872    /// assert_eq!([1].iter().le([1, 2].iter()), true);3873    /// assert_eq!([1, 2].iter().le([1].iter()), false);3874    /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);3875    /// ```3876#[stable(feature ="iter_order", since ="1.5.0")]3877fnle<I>(self, other: I) -> bool3878where3879I: IntoIterator,3880Self::Item: PartialOrd<I::Item>,3881Self: Sized,3882    {3883matches!(self.partial_cmp(other),Some(Ordering::Less | Ordering::Equal))3884    }38853886/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)3887    /// greater than those of another.3888    ///3889    /// # Examples3890    ///3891    /// ```3892    /// assert_eq!([1].iter().gt([1].iter()), false);3893    /// assert_eq!([1].iter().gt([1, 2].iter()), false);3894    /// assert_eq!([1, 2].iter().gt([1].iter()), true);3895    /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);3896    /// ```3897#[stable(feature ="iter_order", since ="1.5.0")]3898fngt<I>(self, other: I) -> bool3899where3900I: IntoIterator,3901Self::Item: PartialOrd<I::Item>,3902Self: Sized,3903    {3904self.partial_cmp(other) ==Some(Ordering::Greater)3905    }39063907/// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)3908    /// greater than or equal to those of another.3909    ///3910    /// # Examples3911    ///3912    /// ```3913    /// assert_eq!([1].iter().ge([1].iter()), true);3914    /// assert_eq!([1].iter().ge([1, 2].iter()), false);3915    /// assert_eq!([1, 2].iter().ge([1].iter()), true);3916    /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);3917    /// ```3918#[stable(feature ="iter_order", since ="1.5.0")]3919fnge<I>(self, other: I) -> bool3920where3921I: IntoIterator,3922Self::Item: PartialOrd<I::Item>,3923Self: Sized,3924    {3925matches!(self.partial_cmp(other),Some(Ordering::Greater | Ordering::Equal))3926    }39273928/// Checks if the elements of this iterator are sorted.3929    ///3930    /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the3931    /// iterator yields exactly zero or one element, `true` is returned.3932    ///3933    /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition3934    /// implies that this function returns `false` if any two consecutive items are not3935    /// comparable.3936    ///3937    /// # Examples3938    ///3939    /// ```3940    /// assert!([1, 2, 2, 9].iter().is_sorted());3941    /// assert!(![1, 3, 2, 4].iter().is_sorted());3942    /// assert!([0].iter().is_sorted());3943    /// assert!(std::iter::empty::<i32>().is_sorted());3944    /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());3945    /// ```3946#[inline]3947    #[stable(feature ="is_sorted", since ="1.82.0")]3948fnis_sorted(self) -> bool3949where3950Self: Sized,3951Self::Item: PartialOrd,3952    {3953self.is_sorted_by(|a, b| a <= b)3954    }39553956/// Checks if the elements of this iterator are sorted using the given comparator function.3957    ///3958    /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`3959    /// function to determine whether two elements are to be considered in sorted order.3960    ///3961    /// # Examples3962    ///3963    /// ```3964    /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));3965    /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));3966    ///3967    /// assert!([0].iter().is_sorted_by(|a, b| true));3968    /// assert!([0].iter().is_sorted_by(|a, b| false));3969    ///3970    /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));3971    /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));3972    /// ```3973#[stable(feature ="is_sorted", since ="1.82.0")]3974fnis_sorted_by<F>(mutself, compare: F) -> bool3975where3976Self: Sized,3977        F: FnMut(&Self::Item,&Self::Item) -> bool,3978    {3979#[inline]3980fncheck<'a, T>(3981            last:&'amutT,3982mutcompare:implFnMut(&T,&T) -> bool +'a,3983        ) ->implFnMut(T) -> bool +'a{3984move|curr| {3985if!compare(&last,&curr) {3986returnfalse;3987                }3988*last = curr;3989true3990}3991        }39923993letmutlast =matchself.next() {3994Some(e) => e,3995None=>returntrue,3996        };39973998self.all(check(&mutlast, compare))3999    }40004001/// Checks if the elements of this iterator are sorted using the given key extraction4002    /// function.4003    ///4004    /// Instead of comparing the iterator's elements directly, this function compares the keys of4005    /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see4006    /// its documentation for more information.4007    ///4008    /// [`is_sorted`]: Iterator::is_sorted4009    ///4010    /// # Examples4011    ///4012    /// ```4013    /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));4014    /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));4015    /// ```4016#[inline]4017    #[stable(feature ="is_sorted", since ="1.82.0")]4018fnis_sorted_by_key<F, K>(self, f: F) -> bool4019where4020Self: Sized,4021        F: FnMut(Self::Item) -> K,4022        K: PartialOrd,4023    {4024self.map(f).is_sorted()4025    }40264027/// See [TrustedRandomAccess][super::super::TrustedRandomAccess]4028// The unusual name is to avoid name collisions in method resolution4029    // see #76479.4030#[inline]4031    #[doc(hidden)]4032    #[unstable(feature ="trusted_random_access", issue ="none")]4033unsafe fn__iterator_get_unchecked(&mutself, _idx: usize) ->Self::Item4034where4035Self: TrustedRandomAccessNoCoerce,4036    {4037unreachable!("Always specialized");4038    }4039}40404041/// Compares two iterators element-wise using the given function.4042///4043/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next4044/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and4045/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,4046/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of4047/// the iterators.4048///4049/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),4050/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).4051#[inline]4052fniter_compare<A, B, F, T>(muta: A,mutb: B, f: F) -> ControlFlow<T, Ordering>4053where4054A: Iterator,4055    B: Iterator,4056    F: FnMut(A::Item, B::Item) -> ControlFlow<T>,4057{4058#[inline]4059fncompare<'a, B, X, T>(4060        b:&'amutB,4061mutf:implFnMut(X, B::Item) -> ControlFlow<T> +'a,4062    ) ->implFnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> +'a4063where4064B: Iterator,4065    {4066move|x|matchb.next() {4067None=> ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),4068Some(y) => f(x, y).map_break(ControlFlow::Break),4069        }4070    }40714072matcha.try_for_each(compare(&mutb, f)) {4073        ControlFlow::Continue(()) => ControlFlow::Continue(matchb.next() {4074None=> Ordering::Equal,4075Some(_) => Ordering::Less,4076        }),4077        ControlFlow::Break(x) => x,4078    }4079}40804081/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].4082///4083/// This implementation passes all method calls on to the original iterator.4084#[stable(feature ="rust1", since ="1.0.0")]4085impl<I: Iterator +?Sized> Iteratorfor&mutI {4086typeItem = I::Item;4087#[inline]4088fnnext(&mutself) ->Option<I::Item> {4089        (**self).next()4090    }4091fnsize_hint(&self) -> (usize,Option<usize>) {4092        (**self).size_hint()4093    }4094fnadvance_by(&mutself, n: usize) ->Result<(), NonZero<usize>> {4095        (**self).advance_by(n)4096    }4097fnnth(&mutself, n: usize) ->Option<Self::Item> {4098        (**self).nth(n)4099    }4100fnfold<B, F>(self, init: B, f: F) -> B4101where4102F: FnMut(B,Self::Item) -> B,4103    {4104self.spec_fold(init, f)4105    }4106fntry_fold<B, F, R>(&mutself, init: B, f: F) -> R4107where4108F: FnMut(B,Self::Item) -> R,4109        R: Try<Output = B>,4110    {4111self.spec_try_fold(init, f)4112    }4113}41144115/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`4116traitIteratorRefSpec: Iterator {4117fnspec_fold<B, F>(self, init: B, f: F) -> B4118where4119F: FnMut(B,Self::Item) -> B;41204121fnspec_try_fold<B, F, R>(&mutself, init: B, f: F) -> R4122where4123F: FnMut(B,Self::Item) -> R,4124        R: Try<Output = B>;4125}41264127impl<I: Iterator +?Sized> IteratorRefSpecfor&mutI {4128    defaultfnspec_fold<B, F>(self, init: B,mutf: F) -> B4129where4130F: FnMut(B,Self::Item) -> B,4131    {4132letmutaccum = init;4133while letSome(x) =self.next() {4134            accum = f(accum, x);4135        }4136        accum4137    }41384139    defaultfnspec_try_fold<B, F, R>(&mutself, init: B,mutf: F) -> R4140where4141F: FnMut(B,Self::Item) -> R,4142        R: Try<Output = B>,4143    {4144letmutaccum = init;4145while letSome(x) =self.next() {4146            accum = f(accum, x)?;4147        }4148try{ accum }4149    }4150}41514152impl<I: Iterator> IteratorRefSpecfor&mutI {4153impl_fold_via_try_fold! { spec_fold -> spec_try_fold }41544155fnspec_try_fold<B, F, R>(&mutself, init: B, f: F) -> R4156where4157F: FnMut(B,Self::Item) -> R,4158        R: Try<Output = B>,4159    {4160        (**self).try_fold(init, f)4161    }4162}

[8]ページ先頭

©2009-2025 Movatter.jp