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