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