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