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