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