]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/traits/iterator.rs
403f3358105325c917fae4fa0277f4dc7be5700e
[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     ///
968     /// # Examples
969     ///
970     /// Basic usage:
971     ///
972     /// ```
973     /// let a = [1, 2, 3];
974     ///
975     /// let mut iter = a.iter().skip(2);
976     ///
977     /// assert_eq!(iter.next(), Some(&3));
978     /// assert_eq!(iter.next(), None);
979     /// ```
980     #[inline]
981     #[stable(feature = "rust1", since = "1.0.0")]
982     fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
983         Skip::new(self, n)
984     }
985
986     /// Creates an iterator that yields its first `n` elements.
987     ///
988     /// # Examples
989     ///
990     /// Basic usage:
991     ///
992     /// ```
993     /// let a = [1, 2, 3];
994     ///
995     /// let mut iter = a.iter().take(2);
996     ///
997     /// assert_eq!(iter.next(), Some(&1));
998     /// assert_eq!(iter.next(), Some(&2));
999     /// assert_eq!(iter.next(), None);
1000     /// ```
1001     ///
1002     /// `take()` is often used with an infinite iterator, to make it finite:
1003     ///
1004     /// ```
1005     /// let mut iter = (0..).take(3);
1006     ///
1007     /// assert_eq!(iter.next(), Some(0));
1008     /// assert_eq!(iter.next(), Some(1));
1009     /// assert_eq!(iter.next(), Some(2));
1010     /// assert_eq!(iter.next(), None);
1011     /// ```
1012     #[inline]
1013     #[stable(feature = "rust1", since = "1.0.0")]
1014     fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1015         Take::new(self, n)
1016     }
1017
1018     /// An iterator adaptor similar to [`fold`] that holds internal state and
1019     /// produces a new iterator.
1020     ///
1021     /// [`fold`]: #method.fold
1022     ///
1023     /// `scan()` takes two arguments: an initial value which seeds the internal
1024     /// state, and a closure with two arguments, the first being a mutable
1025     /// reference to the internal state and the second an iterator element.
1026     /// The closure can assign to the internal state to share state between
1027     /// iterations.
1028     ///
1029     /// On iteration, the closure will be applied to each element of the
1030     /// iterator and the return value from the closure, an [`Option`], is
1031     /// yielded by the iterator.
1032     ///
1033     /// [`Option`]: ../../std/option/enum.Option.html
1034     ///
1035     /// # Examples
1036     ///
1037     /// Basic usage:
1038     ///
1039     /// ```
1040     /// let a = [1, 2, 3];
1041     ///
1042     /// let mut iter = a.iter().scan(1, |state, &x| {
1043     ///     // each iteration, we'll multiply the state by the element
1044     ///     *state = *state * x;
1045     ///
1046     ///     // then, we'll yield the negation of the state
1047     ///     Some(-*state)
1048     /// });
1049     ///
1050     /// assert_eq!(iter.next(), Some(-1));
1051     /// assert_eq!(iter.next(), Some(-2));
1052     /// assert_eq!(iter.next(), Some(-6));
1053     /// assert_eq!(iter.next(), None);
1054     /// ```
1055     #[inline]
1056     #[stable(feature = "rust1", since = "1.0.0")]
1057     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1058         where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1059     {
1060         Scan::new(self, initial_state, f)
1061     }
1062
1063     /// Creates an iterator that works like map, but flattens nested structure.
1064     ///
1065     /// The [`map`] adapter is very useful, but only when the closure
1066     /// argument produces values. If it produces an iterator instead, there's
1067     /// an extra layer of indirection. `flat_map()` will remove this extra layer
1068     /// on its own.
1069     ///
1070     /// You can think of `flat_map(f)` as the semantic equivalent
1071     /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1072     ///
1073     /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1074     /// one item for each element, and `flat_map()`'s closure returns an
1075     /// iterator for each element.
1076     ///
1077     /// [`map`]: #method.map
1078     /// [`flatten`]: #method.flatten
1079     ///
1080     /// # Examples
1081     ///
1082     /// Basic usage:
1083     ///
1084     /// ```
1085     /// let words = ["alpha", "beta", "gamma"];
1086     ///
1087     /// // chars() returns an iterator
1088     /// let merged: String = words.iter()
1089     ///                           .flat_map(|s| s.chars())
1090     ///                           .collect();
1091     /// assert_eq!(merged, "alphabetagamma");
1092     /// ```
1093     #[inline]
1094     #[stable(feature = "rust1", since = "1.0.0")]
1095     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1096         where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1097     {
1098         FlatMap::new(self, f)
1099     }
1100
1101     /// Creates an iterator that flattens nested structure.
1102     ///
1103     /// This is useful when you have an iterator of iterators or an iterator of
1104     /// things that can be turned into iterators and you want to remove one
1105     /// level of indirection.
1106     ///
1107     /// # Examples
1108     ///
1109     /// Basic usage:
1110     ///
1111     /// ```
1112     /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1113     /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
1114     /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
1115     /// ```
1116     ///
1117     /// Mapping and then flattening:
1118     ///
1119     /// ```
1120     /// let words = ["alpha", "beta", "gamma"];
1121     ///
1122     /// // chars() returns an iterator
1123     /// let merged: String = words.iter()
1124     ///                           .map(|s| s.chars())
1125     ///                           .flatten()
1126     ///                           .collect();
1127     /// assert_eq!(merged, "alphabetagamma");
1128     /// ```
1129     ///
1130     /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1131     /// in this case since it conveys intent more clearly:
1132     ///
1133     /// ```
1134     /// let words = ["alpha", "beta", "gamma"];
1135     ///
1136     /// // chars() returns an iterator
1137     /// let merged: String = words.iter()
1138     ///                           .flat_map(|s| s.chars())
1139     ///                           .collect();
1140     /// assert_eq!(merged, "alphabetagamma");
1141     /// ```
1142     ///
1143     /// Flattening once only removes one level of nesting:
1144     ///
1145     /// ```
1146     /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1147     ///
1148     /// let d2 = d3.iter().flatten().collect::<Vec<_>>();
1149     /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
1150     ///
1151     /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
1152     /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
1153     /// ```
1154     ///
1155     /// Here we see that `flatten()` does not perform a "deep" flatten.
1156     /// Instead, only one level of nesting is removed. That is, if you
1157     /// `flatten()` a three-dimensional array the result will be
1158     /// two-dimensional and not one-dimensional. To get a one-dimensional
1159     /// structure, you have to `flatten()` again.
1160     ///
1161     /// [`flat_map()`]: #method.flat_map
1162     #[inline]
1163     #[stable(feature = "iterator_flatten", since = "1.29.0")]
1164     fn flatten(self) -> Flatten<Self>
1165     where Self: Sized, Self::Item: IntoIterator {
1166         Flatten::new(self)
1167     }
1168
1169     /// Creates an iterator which ends after the first [`None`].
1170     ///
1171     /// After an iterator returns [`None`], future calls may or may not yield
1172     /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1173     /// [`None`] is given, it will always return [`None`] forever.
1174     ///
1175     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1176     /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
1177     ///
1178     /// # Examples
1179     ///
1180     /// Basic usage:
1181     ///
1182     /// ```
1183     /// // an iterator which alternates between Some and None
1184     /// struct Alternate {
1185     ///     state: i32,
1186     /// }
1187     ///
1188     /// impl Iterator for Alternate {
1189     ///     type Item = i32;
1190     ///
1191     ///     fn next(&mut self) -> Option<i32> {
1192     ///         let val = self.state;
1193     ///         self.state = self.state + 1;
1194     ///
1195     ///         // if it's even, Some(i32), else None
1196     ///         if val % 2 == 0 {
1197     ///             Some(val)
1198     ///         } else {
1199     ///             None
1200     ///         }
1201     ///     }
1202     /// }
1203     ///
1204     /// let mut iter = Alternate { state: 0 };
1205     ///
1206     /// // we can see our iterator going back and forth
1207     /// assert_eq!(iter.next(), Some(0));
1208     /// assert_eq!(iter.next(), None);
1209     /// assert_eq!(iter.next(), Some(2));
1210     /// assert_eq!(iter.next(), None);
1211     ///
1212     /// // however, once we fuse it...
1213     /// let mut iter = iter.fuse();
1214     ///
1215     /// assert_eq!(iter.next(), Some(4));
1216     /// assert_eq!(iter.next(), None);
1217     ///
1218     /// // it will always return `None` after the first time.
1219     /// assert_eq!(iter.next(), None);
1220     /// assert_eq!(iter.next(), None);
1221     /// assert_eq!(iter.next(), None);
1222     /// ```
1223     #[inline]
1224     #[stable(feature = "rust1", since = "1.0.0")]
1225     fn fuse(self) -> Fuse<Self> where Self: Sized {
1226         Fuse::new(self)
1227     }
1228
1229     /// Do something with each element of an iterator, passing the value on.
1230     ///
1231     /// When using iterators, you'll often chain several of them together.
1232     /// While working on such code, you might want to check out what's
1233     /// happening at various parts in the pipeline. To do that, insert
1234     /// a call to `inspect()`.
1235     ///
1236     /// It's more common for `inspect()` to be used as a debugging tool than to
1237     /// exist in your final code, but applications may find it useful in certain
1238     /// situations when errors need to be logged before being discarded.
1239     ///
1240     /// # Examples
1241     ///
1242     /// Basic usage:
1243     ///
1244     /// ```
1245     /// let a = [1, 4, 2, 3];
1246     ///
1247     /// // this iterator sequence is complex.
1248     /// let sum = a.iter()
1249     ///     .cloned()
1250     ///     .filter(|x| x % 2 == 0)
1251     ///     .fold(0, |sum, i| sum + i);
1252     ///
1253     /// println!("{}", sum);
1254     ///
1255     /// // let's add some inspect() calls to investigate what's happening
1256     /// let sum = a.iter()
1257     ///     .cloned()
1258     ///     .inspect(|x| println!("about to filter: {}", x))
1259     ///     .filter(|x| x % 2 == 0)
1260     ///     .inspect(|x| println!("made it through filter: {}", x))
1261     ///     .fold(0, |sum, i| sum + i);
1262     ///
1263     /// println!("{}", sum);
1264     /// ```
1265     ///
1266     /// This will print:
1267     ///
1268     /// ```text
1269     /// 6
1270     /// about to filter: 1
1271     /// about to filter: 4
1272     /// made it through filter: 4
1273     /// about to filter: 2
1274     /// made it through filter: 2
1275     /// about to filter: 3
1276     /// 6
1277     /// ```
1278     ///
1279     /// Logging errors before discarding them:
1280     ///
1281     /// ```
1282     /// let lines = ["1", "2", "a"];
1283     ///
1284     /// let sum: i32 = lines
1285     ///     .iter()
1286     ///     .map(|line| line.parse::<i32>())
1287     ///     .inspect(|num| {
1288     ///         if let Err(ref e) = *num {
1289     ///             println!("Parsing error: {}", e);
1290     ///         }
1291     ///     })
1292     ///     .filter_map(Result::ok)
1293     ///     .sum();
1294     ///
1295     /// println!("Sum: {}", sum);
1296     /// ```
1297     ///
1298     /// This will print:
1299     ///
1300     /// ```text
1301     /// Parsing error: invalid digit found in string
1302     /// Sum: 3
1303     /// ```
1304     #[inline]
1305     #[stable(feature = "rust1", since = "1.0.0")]
1306     fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1307         Self: Sized, F: FnMut(&Self::Item),
1308     {
1309         Inspect::new(self, f)
1310     }
1311
1312     /// Borrows an iterator, rather than consuming it.
1313     ///
1314     /// This is useful to allow applying iterator adaptors while still
1315     /// retaining ownership of the original iterator.
1316     ///
1317     /// # Examples
1318     ///
1319     /// Basic usage:
1320     ///
1321     /// ```
1322     /// let a = [1, 2, 3];
1323     ///
1324     /// let iter = a.into_iter();
1325     ///
1326     /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
1327     ///
1328     /// assert_eq!(sum, 6);
1329     ///
1330     /// // if we try to use iter again, it won't work. The following line
1331     /// // gives "error: use of moved value: `iter`
1332     /// // assert_eq!(iter.next(), None);
1333     ///
1334     /// // let's try that again
1335     /// let a = [1, 2, 3];
1336     ///
1337     /// let mut iter = a.into_iter();
1338     ///
1339     /// // instead, we add in a .by_ref()
1340     /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
1341     ///
1342     /// assert_eq!(sum, 3);
1343     ///
1344     /// // now this is just fine:
1345     /// assert_eq!(iter.next(), Some(&3));
1346     /// assert_eq!(iter.next(), None);
1347     /// ```
1348     #[stable(feature = "rust1", since = "1.0.0")]
1349     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1350
1351     /// Transforms an iterator into a collection.
1352     ///
1353     /// `collect()` can take anything iterable, and turn it into a relevant
1354     /// collection. This is one of the more powerful methods in the standard
1355     /// library, used in a variety of contexts.
1356     ///
1357     /// The most basic pattern in which `collect()` is used is to turn one
1358     /// collection into another. You take a collection, call [`iter`] on it,
1359     /// do a bunch of transformations, and then `collect()` at the end.
1360     ///
1361     /// One of the keys to `collect()`'s power is that many things you might
1362     /// not think of as 'collections' actually are. For example, a [`String`]
1363     /// is a collection of [`char`]s. And a collection of
1364     /// [`Result<T, E>`][`Result`] can be thought of as single
1365     /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1366     ///
1367     /// Because `collect()` is so general, it can cause problems with type
1368     /// inference. As such, `collect()` is one of the few times you'll see
1369     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1370     /// helps the inference algorithm understand specifically which collection
1371     /// you're trying to collect into.
1372     ///
1373     /// # Examples
1374     ///
1375     /// Basic usage:
1376     ///
1377     /// ```
1378     /// let a = [1, 2, 3];
1379     ///
1380     /// let doubled: Vec<i32> = a.iter()
1381     ///                          .map(|&x| x * 2)
1382     ///                          .collect();
1383     ///
1384     /// assert_eq!(vec![2, 4, 6], doubled);
1385     /// ```
1386     ///
1387     /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1388     /// we could collect into, for example, a [`VecDeque<T>`] instead:
1389     ///
1390     /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1391     ///
1392     /// ```
1393     /// use std::collections::VecDeque;
1394     ///
1395     /// let a = [1, 2, 3];
1396     ///
1397     /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
1398     ///
1399     /// assert_eq!(2, doubled[0]);
1400     /// assert_eq!(4, doubled[1]);
1401     /// assert_eq!(6, doubled[2]);
1402     /// ```
1403     ///
1404     /// Using the 'turbofish' instead of annotating `doubled`:
1405     ///
1406     /// ```
1407     /// let a = [1, 2, 3];
1408     ///
1409     /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1410     ///
1411     /// assert_eq!(vec![2, 4, 6], doubled);
1412     /// ```
1413     ///
1414     /// Because `collect()` only cares about what you're collecting into, you can
1415     /// still use a partial type hint, `_`, with the turbofish:
1416     ///
1417     /// ```
1418     /// let a = [1, 2, 3];
1419     ///
1420     /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1421     ///
1422     /// assert_eq!(vec![2, 4, 6], doubled);
1423     /// ```
1424     ///
1425     /// Using `collect()` to make a [`String`]:
1426     ///
1427     /// ```
1428     /// let chars = ['g', 'd', 'k', 'k', 'n'];
1429     ///
1430     /// let hello: String = chars.iter()
1431     ///     .map(|&x| x as u8)
1432     ///     .map(|x| (x + 1) as char)
1433     ///     .collect();
1434     ///
1435     /// assert_eq!("hello", hello);
1436     /// ```
1437     ///
1438     /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1439     /// see if any of them failed:
1440     ///
1441     /// ```
1442     /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1443     ///
1444     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1445     ///
1446     /// // gives us the first error
1447     /// assert_eq!(Err("nope"), result);
1448     ///
1449     /// let results = [Ok(1), Ok(3)];
1450     ///
1451     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1452     ///
1453     /// // gives us the list of answers
1454     /// assert_eq!(Ok(vec![1, 3]), result);
1455     /// ```
1456     ///
1457     /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1458     /// [`String`]: ../../std/string/struct.String.html
1459     /// [`char`]: ../../std/primitive.char.html
1460     /// [`Result`]: ../../std/result/enum.Result.html
1461     #[inline]
1462     #[stable(feature = "rust1", since = "1.0.0")]
1463     #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
1464     fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1465         FromIterator::from_iter(self)
1466     }
1467
1468     /// Consumes an iterator, creating two collections from it.
1469     ///
1470     /// The predicate passed to `partition()` can return `true`, or `false`.
1471     /// `partition()` returns a pair, all of the elements for which it returned
1472     /// `true`, and all of the elements for which it returned `false`.
1473     ///
1474     /// # Examples
1475     ///
1476     /// Basic usage:
1477     ///
1478     /// ```
1479     /// let a = [1, 2, 3];
1480     ///
1481     /// let (even, odd): (Vec<i32>, Vec<i32>) = a
1482     ///     .into_iter()
1483     ///     .partition(|&n| n % 2 == 0);
1484     ///
1485     /// assert_eq!(even, vec![2]);
1486     /// assert_eq!(odd, vec![1, 3]);
1487     /// ```
1488     #[stable(feature = "rust1", since = "1.0.0")]
1489     fn partition<B, F>(self, mut f: F) -> (B, B) where
1490         Self: Sized,
1491         B: Default + Extend<Self::Item>,
1492         F: FnMut(&Self::Item) -> bool
1493     {
1494         let mut left: B = Default::default();
1495         let mut right: B = Default::default();
1496
1497         for x in self {
1498             if f(&x) {
1499                 left.extend(Some(x))
1500             } else {
1501                 right.extend(Some(x))
1502             }
1503         }
1504
1505         (left, right)
1506     }
1507
1508     /// An iterator method that applies a function as long as it returns
1509     /// successfully, producing a single, final value.
1510     ///
1511     /// `try_fold()` takes two arguments: an initial value, and a closure with
1512     /// two arguments: an 'accumulator', and an element. The closure either
1513     /// returns successfully, with the value that the accumulator should have
1514     /// for the next iteration, or it returns failure, with an error value that
1515     /// is propagated back to the caller immediately (short-circuiting).
1516     ///
1517     /// The initial value is the value the accumulator will have on the first
1518     /// call. If applying the closure succeeded against every element of the
1519     /// iterator, `try_fold()` returns the final accumulator as success.
1520     ///
1521     /// Folding is useful whenever you have a collection of something, and want
1522     /// to produce a single value from it.
1523     ///
1524     /// # Note to Implementors
1525     ///
1526     /// Most of the other (forward) methods have default implementations in
1527     /// terms of this one, so try to implement this explicitly if it can
1528     /// do something better than the default `for` loop implementation.
1529     ///
1530     /// In particular, try to have this call `try_fold()` on the internal parts
1531     /// from which this iterator is composed. If multiple calls are needed,
1532     /// the `?` operator may be convenient for chaining the accumulator value
1533     /// along, but beware any invariants that need to be upheld before those
1534     /// early returns. This is a `&mut self` method, so iteration needs to be
1535     /// resumable after hitting an error here.
1536     ///
1537     /// # Examples
1538     ///
1539     /// Basic usage:
1540     ///
1541     /// ```
1542     /// let a = [1, 2, 3];
1543     ///
1544     /// // the checked sum of all of the elements of the array
1545     /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
1546     ///
1547     /// assert_eq!(sum, Some(6));
1548     /// ```
1549     ///
1550     /// Short-circuiting:
1551     ///
1552     /// ```
1553     /// let a = [10, 20, 30, 100, 40, 50];
1554     /// let mut it = a.iter();
1555     ///
1556     /// // This sum overflows when adding the 100 element
1557     /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
1558     /// assert_eq!(sum, None);
1559     ///
1560     /// // Because it short-circuited, the remaining elements are still
1561     /// // available through the iterator.
1562     /// assert_eq!(it.len(), 2);
1563     /// assert_eq!(it.next(), Some(&40));
1564     /// ```
1565     #[inline]
1566     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1567     fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1568         Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1569     {
1570         let mut accum = init;
1571         while let Some(x) = self.next() {
1572             accum = f(accum, x)?;
1573         }
1574         Try::from_ok(accum)
1575     }
1576
1577     /// An iterator method that applies a fallible function to each item in the
1578     /// iterator, stopping at the first error and returning that error.
1579     ///
1580     /// This can also be thought of as the fallible form of [`for_each()`]
1581     /// or as the stateless version of [`try_fold()`].
1582     ///
1583     /// [`for_each()`]: #method.for_each
1584     /// [`try_fold()`]: #method.try_fold
1585     ///
1586     /// # Examples
1587     ///
1588     /// ```
1589     /// use std::fs::rename;
1590     /// use std::io::{stdout, Write};
1591     /// use std::path::Path;
1592     ///
1593     /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
1594     ///
1595     /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
1596     /// assert!(res.is_ok());
1597     ///
1598     /// let mut it = data.iter().cloned();
1599     /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
1600     /// assert!(res.is_err());
1601     /// // It short-circuited, so the remaining items are still in the iterator:
1602     /// assert_eq!(it.next(), Some("stale_bread.json"));
1603     /// ```
1604     #[inline]
1605     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
1606     fn try_for_each<F, R>(&mut self, mut f: F) -> R where
1607         Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
1608     {
1609         self.try_fold((), move |(), x| f(x))
1610     }
1611
1612     /// An iterator method that applies a function, producing a single, final value.
1613     ///
1614     /// `fold()` takes two arguments: an initial value, and a closure with two
1615     /// arguments: an 'accumulator', and an element. The closure returns the value that
1616     /// the accumulator should have for the next iteration.
1617     ///
1618     /// The initial value is the value the accumulator will have on the first
1619     /// call.
1620     ///
1621     /// After applying this closure to every element of the iterator, `fold()`
1622     /// returns the accumulator.
1623     ///
1624     /// This operation is sometimes called 'reduce' or 'inject'.
1625     ///
1626     /// Folding is useful whenever you have a collection of something, and want
1627     /// to produce a single value from it.
1628     ///
1629     /// Note: `fold()`, and similar methods that traverse the entire iterator,
1630     /// may not terminate for infinite iterators, even on traits for which a
1631     /// result is determinable in finite time.
1632     ///
1633     /// # Examples
1634     ///
1635     /// Basic usage:
1636     ///
1637     /// ```
1638     /// let a = [1, 2, 3];
1639     ///
1640     /// // the sum of all of the elements of the array
1641     /// let sum = a.iter().fold(0, |acc, x| acc + x);
1642     ///
1643     /// assert_eq!(sum, 6);
1644     /// ```
1645     ///
1646     /// Let's walk through each step of the iteration here:
1647     ///
1648     /// | element | acc | x | result |
1649     /// |---------|-----|---|--------|
1650     /// |         | 0   |   |        |
1651     /// | 1       | 0   | 1 | 1      |
1652     /// | 2       | 1   | 2 | 3      |
1653     /// | 3       | 3   | 3 | 6      |
1654     ///
1655     /// And so, our final result, `6`.
1656     ///
1657     /// It's common for people who haven't used iterators a lot to
1658     /// use a `for` loop with a list of things to build up a result. Those
1659     /// can be turned into `fold()`s:
1660     ///
1661     /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
1662     ///
1663     /// ```
1664     /// let numbers = [1, 2, 3, 4, 5];
1665     ///
1666     /// let mut result = 0;
1667     ///
1668     /// // for loop:
1669     /// for i in &numbers {
1670     ///     result = result + i;
1671     /// }
1672     ///
1673     /// // fold:
1674     /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1675     ///
1676     /// // they're the same
1677     /// assert_eq!(result, result2);
1678     /// ```
1679     #[inline]
1680     #[stable(feature = "rust1", since = "1.0.0")]
1681     fn fold<B, F>(mut self, init: B, mut f: F) -> B where
1682         Self: Sized, F: FnMut(B, Self::Item) -> B,
1683     {
1684         self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
1685     }
1686
1687     /// Tests if every element of the iterator matches a predicate.
1688     ///
1689     /// `all()` takes a closure that returns `true` or `false`. It applies
1690     /// this closure to each element of the iterator, and if they all return
1691     /// `true`, then so does `all()`. If any of them return `false`, it
1692     /// returns `false`.
1693     ///
1694     /// `all()` is short-circuiting; in other words, it will stop processing
1695     /// as soon as it finds a `false`, given that no matter what else happens,
1696     /// the result will also be `false`.
1697     ///
1698     /// An empty iterator returns `true`.
1699     ///
1700     /// # Examples
1701     ///
1702     /// Basic usage:
1703     ///
1704     /// ```
1705     /// let a = [1, 2, 3];
1706     ///
1707     /// assert!(a.iter().all(|&x| x > 0));
1708     ///
1709     /// assert!(!a.iter().all(|&x| x > 2));
1710     /// ```
1711     ///
1712     /// Stopping at the first `false`:
1713     ///
1714     /// ```
1715     /// let a = [1, 2, 3];
1716     ///
1717     /// let mut iter = a.iter();
1718     ///
1719     /// assert!(!iter.all(|&x| x != 2));
1720     ///
1721     /// // we can still use `iter`, as there are more elements.
1722     /// assert_eq!(iter.next(), Some(&3));
1723     /// ```
1724     #[inline]
1725     #[stable(feature = "rust1", since = "1.0.0")]
1726     fn all<F>(&mut self, mut f: F) -> bool where
1727         Self: Sized, F: FnMut(Self::Item) -> bool
1728     {
1729         self.try_for_each(move |x| {
1730             if f(x) { LoopState::Continue(()) }
1731             else { LoopState::Break(()) }
1732         }) == LoopState::Continue(())
1733     }
1734
1735     /// Tests if any element of the iterator matches a predicate.
1736     ///
1737     /// `any()` takes a closure that returns `true` or `false`. It applies
1738     /// this closure to each element of the iterator, and if any of them return
1739     /// `true`, then so does `any()`. If they all return `false`, it
1740     /// returns `false`.
1741     ///
1742     /// `any()` is short-circuiting; in other words, it will stop processing
1743     /// as soon as it finds a `true`, given that no matter what else happens,
1744     /// the result will also be `true`.
1745     ///
1746     /// An empty iterator returns `false`.
1747     ///
1748     /// # Examples
1749     ///
1750     /// Basic usage:
1751     ///
1752     /// ```
1753     /// let a = [1, 2, 3];
1754     ///
1755     /// assert!(a.iter().any(|&x| x > 0));
1756     ///
1757     /// assert!(!a.iter().any(|&x| x > 5));
1758     /// ```
1759     ///
1760     /// Stopping at the first `true`:
1761     ///
1762     /// ```
1763     /// let a = [1, 2, 3];
1764     ///
1765     /// let mut iter = a.iter();
1766     ///
1767     /// assert!(iter.any(|&x| x != 2));
1768     ///
1769     /// // we can still use `iter`, as there are more elements.
1770     /// assert_eq!(iter.next(), Some(&2));
1771     /// ```
1772     #[inline]
1773     #[stable(feature = "rust1", since = "1.0.0")]
1774     fn any<F>(&mut self, mut f: F) -> bool where
1775         Self: Sized,
1776         F: FnMut(Self::Item) -> bool
1777     {
1778         self.try_for_each(move |x| {
1779             if f(x) { LoopState::Break(()) }
1780             else { LoopState::Continue(()) }
1781         }) == LoopState::Break(())
1782     }
1783
1784     /// Searches for an element of an iterator that satisfies a predicate.
1785     ///
1786     /// `find()` takes a closure that returns `true` or `false`. It applies
1787     /// this closure to each element of the iterator, and if any of them return
1788     /// `true`, then `find()` returns [`Some(element)`]. If they all return
1789     /// `false`, it returns [`None`].
1790     ///
1791     /// `find()` is short-circuiting; in other words, it will stop processing
1792     /// as soon as the closure returns `true`.
1793     ///
1794     /// Because `find()` takes a reference, and many iterators iterate over
1795     /// references, this leads to a possibly confusing situation where the
1796     /// argument is a double reference. You can see this effect in the
1797     /// examples below, with `&&x`.
1798     ///
1799     /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1800     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1801     ///
1802     /// # Examples
1803     ///
1804     /// Basic usage:
1805     ///
1806     /// ```
1807     /// let a = [1, 2, 3];
1808     ///
1809     /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1810     ///
1811     /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1812     /// ```
1813     ///
1814     /// Stopping at the first `true`:
1815     ///
1816     /// ```
1817     /// let a = [1, 2, 3];
1818     ///
1819     /// let mut iter = a.iter();
1820     ///
1821     /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1822     ///
1823     /// // we can still use `iter`, as there are more elements.
1824     /// assert_eq!(iter.next(), Some(&3));
1825     /// ```
1826     #[inline]
1827     #[stable(feature = "rust1", since = "1.0.0")]
1828     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1829         Self: Sized,
1830         P: FnMut(&Self::Item) -> bool,
1831     {
1832         self.try_for_each(move |x| {
1833             if predicate(&x) { LoopState::Break(x) }
1834             else { LoopState::Continue(()) }
1835         }).break_value()
1836     }
1837
1838     /// Applies function to the elements of iterator and returns
1839     /// the first non-none result.
1840     ///
1841     /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
1842     ///
1843     ///
1844     /// # Examples
1845     ///
1846     /// ```
1847     /// let a = ["lol", "NaN", "2", "5"];
1848     ///
1849     /// let first_number = a.iter().find_map(|s| s.parse().ok());
1850     ///
1851     /// assert_eq!(first_number, Some(2));
1852     /// ```
1853     #[inline]
1854     #[stable(feature = "iterator_find_map", since = "1.30.0")]
1855     fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
1856         Self: Sized,
1857         F: FnMut(Self::Item) -> Option<B>,
1858     {
1859         self.try_for_each(move |x| {
1860             match f(x) {
1861                 Some(x) => LoopState::Break(x),
1862                 None => LoopState::Continue(()),
1863             }
1864         }).break_value()
1865     }
1866
1867     /// Searches for an element in an iterator, returning its index.
1868     ///
1869     /// `position()` takes a closure that returns `true` or `false`. It applies
1870     /// this closure to each element of the iterator, and if one of them
1871     /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1872     /// them return `false`, it returns [`None`].
1873     ///
1874     /// `position()` is short-circuiting; in other words, it will stop
1875     /// processing as soon as it finds a `true`.
1876     ///
1877     /// # Overflow Behavior
1878     ///
1879     /// The method does no guarding against overflows, so if there are more
1880     /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1881     /// result or panics. If debug assertions are enabled, a panic is
1882     /// guaranteed.
1883     ///
1884     /// # Panics
1885     ///
1886     /// This function might panic if the iterator has more than `usize::MAX`
1887     /// non-matching elements.
1888     ///
1889     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1890     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1891     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1892     ///
1893     /// # Examples
1894     ///
1895     /// Basic usage:
1896     ///
1897     /// ```
1898     /// let a = [1, 2, 3];
1899     ///
1900     /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1901     ///
1902     /// assert_eq!(a.iter().position(|&x| x == 5), None);
1903     /// ```
1904     ///
1905     /// Stopping at the first `true`:
1906     ///
1907     /// ```
1908     /// let a = [1, 2, 3, 4];
1909     ///
1910     /// let mut iter = a.iter();
1911     ///
1912     /// assert_eq!(iter.position(|&x| x >= 2), Some(1));
1913     ///
1914     /// // we can still use `iter`, as there are more elements.
1915     /// assert_eq!(iter.next(), Some(&3));
1916     ///
1917     /// // The returned index depends on iterator state
1918     /// assert_eq!(iter.position(|&x| x == 4), Some(0));
1919     ///
1920     /// ```
1921     #[inline]
1922     #[rustc_inherit_overflow_checks]
1923     #[stable(feature = "rust1", since = "1.0.0")]
1924     fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1925         Self: Sized,
1926         P: FnMut(Self::Item) -> bool,
1927     {
1928         // The addition might panic on overflow
1929         self.try_fold(0, move |i, x| {
1930             if predicate(x) { LoopState::Break(i) }
1931             else { LoopState::Continue(i + 1) }
1932         }).break_value()
1933     }
1934
1935     /// Searches for an element in an iterator from the right, returning its
1936     /// index.
1937     ///
1938     /// `rposition()` takes a closure that returns `true` or `false`. It applies
1939     /// this closure to each element of the iterator, starting from the end,
1940     /// and if one of them returns `true`, then `rposition()` returns
1941     /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1942     ///
1943     /// `rposition()` is short-circuiting; in other words, it will stop
1944     /// processing as soon as it finds a `true`.
1945     ///
1946     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1947     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1948     ///
1949     /// # Examples
1950     ///
1951     /// Basic usage:
1952     ///
1953     /// ```
1954     /// let a = [1, 2, 3];
1955     ///
1956     /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1957     ///
1958     /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1959     /// ```
1960     ///
1961     /// Stopping at the first `true`:
1962     ///
1963     /// ```
1964     /// let a = [1, 2, 3];
1965     ///
1966     /// let mut iter = a.iter();
1967     ///
1968     /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1969     ///
1970     /// // we can still use `iter`, as there are more elements.
1971     /// assert_eq!(iter.next(), Some(&1));
1972     /// ```
1973     #[inline]
1974     #[stable(feature = "rust1", since = "1.0.0")]
1975     fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1976         P: FnMut(Self::Item) -> bool,
1977         Self: Sized + ExactSizeIterator + DoubleEndedIterator
1978     {
1979         // No need for an overflow check here, because `ExactSizeIterator`
1980         // implies that the number of elements fits into a `usize`.
1981         let n = self.len();
1982         self.try_rfold(n, move |i, x| {
1983             let i = i - 1;
1984             if predicate(x) { LoopState::Break(i) }
1985             else { LoopState::Continue(i) }
1986         }).break_value()
1987     }
1988
1989     /// Returns the maximum element of an iterator.
1990     ///
1991     /// If several elements are equally maximum, the last element is
1992     /// returned. If the iterator is empty, [`None`] is returned.
1993     ///
1994     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1995     ///
1996     /// # Examples
1997     ///
1998     /// Basic usage:
1999     ///
2000     /// ```
2001     /// let a = [1, 2, 3];
2002     /// let b: Vec<u32> = Vec::new();
2003     ///
2004     /// assert_eq!(a.iter().max(), Some(&3));
2005     /// assert_eq!(b.iter().max(), None);
2006     /// ```
2007     #[inline]
2008     #[stable(feature = "rust1", since = "1.0.0")]
2009     fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2010     {
2011         self.max_by(Ord::cmp)
2012     }
2013
2014     /// Returns the minimum element of an iterator.
2015     ///
2016     /// If several elements are equally minimum, the first element is
2017     /// returned. If the iterator is empty, [`None`] is returned.
2018     ///
2019     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2020     ///
2021     /// # Examples
2022     ///
2023     /// Basic usage:
2024     ///
2025     /// ```
2026     /// let a = [1, 2, 3];
2027     /// let b: Vec<u32> = Vec::new();
2028     ///
2029     /// assert_eq!(a.iter().min(), Some(&1));
2030     /// assert_eq!(b.iter().min(), None);
2031     /// ```
2032     #[inline]
2033     #[stable(feature = "rust1", since = "1.0.0")]
2034     fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
2035     {
2036         self.min_by(Ord::cmp)
2037     }
2038
2039     /// Returns the element that gives the maximum value from the
2040     /// specified function.
2041     ///
2042     /// If several elements are equally maximum, the last element is
2043     /// returned. If the iterator is empty, [`None`] is returned.
2044     ///
2045     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2046     ///
2047     /// # Examples
2048     ///
2049     /// ```
2050     /// let a = [-3_i32, 0, 1, 5, -10];
2051     /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
2052     /// ```
2053     #[inline]
2054     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2055     fn max_by_key<B: Ord, F>(self, mut f: F) -> Option<Self::Item>
2056         where Self: Sized, F: FnMut(&Self::Item) -> B,
2057     {
2058         // switch to y even if it is only equal, to preserve stability.
2059         select_fold1(self.map(|x| (f(&x), x)), |(x_p, _), (y_p, _)| x_p <= y_p).map(|(_, x)| x)
2060     }
2061
2062     /// Returns the element that gives the maximum value with respect to the
2063     /// specified comparison function.
2064     ///
2065     /// If several elements are equally maximum, the last element is
2066     /// returned. If the iterator is empty, [`None`] is returned.
2067     ///
2068     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2069     ///
2070     /// # Examples
2071     ///
2072     /// ```
2073     /// let a = [-3_i32, 0, 1, 5, -10];
2074     /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
2075     /// ```
2076     #[inline]
2077     #[stable(feature = "iter_max_by", since = "1.15.0")]
2078     fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
2079         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2080     {
2081         // switch to y even if it is only equal, to preserve stability.
2082         select_fold1(self, |x, y| compare(x, y) != Ordering::Greater)
2083     }
2084
2085     /// Returns the element that gives the minimum value from the
2086     /// specified function.
2087     ///
2088     /// If several elements are equally minimum, the first element is
2089     /// returned. If the iterator is empty, [`None`] is returned.
2090     ///
2091     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2092     ///
2093     /// # Examples
2094     ///
2095     /// ```
2096     /// let a = [-3_i32, 0, 1, 5, -10];
2097     /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
2098     /// ```
2099     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
2100     fn min_by_key<B: Ord, F>(self, mut f: F) -> Option<Self::Item>
2101         where Self: Sized, F: FnMut(&Self::Item) -> B,
2102     {
2103         // only switch to y if it is strictly smaller, to preserve stability.
2104         select_fold1(self.map(|x| (f(&x), x)), |(x_p, _), (y_p, _)| x_p > y_p).map(|(_, x)| x)
2105     }
2106
2107     /// Returns the element that gives the minimum value with respect to the
2108     /// specified comparison function.
2109     ///
2110     /// If several elements are equally minimum, the first element is
2111     /// returned. If the iterator is empty, [`None`] is returned.
2112     ///
2113     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2114     ///
2115     /// # Examples
2116     ///
2117     /// ```
2118     /// let a = [-3_i32, 0, 1, 5, -10];
2119     /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
2120     /// ```
2121     #[inline]
2122     #[stable(feature = "iter_min_by", since = "1.15.0")]
2123     fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
2124         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
2125     {
2126         // only switch to y if it is strictly smaller, to preserve stability.
2127         select_fold1(self, |x, y| compare(x, y) == Ordering::Greater)
2128     }
2129
2130
2131     /// Reverses an iterator's direction.
2132     ///
2133     /// Usually, iterators iterate from left to right. After using `rev()`,
2134     /// an iterator will instead iterate from right to left.
2135     ///
2136     /// This is only possible if the iterator has an end, so `rev()` only
2137     /// works on [`DoubleEndedIterator`]s.
2138     ///
2139     /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2140     ///
2141     /// # Examples
2142     ///
2143     /// ```
2144     /// let a = [1, 2, 3];
2145     ///
2146     /// let mut iter = a.iter().rev();
2147     ///
2148     /// assert_eq!(iter.next(), Some(&3));
2149     /// assert_eq!(iter.next(), Some(&2));
2150     /// assert_eq!(iter.next(), Some(&1));
2151     ///
2152     /// assert_eq!(iter.next(), None);
2153     /// ```
2154     #[inline]
2155     #[stable(feature = "rust1", since = "1.0.0")]
2156     fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2157         Rev::new(self)
2158     }
2159
2160     /// Converts an iterator of pairs into a pair of containers.
2161     ///
2162     /// `unzip()` consumes an entire iterator of pairs, producing two
2163     /// collections: one from the left elements of the pairs, and one
2164     /// from the right elements.
2165     ///
2166     /// This function is, in some sense, the opposite of [`zip`].
2167     ///
2168     /// [`zip`]: #method.zip
2169     ///
2170     /// # Examples
2171     ///
2172     /// Basic usage:
2173     ///
2174     /// ```
2175     /// let a = [(1, 2), (3, 4)];
2176     ///
2177     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2178     ///
2179     /// assert_eq!(left, [1, 3]);
2180     /// assert_eq!(right, [2, 4]);
2181     /// ```
2182     #[stable(feature = "rust1", since = "1.0.0")]
2183     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2184         FromA: Default + Extend<A>,
2185         FromB: Default + Extend<B>,
2186         Self: Sized + Iterator<Item=(A, B)>,
2187     {
2188         let mut ts: FromA = Default::default();
2189         let mut us: FromB = Default::default();
2190
2191         self.for_each(|(t, u)| {
2192             ts.extend(Some(t));
2193             us.extend(Some(u));
2194         });
2195
2196         (ts, us)
2197     }
2198
2199     /// Creates an iterator which copies all of its elements.
2200     ///
2201     /// This is useful when you have an iterator over `&T`, but you need an
2202     /// iterator over `T`.
2203     ///
2204     /// # Examples
2205     ///
2206     /// Basic usage:
2207     ///
2208     /// ```
2209     /// let a = [1, 2, 3];
2210     ///
2211     /// let v_cloned: Vec<_> = a.iter().copied().collect();
2212     ///
2213     /// // copied is the same as .map(|&x| x)
2214     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2215     ///
2216     /// assert_eq!(v_cloned, vec![1, 2, 3]);
2217     /// assert_eq!(v_map, vec![1, 2, 3]);
2218     /// ```
2219     #[stable(feature = "iter_copied", since = "1.36.0")]
2220     fn copied<'a, T: 'a>(self) -> Copied<Self>
2221         where Self: Sized + Iterator<Item=&'a T>, T: Copy
2222     {
2223         Copied::new(self)
2224     }
2225
2226     /// Creates an iterator which [`clone`]s all of its elements.
2227     ///
2228     /// This is useful when you have an iterator over `&T`, but you need an
2229     /// iterator over `T`.
2230     ///
2231     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
2232     ///
2233     /// # Examples
2234     ///
2235     /// Basic usage:
2236     ///
2237     /// ```
2238     /// let a = [1, 2, 3];
2239     ///
2240     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2241     ///
2242     /// // cloned is the same as .map(|&x| x), for integers
2243     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2244     ///
2245     /// assert_eq!(v_cloned, vec![1, 2, 3]);
2246     /// assert_eq!(v_map, vec![1, 2, 3]);
2247     /// ```
2248     #[stable(feature = "rust1", since = "1.0.0")]
2249     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2250         where Self: Sized + Iterator<Item=&'a T>, T: Clone
2251     {
2252         Cloned::new(self)
2253     }
2254
2255     /// Repeats an iterator endlessly.
2256     ///
2257     /// Instead of stopping at [`None`], the iterator will instead start again,
2258     /// from the beginning. After iterating again, it will start at the
2259     /// beginning again. And again. And again. Forever.
2260     ///
2261     /// [`None`]: ../../std/option/enum.Option.html#variant.None
2262     ///
2263     /// # Examples
2264     ///
2265     /// Basic usage:
2266     ///
2267     /// ```
2268     /// let a = [1, 2, 3];
2269     ///
2270     /// let mut it = a.iter().cycle();
2271     ///
2272     /// assert_eq!(it.next(), Some(&1));
2273     /// assert_eq!(it.next(), Some(&2));
2274     /// assert_eq!(it.next(), Some(&3));
2275     /// assert_eq!(it.next(), Some(&1));
2276     /// assert_eq!(it.next(), Some(&2));
2277     /// assert_eq!(it.next(), Some(&3));
2278     /// assert_eq!(it.next(), Some(&1));
2279     /// ```
2280     #[stable(feature = "rust1", since = "1.0.0")]
2281     #[inline]
2282     fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2283         Cycle::new(self)
2284     }
2285
2286     /// Sums the elements of an iterator.
2287     ///
2288     /// Takes each element, adds them together, and returns the result.
2289     ///
2290     /// An empty iterator returns the zero value of the type.
2291     ///
2292     /// # Panics
2293     ///
2294     /// When calling `sum()` and a primitive integer type is being returned, this
2295     /// method will panic if the computation overflows and debug assertions are
2296     /// enabled.
2297     ///
2298     /// # Examples
2299     ///
2300     /// Basic usage:
2301     ///
2302     /// ```
2303     /// let a = [1, 2, 3];
2304     /// let sum: i32 = a.iter().sum();
2305     ///
2306     /// assert_eq!(sum, 6);
2307     /// ```
2308     #[stable(feature = "iter_arith", since = "1.11.0")]
2309     fn sum<S>(self) -> S
2310         where Self: Sized,
2311               S: Sum<Self::Item>,
2312     {
2313         Sum::sum(self)
2314     }
2315
2316     /// Iterates over the entire iterator, multiplying all the elements
2317     ///
2318     /// An empty iterator returns the one value of the type.
2319     ///
2320     /// # Panics
2321     ///
2322     /// When calling `product()` and a primitive integer type is being returned,
2323     /// method will panic if the computation overflows and debug assertions are
2324     /// enabled.
2325     ///
2326     /// # Examples
2327     ///
2328     /// ```
2329     /// fn factorial(n: u32) -> u32 {
2330     ///     (1..=n).product()
2331     /// }
2332     /// assert_eq!(factorial(0), 1);
2333     /// assert_eq!(factorial(1), 1);
2334     /// assert_eq!(factorial(5), 120);
2335     /// ```
2336     #[stable(feature = "iter_arith", since = "1.11.0")]
2337     fn product<P>(self) -> P
2338         where Self: Sized,
2339               P: Product<Self::Item>,
2340     {
2341         Product::product(self)
2342     }
2343
2344     /// Lexicographically compares the elements of this `Iterator` with those
2345     /// of another.
2346     #[stable(feature = "iter_order", since = "1.5.0")]
2347     fn cmp<I>(mut self, other: I) -> Ordering where
2348         I: IntoIterator<Item = Self::Item>,
2349         Self::Item: Ord,
2350         Self: Sized,
2351     {
2352         let mut other = other.into_iter();
2353
2354         loop {
2355             let x = match self.next() {
2356                 None => if other.next().is_none() {
2357                     return Ordering::Equal
2358                 } else {
2359                     return Ordering::Less
2360                 },
2361                 Some(val) => val,
2362             };
2363
2364             let y = match other.next() {
2365                 None => return Ordering::Greater,
2366                 Some(val) => val,
2367             };
2368
2369             match x.cmp(&y) {
2370                 Ordering::Equal => (),
2371                 non_eq => return non_eq,
2372             }
2373         }
2374     }
2375
2376     /// Lexicographically compares the elements of this `Iterator` with those
2377     /// of another.
2378     #[stable(feature = "iter_order", since = "1.5.0")]
2379     fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2380         I: IntoIterator,
2381         Self::Item: PartialOrd<I::Item>,
2382         Self: Sized,
2383     {
2384         let mut other = other.into_iter();
2385
2386         loop {
2387             let x = match self.next() {
2388                 None => if other.next().is_none() {
2389                     return Some(Ordering::Equal)
2390                 } else {
2391                     return Some(Ordering::Less)
2392                 },
2393                 Some(val) => val,
2394             };
2395
2396             let y = match other.next() {
2397                 None => return Some(Ordering::Greater),
2398                 Some(val) => val,
2399             };
2400
2401             match x.partial_cmp(&y) {
2402                 Some(Ordering::Equal) => (),
2403                 non_eq => return non_eq,
2404             }
2405         }
2406     }
2407
2408     /// Determines if the elements of this `Iterator` are equal to those of
2409     /// another.
2410     #[stable(feature = "iter_order", since = "1.5.0")]
2411     fn eq<I>(mut self, other: I) -> bool where
2412         I: IntoIterator,
2413         Self::Item: PartialEq<I::Item>,
2414         Self: Sized,
2415     {
2416         let mut other = other.into_iter();
2417
2418         loop {
2419             let x = match self.next() {
2420                 None => return other.next().is_none(),
2421                 Some(val) => val,
2422             };
2423
2424             let y = match other.next() {
2425                 None => return false,
2426                 Some(val) => val,
2427             };
2428
2429             if x != y { return false }
2430         }
2431     }
2432
2433     /// Determines if the elements of this `Iterator` are unequal to those of
2434     /// another.
2435     #[stable(feature = "iter_order", since = "1.5.0")]
2436     fn ne<I>(self, other: I) -> bool where
2437         I: IntoIterator,
2438         Self::Item: PartialEq<I::Item>,
2439         Self: Sized,
2440     {
2441         !self.eq(other)
2442     }
2443
2444     /// Determines if the elements of this `Iterator` are lexicographically
2445     /// less than those of another.
2446     #[stable(feature = "iter_order", since = "1.5.0")]
2447     fn lt<I>(self, other: I) -> bool where
2448         I: IntoIterator,
2449         Self::Item: PartialOrd<I::Item>,
2450         Self: Sized,
2451     {
2452         self.partial_cmp(other) == Some(Ordering::Less)
2453     }
2454
2455     /// Determines if the elements of this `Iterator` are lexicographically
2456     /// less or equal to those of another.
2457     #[stable(feature = "iter_order", since = "1.5.0")]
2458     fn le<I>(self, other: I) -> bool where
2459         I: IntoIterator,
2460         Self::Item: PartialOrd<I::Item>,
2461         Self: Sized,
2462     {
2463         match self.partial_cmp(other) {
2464             Some(Ordering::Less) | Some(Ordering::Equal) => true,
2465             _ => false,
2466         }
2467     }
2468
2469     /// Determines if the elements of this `Iterator` are lexicographically
2470     /// greater than those of another.
2471     #[stable(feature = "iter_order", since = "1.5.0")]
2472     fn gt<I>(self, other: I) -> bool where
2473         I: IntoIterator,
2474         Self::Item: PartialOrd<I::Item>,
2475         Self: Sized,
2476     {
2477         self.partial_cmp(other) == Some(Ordering::Greater)
2478     }
2479
2480     /// Determines if the elements of this `Iterator` are lexicographically
2481     /// greater than or equal to those of another.
2482     #[stable(feature = "iter_order", since = "1.5.0")]
2483     fn ge<I>(self, other: I) -> bool where
2484         I: IntoIterator,
2485         Self::Item: PartialOrd<I::Item>,
2486         Self: Sized,
2487     {
2488         match self.partial_cmp(other) {
2489             Some(Ordering::Greater) | Some(Ordering::Equal) => true,
2490             _ => false,
2491         }
2492     }
2493
2494     /// Checks if the elements of this iterator are sorted.
2495     ///
2496     /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2497     /// iterator yields exactly zero or one element, `true` is returned.
2498     ///
2499     /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2500     /// implies that this function returns `false` if any two consecutive items are not
2501     /// comparable.
2502     ///
2503     /// # Examples
2504     ///
2505     /// ```
2506     /// #![feature(is_sorted)]
2507     ///
2508     /// assert!([1, 2, 2, 9].iter().is_sorted());
2509     /// assert!(![1, 3, 2, 4].iter().is_sorted());
2510     /// assert!([0].iter().is_sorted());
2511     /// assert!(std::iter::empty::<i32>().is_sorted());
2512     /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted());
2513     /// ```
2514     #[inline]
2515     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2516     fn is_sorted(self) -> bool
2517     where
2518         Self: Sized,
2519         Self::Item: PartialOrd,
2520     {
2521         self.is_sorted_by(|a, b| a.partial_cmp(b))
2522     }
2523
2524     /// Checks if the elements of this iterator are sorted using the given comparator function.
2525     ///
2526     /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2527     /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2528     /// [`is_sorted`]; see its documentation for more information.
2529     ///
2530     /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2531     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2532     fn is_sorted_by<F>(mut self, mut compare: F) -> bool
2533     where
2534         Self: Sized,
2535         F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>
2536     {
2537         let mut last = match self.next() {
2538             Some(e) => e,
2539             None => return true,
2540         };
2541
2542         while let Some(curr) = self.next() {
2543             if compare(&last, &curr)
2544                 .map(|o| o == Ordering::Greater)
2545                 .unwrap_or(true)
2546             {
2547                 return false;
2548             }
2549             last = curr;
2550         }
2551
2552         true
2553     }
2554
2555     /// Checks if the elements of this iterator are sorted using the given key extraction
2556     /// function.
2557     ///
2558     /// Instead of comparing the iterator's elements directly, this function compares the keys of
2559     /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
2560     /// its documentation for more information.
2561     ///
2562     /// [`is_sorted`]: trait.Iterator.html#method.is_sorted
2563     ///
2564     /// # Examples
2565     ///
2566     /// ```
2567     /// #![feature(is_sorted)]
2568     ///
2569     /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
2570     /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
2571     /// ```
2572     #[inline]
2573     #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2574     fn is_sorted_by_key<F, K>(self, mut f: F) -> bool
2575     where
2576         Self: Sized,
2577         F: FnMut(&Self::Item) -> K,
2578         K: PartialOrd
2579     {
2580         self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
2581     }
2582 }
2583
2584 /// Select an element from an iterator based on the given "comparison"
2585 /// function.
2586 ///
2587 /// This is an idiosyncratic helper to try to factor out the
2588 /// commonalities of {max,min}{,_by}. In particular, this avoids
2589 /// having to implement optimizations several times.
2590 #[inline]
2591 fn select_fold1<I, F>(mut it: I, mut f: F) -> Option<I::Item>
2592     where
2593         I: Iterator,
2594         F: FnMut(&I::Item, &I::Item) -> bool,
2595 {
2596     // start with the first element as our selection. This avoids
2597     // having to use `Option`s inside the loop, translating to a
2598     // sizeable performance gain (6x in one case).
2599     it.next().map(|first| {
2600         it.fold(first, |sel, x| if f(&sel, &x) { x } else { sel })
2601     })
2602 }
2603
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 impl<I: Iterator + ?Sized> Iterator for &mut I {
2606     type Item = I::Item;
2607     fn next(&mut self) -> Option<I::Item> { (**self).next() }
2608     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2609     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2610         (**self).nth(n)
2611     }
2612 }