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