]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/iterator.rs
Rollup merge of #34460 - dsprenkels:issue-33455, r=alexcrichton
[rust.git] / src / libcore / iter / iterator.rs
1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use clone::Clone;
12 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
13 use default::Default;
14 use num::{Zero, One};
15 use ops::{Add, FnMut, Mul};
16 use option::Option::{self, Some, None};
17 use marker::Sized;
18
19 use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, FlatMap, Fuse,
20             Inspect, Map, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, Rev,
21             Zip};
22 use super::ChainState;
23 use super::{DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator,
24             IntoIterator};
25 use super::ZipImpl;
26
27 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
28
29 /// An interface for dealing with iterators.
30 ///
31 /// This is the main iterator trait. For more about the concept of iterators
32 /// generally, please see the [module-level documentation]. In particular, you
33 /// may want to know how to [implement `Iterator`][impl].
34 ///
35 /// [module-level documentation]: index.html
36 /// [impl]: index.html#implementing-iterator
37 #[stable(feature = "rust1", since = "1.0.0")]
38 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
39                             `.iter()` or a similar method"]
40 pub trait Iterator {
41     /// The type of the elements being iterated over.
42     #[stable(feature = "rust1", since = "1.0.0")]
43     type Item;
44
45     /// Advances the iterator and returns the next value.
46     ///
47     /// Returns `None` when iteration is finished. Individual iterator
48     /// implementations may choose to resume iteration, and so calling `next()`
49     /// again may or may not eventually start returning `Some(Item)` again at some
50     /// point.
51     ///
52     /// # Examples
53     ///
54     /// Basic usage:
55     ///
56     /// ```
57     /// let a = [1, 2, 3];
58     ///
59     /// let mut iter = a.iter();
60     ///
61     /// // A call to next() returns the next value...
62     /// assert_eq!(Some(&1), iter.next());
63     /// assert_eq!(Some(&2), iter.next());
64     /// assert_eq!(Some(&3), iter.next());
65     ///
66     /// // ... and then None once it's over.
67     /// assert_eq!(None, iter.next());
68     ///
69     /// // More calls may or may not return None. Here, they always will.
70     /// assert_eq!(None, iter.next());
71     /// assert_eq!(None, iter.next());
72     /// ```
73     #[stable(feature = "rust1", since = "1.0.0")]
74     fn next(&mut self) -> Option<Self::Item>;
75
76     /// Returns the bounds on the remaining length of the iterator.
77     ///
78     /// Specifically, `size_hint()` returns a tuple where the first element
79     /// is the lower bound, and the second element is the upper bound.
80     ///
81     /// The second half of the tuple that is returned is an `Option<usize>`. A
82     /// `None` here means that either there is no known upper bound, or the
83     /// upper bound is larger than `usize`.
84     ///
85     /// # Implementation notes
86     ///
87     /// It is not enforced that an iterator implementation yields the declared
88     /// number of elements. A buggy iterator may yield less than the lower bound
89     /// or more than the upper bound of elements.
90     ///
91     /// `size_hint()` is primarily intended to be used for optimizations such as
92     /// reserving space for the elements of the iterator, but must not be
93     /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
94     /// implementation of `size_hint()` should not lead to memory safety
95     /// violations.
96     ///
97     /// That said, the implementation should provide a correct estimation,
98     /// because otherwise it would be a violation of the trait's protocol.
99     ///
100     /// The default implementation returns `(0, None)` which is correct for any
101     /// iterator.
102     ///
103     /// # Examples
104     ///
105     /// Basic usage:
106     ///
107     /// ```
108     /// let a = [1, 2, 3];
109     /// let iter = a.iter();
110     ///
111     /// assert_eq!((3, Some(3)), iter.size_hint());
112     /// ```
113     ///
114     /// A more complex example:
115     ///
116     /// ```
117     /// // The even numbers from zero to ten.
118     /// let iter = (0..10).filter(|x| x % 2 == 0);
119     ///
120     /// // We might iterate from zero to ten times. Knowing that it's five
121     /// // exactly wouldn't be possible without executing filter().
122     /// assert_eq!((0, Some(10)), iter.size_hint());
123     ///
124     /// // Let's add one five more numbers with chain()
125     /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
126     ///
127     /// // now both bounds are increased by five
128     /// assert_eq!((5, Some(15)), iter.size_hint());
129     /// ```
130     ///
131     /// Returning `None` for an upper bound:
132     ///
133     /// ```
134     /// // an infinite iterator has no upper bound
135     /// let iter = 0..;
136     ///
137     /// assert_eq!((0, None), iter.size_hint());
138     /// ```
139     #[inline]
140     #[stable(feature = "rust1", since = "1.0.0")]
141     fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
142
143     /// Consumes the iterator, counting the number of iterations and returning it.
144     ///
145     /// This method will evaluate the iterator until its [`next()`] returns
146     /// `None`. Once `None` is encountered, `count()` returns the number of
147     /// times it called [`next()`].
148     ///
149     /// [`next()`]: #tymethod.next
150     ///
151     /// # Overflow Behavior
152     ///
153     /// The method does no guarding against overflows, so counting elements of
154     /// an iterator with more than `usize::MAX` elements either produces the
155     /// wrong result or panics. If debug assertions are enabled, a panic is
156     /// guaranteed.
157     ///
158     /// # Panics
159     ///
160     /// This function might panic if the iterator has more than `usize::MAX`
161     /// elements.
162     ///
163     /// # Examples
164     ///
165     /// Basic usage:
166     ///
167     /// ```
168     /// let a = [1, 2, 3];
169     /// assert_eq!(a.iter().count(), 3);
170     ///
171     /// let a = [1, 2, 3, 4, 5];
172     /// assert_eq!(a.iter().count(), 5);
173     /// ```
174     #[inline]
175     #[rustc_inherit_overflow_checks]
176     #[stable(feature = "rust1", since = "1.0.0")]
177     fn count(self) -> usize where Self: Sized {
178         // Might overflow.
179         self.fold(0, |cnt, _| cnt + 1)
180     }
181
182     /// Consumes the iterator, returning the last element.
183     ///
184     /// This method will evaluate the iterator until it returns `None`. While
185     /// doing so, it keeps track of the current element. After `None` is
186     /// returned, `last()` will then return the last element it saw.
187     ///
188     /// # Examples
189     ///
190     /// Basic usage:
191     ///
192     /// ```
193     /// let a = [1, 2, 3];
194     /// assert_eq!(a.iter().last(), Some(&3));
195     ///
196     /// let a = [1, 2, 3, 4, 5];
197     /// assert_eq!(a.iter().last(), Some(&5));
198     /// ```
199     #[inline]
200     #[stable(feature = "rust1", since = "1.0.0")]
201     fn last(self) -> Option<Self::Item> where Self: Sized {
202         let mut last = None;
203         for x in self { last = Some(x); }
204         last
205     }
206
207     /// Consumes the `n` first elements of the iterator, then returns the
208     /// `next()` one.
209     ///
210     /// This method will evaluate the iterator `n` times, discarding those elements.
211     /// After it does so, it will call [`next()`] and return its value.
212     ///
213     /// [`next()`]: #tymethod.next
214     ///
215     /// Like most indexing operations, the count starts from zero, so `nth(0)`
216     /// returns the first value, `nth(1)` the second, and so on.
217     ///
218     /// `nth()` will return `None` if `n` is greater than or equal to the length of the
219     /// iterator.
220     ///
221     /// # Examples
222     ///
223     /// Basic usage:
224     ///
225     /// ```
226     /// let a = [1, 2, 3];
227     /// assert_eq!(a.iter().nth(1), Some(&2));
228     /// ```
229     ///
230     /// Calling `nth()` multiple times doesn't rewind the iterator:
231     ///
232     /// ```
233     /// let a = [1, 2, 3];
234     ///
235     /// let mut iter = a.iter();
236     ///
237     /// assert_eq!(iter.nth(1), Some(&2));
238     /// assert_eq!(iter.nth(1), None);
239     /// ```
240     ///
241     /// Returning `None` if there are less than `n + 1` elements:
242     ///
243     /// ```
244     /// let a = [1, 2, 3];
245     /// assert_eq!(a.iter().nth(10), None);
246     /// ```
247     #[inline]
248     #[stable(feature = "rust1", since = "1.0.0")]
249     fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
250         for x in self {
251             if n == 0 { return Some(x) }
252             n -= 1;
253         }
254         None
255     }
256
257     /// Takes two iterators and creates a new iterator over both in sequence.
258     ///
259     /// `chain()` will return a new iterator which will first iterate over
260     /// values from the first iterator and then over values from the second
261     /// iterator.
262     ///
263     /// In other words, it links two iterators together, in a chain. ðŸ”—
264     ///
265     /// # Examples
266     ///
267     /// Basic usage:
268     ///
269     /// ```
270     /// let a1 = [1, 2, 3];
271     /// let a2 = [4, 5, 6];
272     ///
273     /// let mut iter = a1.iter().chain(a2.iter());
274     ///
275     /// assert_eq!(iter.next(), Some(&1));
276     /// assert_eq!(iter.next(), Some(&2));
277     /// assert_eq!(iter.next(), Some(&3));
278     /// assert_eq!(iter.next(), Some(&4));
279     /// assert_eq!(iter.next(), Some(&5));
280     /// assert_eq!(iter.next(), Some(&6));
281     /// assert_eq!(iter.next(), None);
282     /// ```
283     ///
284     /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
285     /// anything that can be converted into an [`Iterator`], not just an
286     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
287     /// [`IntoIterator`], and so can be passed to `chain()` directly:
288     ///
289     /// [`IntoIterator`]: trait.IntoIterator.html
290     /// [`Iterator`]: trait.Iterator.html
291     ///
292     /// ```
293     /// let s1 = &[1, 2, 3];
294     /// let s2 = &[4, 5, 6];
295     ///
296     /// let mut iter = s1.iter().chain(s2);
297     ///
298     /// assert_eq!(iter.next(), Some(&1));
299     /// assert_eq!(iter.next(), Some(&2));
300     /// assert_eq!(iter.next(), Some(&3));
301     /// assert_eq!(iter.next(), Some(&4));
302     /// assert_eq!(iter.next(), Some(&5));
303     /// assert_eq!(iter.next(), Some(&6));
304     /// assert_eq!(iter.next(), None);
305     /// ```
306     #[inline]
307     #[stable(feature = "rust1", since = "1.0.0")]
308     fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
309         Self: Sized, U: IntoIterator<Item=Self::Item>,
310     {
311         Chain{a: self, b: other.into_iter(), state: ChainState::Both}
312     }
313
314     /// 'Zips up' two iterators into a single iterator of pairs.
315     ///
316     /// `zip()` returns a new iterator that will iterate over two other
317     /// iterators, returning a tuple where the first element comes from the
318     /// first iterator, and the second element comes from the second iterator.
319     ///
320     /// In other words, it zips two iterators together, into a single one.
321     ///
322     /// When either iterator returns `None`, all further calls to `next()`
323     /// will return `None`.
324     ///
325     /// # Examples
326     ///
327     /// Basic usage:
328     ///
329     /// ```
330     /// let a1 = [1, 2, 3];
331     /// let a2 = [4, 5, 6];
332     ///
333     /// let mut iter = a1.iter().zip(a2.iter());
334     ///
335     /// assert_eq!(iter.next(), Some((&1, &4)));
336     /// assert_eq!(iter.next(), Some((&2, &5)));
337     /// assert_eq!(iter.next(), Some((&3, &6)));
338     /// assert_eq!(iter.next(), None);
339     /// ```
340     ///
341     /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
342     /// anything that can be converted into an [`Iterator`], not just an
343     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
344     /// [`IntoIterator`], and so can be passed to `zip()` directly:
345     ///
346     /// [`IntoIterator`]: trait.IntoIterator.html
347     /// [`Iterator`]: trait.Iterator.html
348     ///
349     /// ```
350     /// let s1 = &[1, 2, 3];
351     /// let s2 = &[4, 5, 6];
352     ///
353     /// let mut iter = s1.iter().zip(s2);
354     ///
355     /// assert_eq!(iter.next(), Some((&1, &4)));
356     /// assert_eq!(iter.next(), Some((&2, &5)));
357     /// assert_eq!(iter.next(), Some((&3, &6)));
358     /// assert_eq!(iter.next(), None);
359     /// ```
360     ///
361     /// `zip()` is often used to zip an infinite iterator to a finite one.
362     /// This works because the finite iterator will eventually return `None`,
363     /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
364     ///
365     /// ```
366     /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
367     ///
368     /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
369     ///
370     /// assert_eq!((0, 'f'), enumerate[0]);
371     /// assert_eq!((0, 'f'), zipper[0]);
372     ///
373     /// assert_eq!((1, 'o'), enumerate[1]);
374     /// assert_eq!((1, 'o'), zipper[1]);
375     ///
376     /// assert_eq!((2, 'o'), enumerate[2]);
377     /// assert_eq!((2, 'o'), zipper[2]);
378     /// ```
379     ///
380     /// [`enumerate()`]: trait.Iterator.html#method.enumerate
381     #[inline]
382     #[stable(feature = "rust1", since = "1.0.0")]
383     fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
384         Self: Sized, U: IntoIterator
385     {
386         Zip::new(self, other.into_iter())
387     }
388
389     /// Takes a closure and creates an iterator which calls that closure on each
390     /// element.
391     ///
392     /// `map()` transforms one iterator into another, by means of its argument:
393     /// something that implements `FnMut`. It produces a new iterator which
394     /// calls this closure on each element of the original iterator.
395     ///
396     /// If you are good at thinking in types, you can think of `map()` like this:
397     /// If you have an iterator that gives you elements of some type `A`, and
398     /// you want an iterator of some other type `B`, you can use `map()`,
399     /// passing a closure that takes an `A` and returns a `B`.
400     ///
401     /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
402     /// lazy, it is best used when you're already working with other iterators.
403     /// If you're doing some sort of looping for a side effect, it's considered
404     /// more idiomatic to use [`for`] than `map()`.
405     ///
406     /// [`for`]: ../../book/loops.html#for
407     ///
408     /// # Examples
409     ///
410     /// Basic usage:
411     ///
412     /// ```
413     /// let a = [1, 2, 3];
414     ///
415     /// let mut iter = a.into_iter().map(|x| 2 * x);
416     ///
417     /// assert_eq!(iter.next(), Some(2));
418     /// assert_eq!(iter.next(), Some(4));
419     /// assert_eq!(iter.next(), Some(6));
420     /// assert_eq!(iter.next(), None);
421     /// ```
422     ///
423     /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
424     ///
425     /// ```
426     /// # #![allow(unused_must_use)]
427     /// // don't do this:
428     /// (0..5).map(|x| println!("{}", x));
429     ///
430     /// // it won't even execute, as it is lazy. Rust will warn you about this.
431     ///
432     /// // Instead, use for:
433     /// for x in 0..5 {
434     ///     println!("{}", x);
435     /// }
436     /// ```
437     #[inline]
438     #[stable(feature = "rust1", since = "1.0.0")]
439     fn map<B, F>(self, f: F) -> Map<Self, F> where
440         Self: Sized, F: FnMut(Self::Item) -> B,
441     {
442         Map{iter: self, f: f}
443     }
444
445     /// Creates an iterator which uses a closure to determine if an element
446     /// should be yielded.
447     ///
448     /// The closure must return `true` or `false`. `filter()` creates an
449     /// iterator which calls this closure on each element. If the closure
450     /// returns `true`, then the element is returned. If the closure returns
451     /// `false`, it will try again, and call the closure on the next element,
452     /// seeing if it passes the test.
453     ///
454     /// # Examples
455     ///
456     /// Basic usage:
457     ///
458     /// ```
459     /// let a = [0i32, 1, 2];
460     ///
461     /// let mut iter = a.into_iter().filter(|x| x.is_positive());
462     ///
463     /// assert_eq!(iter.next(), Some(&1));
464     /// assert_eq!(iter.next(), Some(&2));
465     /// assert_eq!(iter.next(), None);
466     /// ```
467     ///
468     /// Because the closure passed to `filter()` takes a reference, and many
469     /// iterators iterate over references, this leads to a possibly confusing
470     /// situation, where the type of the closure is a double reference:
471     ///
472     /// ```
473     /// let a = [0, 1, 2];
474     ///
475     /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
476     ///
477     /// assert_eq!(iter.next(), Some(&2));
478     /// assert_eq!(iter.next(), None);
479     /// ```
480     ///
481     /// It's common to instead use destructuring on the argument to strip away
482     /// one:
483     ///
484     /// ```
485     /// let a = [0, 1, 2];
486     ///
487     /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
488     ///
489     /// assert_eq!(iter.next(), Some(&2));
490     /// assert_eq!(iter.next(), None);
491     /// ```
492     ///
493     /// or both:
494     ///
495     /// ```
496     /// let a = [0, 1, 2];
497     ///
498     /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
499     ///
500     /// assert_eq!(iter.next(), Some(&2));
501     /// assert_eq!(iter.next(), None);
502     /// ```
503     ///
504     /// of these layers.
505     #[inline]
506     #[stable(feature = "rust1", since = "1.0.0")]
507     fn filter<P>(self, predicate: P) -> Filter<Self, P> where
508         Self: Sized, P: FnMut(&Self::Item) -> bool,
509     {
510         Filter{iter: self, predicate: predicate}
511     }
512
513     /// Creates an iterator that both filters and maps.
514     ///
515     /// The closure must return an [`Option<T>`]. `filter_map()` creates an
516     /// iterator which calls this closure on each element. If the closure
517     /// returns `Some(element)`, then that element is returned. If the
518     /// closure returns `None`, it will try again, and call the closure on the
519     /// next element, seeing if it will return `Some`.
520     ///
521     /// [`Option<T>`]: ../../std/option/enum.Option.html
522     ///
523     /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
524     /// part:
525     ///
526     /// [`filter()`]: #method.filter
527     /// [`map()`]: #method.map
528     ///
529     /// > If the closure returns `Some(element)`, then that element is returned.
530     ///
531     /// In other words, it removes the [`Option<T>`] layer automatically. If your
532     /// mapping is already returning an [`Option<T>`] and you want to skip over
533     /// `None`s, then `filter_map()` is much, much nicer to use.
534     ///
535     /// # Examples
536     ///
537     /// Basic usage:
538     ///
539     /// ```
540     /// let a = ["1", "2", "lol"];
541     ///
542     /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
543     ///
544     /// assert_eq!(iter.next(), Some(1));
545     /// assert_eq!(iter.next(), Some(2));
546     /// assert_eq!(iter.next(), None);
547     /// ```
548     ///
549     /// Here's the same example, but with [`filter()`] and [`map()`]:
550     ///
551     /// ```
552     /// let a = ["1", "2", "lol"];
553     ///
554     /// let mut iter = a.iter()
555     ///                 .map(|s| s.parse().ok())
556     ///                 .filter(|s| s.is_some());
557     ///
558     /// assert_eq!(iter.next(), Some(Some(1)));
559     /// assert_eq!(iter.next(), Some(Some(2)));
560     /// assert_eq!(iter.next(), None);
561     /// ```
562     ///
563     /// There's an extra layer of `Some` in there.
564     #[inline]
565     #[stable(feature = "rust1", since = "1.0.0")]
566     fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
567         Self: Sized, F: FnMut(Self::Item) -> Option<B>,
568     {
569         FilterMap { iter: self, f: f }
570     }
571
572     /// Creates an iterator which gives the current iteration count as well as
573     /// the next value.
574     ///
575     /// The iterator returned yields pairs `(i, val)`, where `i` is the
576     /// current index of iteration and `val` is the value returned by the
577     /// iterator.
578     ///
579     /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
580     /// different sized integer, the [`zip()`] function provides similar
581     /// functionality.
582     ///
583     /// [`usize`]: ../../std/primitive.usize.html
584     /// [`zip()`]: #method.zip
585     ///
586     /// # Overflow Behavior
587     ///
588     /// The method does no guarding against overflows, so enumerating more than
589     /// [`usize::MAX`] elements either produces the wrong result or panics. If
590     /// debug assertions are enabled, a panic is guaranteed.
591     ///
592     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
593     ///
594     /// # Panics
595     ///
596     /// The returned iterator might panic if the to-be-returned index would
597     /// overflow a `usize`.
598     ///
599     /// # Examples
600     ///
601     /// ```
602     /// let a = ['a', 'b', 'c'];
603     ///
604     /// let mut iter = a.iter().enumerate();
605     ///
606     /// assert_eq!(iter.next(), Some((0, &'a')));
607     /// assert_eq!(iter.next(), Some((1, &'b')));
608     /// assert_eq!(iter.next(), Some((2, &'c')));
609     /// assert_eq!(iter.next(), None);
610     /// ```
611     #[inline]
612     #[stable(feature = "rust1", since = "1.0.0")]
613     fn enumerate(self) -> Enumerate<Self> where Self: Sized {
614         Enumerate { iter: self, count: 0 }
615     }
616
617     /// Creates an iterator which can use `peek` to look at the next element of
618     /// the iterator without consuming it.
619     ///
620     /// Adds a [`peek()`] method to an iterator. See its documentation for
621     /// more information.
622     ///
623     /// Note that the underlying iterator is still advanced when `peek` is
624     /// called for the first time: In order to retrieve the next element,
625     /// `next` is called on the underlying iterator, hence any side effects of
626     /// the `next` method will occur.
627     ///
628     /// [`peek()`]: struct.Peekable.html#method.peek
629     ///
630     /// # Examples
631     ///
632     /// Basic usage:
633     ///
634     /// ```
635     /// let xs = [1, 2, 3];
636     ///
637     /// let mut iter = xs.iter().peekable();
638     ///
639     /// // peek() lets us see into the future
640     /// assert_eq!(iter.peek(), Some(&&1));
641     /// assert_eq!(iter.next(), Some(&1));
642     ///
643     /// assert_eq!(iter.next(), Some(&2));
644     ///
645     /// // we can peek() multiple times, the iterator won't advance
646     /// assert_eq!(iter.peek(), Some(&&3));
647     /// assert_eq!(iter.peek(), Some(&&3));
648     ///
649     /// assert_eq!(iter.next(), Some(&3));
650     ///
651     /// // after the iterator is finished, so is peek()
652     /// assert_eq!(iter.peek(), None);
653     /// assert_eq!(iter.next(), None);
654     /// ```
655     #[inline]
656     #[stable(feature = "rust1", since = "1.0.0")]
657     fn peekable(self) -> Peekable<Self> where Self: Sized {
658         Peekable{iter: self, peeked: None}
659     }
660
661     /// Creates an iterator that [`skip()`]s elements based on a predicate.
662     ///
663     /// [`skip()`]: #method.skip
664     ///
665     /// `skip_while()` takes a closure as an argument. It will call this
666     /// closure on each element of the iterator, and ignore elements
667     /// until it returns `false`.
668     ///
669     /// After `false` is returned, `skip_while()`'s job is over, and the
670     /// rest of the elements are yielded.
671     ///
672     /// # Examples
673     ///
674     /// Basic usage:
675     ///
676     /// ```
677     /// let a = [-1i32, 0, 1];
678     ///
679     /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
680     ///
681     /// assert_eq!(iter.next(), Some(&0));
682     /// assert_eq!(iter.next(), Some(&1));
683     /// assert_eq!(iter.next(), None);
684     /// ```
685     ///
686     /// Because the closure passed to `skip_while()` takes a reference, and many
687     /// iterators iterate over references, this leads to a possibly confusing
688     /// situation, where the type of the closure is a double reference:
689     ///
690     /// ```
691     /// let a = [-1, 0, 1];
692     ///
693     /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
694     ///
695     /// assert_eq!(iter.next(), Some(&0));
696     /// assert_eq!(iter.next(), Some(&1));
697     /// assert_eq!(iter.next(), None);
698     /// ```
699     ///
700     /// Stopping after an initial `false`:
701     ///
702     /// ```
703     /// let a = [-1, 0, 1, -2];
704     ///
705     /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
706     ///
707     /// assert_eq!(iter.next(), Some(&0));
708     /// assert_eq!(iter.next(), Some(&1));
709     ///
710     /// // while this would have been false, since we already got a false,
711     /// // skip_while() isn't used any more
712     /// assert_eq!(iter.next(), Some(&-2));
713     ///
714     /// assert_eq!(iter.next(), None);
715     /// ```
716     #[inline]
717     #[stable(feature = "rust1", since = "1.0.0")]
718     fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
719         Self: Sized, P: FnMut(&Self::Item) -> bool,
720     {
721         SkipWhile{iter: self, flag: false, predicate: predicate}
722     }
723
724     /// Creates an iterator that yields elements based on a predicate.
725     ///
726     /// `take_while()` takes a closure as an argument. It will call this
727     /// closure on each element of the iterator, and yield elements
728     /// while it returns `true`.
729     ///
730     /// After `false` is returned, `take_while()`'s job is over, and the
731     /// rest of the elements are ignored.
732     ///
733     /// # Examples
734     ///
735     /// Basic usage:
736     ///
737     /// ```
738     /// let a = [-1i32, 0, 1];
739     ///
740     /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
741     ///
742     /// assert_eq!(iter.next(), Some(&-1));
743     /// assert_eq!(iter.next(), None);
744     /// ```
745     ///
746     /// Because the closure passed to `take_while()` takes a reference, and many
747     /// iterators iterate over references, this leads to a possibly confusing
748     /// situation, where the type of the closure is a double reference:
749     ///
750     /// ```
751     /// let a = [-1, 0, 1];
752     ///
753     /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
754     ///
755     /// assert_eq!(iter.next(), Some(&-1));
756     /// assert_eq!(iter.next(), None);
757     /// ```
758     ///
759     /// Stopping after an initial `false`:
760     ///
761     /// ```
762     /// let a = [-1, 0, 1, -2];
763     ///
764     /// let mut iter = a.into_iter().take_while(|x| **x < 0);
765     ///
766     /// assert_eq!(iter.next(), Some(&-1));
767     ///
768     /// // We have more elements that are less than zero, but since we already
769     /// // got a false, take_while() isn't used any more
770     /// assert_eq!(iter.next(), None);
771     /// ```
772     ///
773     /// Because `take_while()` needs to look at the value in order to see if it
774     /// should be included or not, consuming iterators will see that it is
775     /// removed:
776     ///
777     /// ```
778     /// let a = [1, 2, 3, 4];
779     /// let mut iter = a.into_iter();
780     ///
781     /// let result: Vec<i32> = iter.by_ref()
782     ///                            .take_while(|n| **n != 3)
783     ///                            .cloned()
784     ///                            .collect();
785     ///
786     /// assert_eq!(result, &[1, 2]);
787     ///
788     /// let result: Vec<i32> = iter.cloned().collect();
789     ///
790     /// assert_eq!(result, &[4]);
791     /// ```
792     ///
793     /// The `3` is no longer there, because it was consumed in order to see if
794     /// the iteration should stop, but wasn't placed back into the iterator or
795     /// some similar thing.
796     #[inline]
797     #[stable(feature = "rust1", since = "1.0.0")]
798     fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
799         Self: Sized, P: FnMut(&Self::Item) -> bool,
800     {
801         TakeWhile{iter: self, flag: false, predicate: predicate}
802     }
803
804     /// Creates an iterator that skips the first `n` elements.
805     ///
806     /// After they have been consumed, the rest of the elements are yielded.
807     ///
808     /// # Examples
809     ///
810     /// Basic usage:
811     ///
812     /// ```
813     /// let a = [1, 2, 3];
814     ///
815     /// let mut iter = a.iter().skip(2);
816     ///
817     /// assert_eq!(iter.next(), Some(&3));
818     /// assert_eq!(iter.next(), None);
819     /// ```
820     #[inline]
821     #[stable(feature = "rust1", since = "1.0.0")]
822     fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
823         Skip{iter: self, n: n}
824     }
825
826     /// Creates an iterator that yields its first `n` elements.
827     ///
828     /// # Examples
829     ///
830     /// Basic usage:
831     ///
832     /// ```
833     /// let a = [1, 2, 3];
834     ///
835     /// let mut iter = a.iter().take(2);
836     ///
837     /// assert_eq!(iter.next(), Some(&1));
838     /// assert_eq!(iter.next(), Some(&2));
839     /// assert_eq!(iter.next(), None);
840     /// ```
841     ///
842     /// `take()` is often used with an infinite iterator, to make it finite:
843     ///
844     /// ```
845     /// let mut iter = (0..).take(3);
846     ///
847     /// assert_eq!(iter.next(), Some(0));
848     /// assert_eq!(iter.next(), Some(1));
849     /// assert_eq!(iter.next(), Some(2));
850     /// assert_eq!(iter.next(), None);
851     /// ```
852     #[inline]
853     #[stable(feature = "rust1", since = "1.0.0")]
854     fn take(self, n: usize) -> Take<Self> where Self: Sized, {
855         Take{iter: self, n: n}
856     }
857
858     /// An iterator adaptor similar to [`fold()`] that holds internal state and
859     /// produces a new iterator.
860     ///
861     /// [`fold()`]: #method.fold
862     ///
863     /// `scan()` takes two arguments: an initial value which seeds the internal
864     /// state, and a closure with two arguments, the first being a mutable
865     /// reference to the internal state and the second an iterator element.
866     /// The closure can assign to the internal state to share state between
867     /// iterations.
868     ///
869     /// On iteration, the closure will be applied to each element of the
870     /// iterator and the return value from the closure, an [`Option`], is
871     /// yielded by the iterator.
872     ///
873     /// [`Option`]: ../../std/option/enum.Option.html
874     ///
875     /// # Examples
876     ///
877     /// Basic usage:
878     ///
879     /// ```
880     /// let a = [1, 2, 3];
881     ///
882     /// let mut iter = a.iter().scan(1, |state, &x| {
883     ///     // each iteration, we'll multiply the state by the element
884     ///     *state = *state * x;
885     ///
886     ///     // the value passed on to the next iteration
887     ///     Some(*state)
888     /// });
889     ///
890     /// assert_eq!(iter.next(), Some(1));
891     /// assert_eq!(iter.next(), Some(2));
892     /// assert_eq!(iter.next(), Some(6));
893     /// assert_eq!(iter.next(), None);
894     /// ```
895     #[inline]
896     #[stable(feature = "rust1", since = "1.0.0")]
897     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
898         where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
899     {
900         Scan{iter: self, f: f, state: initial_state}
901     }
902
903     /// Creates an iterator that works like map, but flattens nested structure.
904     ///
905     /// The [`map()`] adapter is very useful, but only when the closure
906     /// argument produces values. If it produces an iterator instead, there's
907     /// an extra layer of indirection. `flat_map()` will remove this extra layer
908     /// on its own.
909     ///
910     /// [`map()`]: #method.map
911     ///
912     /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
913     /// one item for each element, and `flat_map()`'s closure returns an
914     /// iterator for each element.
915     ///
916     /// # Examples
917     ///
918     /// Basic usage:
919     ///
920     /// ```
921     /// let words = ["alpha", "beta", "gamma"];
922     ///
923     /// // chars() returns an iterator
924     /// let merged: String = words.iter()
925     ///                           .flat_map(|s| s.chars())
926     ///                           .collect();
927     /// assert_eq!(merged, "alphabetagamma");
928     /// ```
929     #[inline]
930     #[stable(feature = "rust1", since = "1.0.0")]
931     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
932         where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
933     {
934         FlatMap{iter: self, f: f, frontiter: None, backiter: None }
935     }
936
937     /// Creates an iterator which ends after the first `None`.
938     ///
939     /// After an iterator returns `None`, future calls may or may not yield
940     /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
941     /// `None` is given, it will always return `None` forever.
942     ///
943     /// # Examples
944     ///
945     /// Basic usage:
946     ///
947     /// ```
948     /// // an iterator which alternates between Some and None
949     /// struct Alternate {
950     ///     state: i32,
951     /// }
952     ///
953     /// impl Iterator for Alternate {
954     ///     type Item = i32;
955     ///
956     ///     fn next(&mut self) -> Option<i32> {
957     ///         let val = self.state;
958     ///         self.state = self.state + 1;
959     ///
960     ///         // if it's even, Some(i32), else None
961     ///         if val % 2 == 0 {
962     ///             Some(val)
963     ///         } else {
964     ///             None
965     ///         }
966     ///     }
967     /// }
968     ///
969     /// let mut iter = Alternate { state: 0 };
970     ///
971     /// // we can see our iterator going back and forth
972     /// assert_eq!(iter.next(), Some(0));
973     /// assert_eq!(iter.next(), None);
974     /// assert_eq!(iter.next(), Some(2));
975     /// assert_eq!(iter.next(), None);
976     ///
977     /// // however, once we fuse it...
978     /// let mut iter = iter.fuse();
979     ///
980     /// assert_eq!(iter.next(), Some(4));
981     /// assert_eq!(iter.next(), None);
982     ///
983     /// // it will always return None after the first time.
984     /// assert_eq!(iter.next(), None);
985     /// assert_eq!(iter.next(), None);
986     /// assert_eq!(iter.next(), None);
987     /// ```
988     #[inline]
989     #[stable(feature = "rust1", since = "1.0.0")]
990     fn fuse(self) -> Fuse<Self> where Self: Sized {
991         Fuse{iter: self, done: false}
992     }
993
994     /// Do something with each element of an iterator, passing the value on.
995     ///
996     /// When using iterators, you'll often chain several of them together.
997     /// While working on such code, you might want to check out what's
998     /// happening at various parts in the pipeline. To do that, insert
999     /// a call to `inspect()`.
1000     ///
1001     /// It's much more common for `inspect()` to be used as a debugging tool
1002     /// than to exist in your final code, but never say never.
1003     ///
1004     /// # Examples
1005     ///
1006     /// Basic usage:
1007     ///
1008     /// ```
1009     /// let a = [1, 4, 2, 3];
1010     ///
1011     /// // this iterator sequence is complex.
1012     /// let sum = a.iter()
1013     ///             .cloned()
1014     ///             .filter(|&x| x % 2 == 0)
1015     ///             .fold(0, |sum, i| sum + i);
1016     ///
1017     /// println!("{}", sum);
1018     ///
1019     /// // let's add some inspect() calls to investigate what's happening
1020     /// let sum = a.iter()
1021     ///             .cloned()
1022     ///             .inspect(|x| println!("about to filter: {}", x))
1023     ///             .filter(|&x| x % 2 == 0)
1024     ///             .inspect(|x| println!("made it through filter: {}", x))
1025     ///             .fold(0, |sum, i| sum + i);
1026     ///
1027     /// println!("{}", sum);
1028     /// ```
1029     ///
1030     /// This will print:
1031     ///
1032     /// ```text
1033     /// about to filter: 1
1034     /// about to filter: 4
1035     /// made it through filter: 4
1036     /// about to filter: 2
1037     /// made it through filter: 2
1038     /// about to filter: 3
1039     /// 6
1040     /// ```
1041     #[inline]
1042     #[stable(feature = "rust1", since = "1.0.0")]
1043     fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1044         Self: Sized, F: FnMut(&Self::Item),
1045     {
1046         Inspect{iter: self, f: f}
1047     }
1048
1049     /// Borrows an iterator, rather than consuming it.
1050     ///
1051     /// This is useful to allow applying iterator adaptors while still
1052     /// retaining ownership of the original iterator.
1053     ///
1054     /// # Examples
1055     ///
1056     /// Basic usage:
1057     ///
1058     /// ```
1059     /// let a = [1, 2, 3];
1060     ///
1061     /// let iter = a.into_iter();
1062     ///
1063     /// let sum: i32 = iter.take(5)
1064     ///                    .fold(0, |acc, &i| acc + i );
1065     ///
1066     /// assert_eq!(sum, 6);
1067     ///
1068     /// // if we try to use iter again, it won't work. The following line
1069     /// // gives "error: use of moved value: `iter`
1070     /// // assert_eq!(iter.next(), None);
1071     ///
1072     /// // let's try that again
1073     /// let a = [1, 2, 3];
1074     ///
1075     /// let mut iter = a.into_iter();
1076     ///
1077     /// // instead, we add in a .by_ref()
1078     /// let sum: i32 = iter.by_ref()
1079     ///                    .take(2)
1080     ///                    .fold(0, |acc, &i| acc + i );
1081     ///
1082     /// assert_eq!(sum, 3);
1083     ///
1084     /// // now this is just fine:
1085     /// assert_eq!(iter.next(), Some(&3));
1086     /// assert_eq!(iter.next(), None);
1087     /// ```
1088     #[stable(feature = "rust1", since = "1.0.0")]
1089     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1090
1091     /// Transforms an iterator into a collection.
1092     ///
1093     /// `collect()` can take anything iterable, and turn it into a relevant
1094     /// collection. This is one of the more powerful methods in the standard
1095     /// library, used in a variety of contexts.
1096     ///
1097     /// The most basic pattern in which `collect()` is used is to turn one
1098     /// collection into another. You take a collection, call `iter()` on it,
1099     /// do a bunch of transformations, and then `collect()` at the end.
1100     ///
1101     /// One of the keys to `collect()`'s power is that many things you might
1102     /// not think of as 'collections' actually are. For example, a [`String`]
1103     /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1104     /// be thought of as single `Result<Collection<T>, E>`. See the examples
1105     /// below for more.
1106     ///
1107     /// [`String`]: ../../std/string/struct.String.html
1108     /// [`Result<T, E>`]: ../../std/result/enum.Result.html
1109     /// [`char`]: ../../std/primitive.char.html
1110     ///
1111     /// Because `collect()` is so general, it can cause problems with type
1112     /// inference. As such, `collect()` is one of the few times you'll see
1113     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1114     /// helps the inference algorithm understand specifically which collection
1115     /// you're trying to collect into.
1116     ///
1117     /// # Examples
1118     ///
1119     /// Basic usage:
1120     ///
1121     /// ```
1122     /// let a = [1, 2, 3];
1123     ///
1124     /// let doubled: Vec<i32> = a.iter()
1125     ///                          .map(|&x| x * 2)
1126     ///                          .collect();
1127     ///
1128     /// assert_eq!(vec![2, 4, 6], doubled);
1129     /// ```
1130     ///
1131     /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1132     /// we could collect into, for example, a [`VecDeque<T>`] instead:
1133     ///
1134     /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1135     ///
1136     /// ```
1137     /// use std::collections::VecDeque;
1138     ///
1139     /// let a = [1, 2, 3];
1140     ///
1141     /// let doubled: VecDeque<i32> = a.iter()
1142     ///                               .map(|&x| x * 2)
1143     ///                               .collect();
1144     ///
1145     /// assert_eq!(2, doubled[0]);
1146     /// assert_eq!(4, doubled[1]);
1147     /// assert_eq!(6, doubled[2]);
1148     /// ```
1149     ///
1150     /// Using the 'turbofish' instead of annotating `doubled`:
1151     ///
1152     /// ```
1153     /// let a = [1, 2, 3];
1154     ///
1155     /// let doubled = a.iter()
1156     ///                .map(|&x| x * 2)
1157     ///                .collect::<Vec<i32>>();
1158     ///
1159     /// assert_eq!(vec![2, 4, 6], doubled);
1160     /// ```
1161     ///
1162     /// Because `collect()` cares about what you're collecting into, you can
1163     /// still use a partial type hint, `_`, with the turbofish:
1164     ///
1165     /// ```
1166     /// let a = [1, 2, 3];
1167     ///
1168     /// let doubled = a.iter()
1169     ///                .map(|&x| x * 2)
1170     ///                .collect::<Vec<_>>();
1171     ///
1172     /// assert_eq!(vec![2, 4, 6], doubled);
1173     /// ```
1174     ///
1175     /// Using `collect()` to make a [`String`]:
1176     ///
1177     /// ```
1178     /// let chars = ['g', 'd', 'k', 'k', 'n'];
1179     ///
1180     /// let hello: String = chars.iter()
1181     ///                          .map(|&x| x as u8)
1182     ///                          .map(|x| (x + 1) as char)
1183     ///                          .collect();
1184     ///
1185     /// assert_eq!("hello", hello);
1186     /// ```
1187     ///
1188     /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1189     /// see if any of them failed:
1190     ///
1191     /// ```
1192     /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1193     ///
1194     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1195     ///
1196     /// // gives us the first error
1197     /// assert_eq!(Err("nope"), result);
1198     ///
1199     /// let results = [Ok(1), Ok(3)];
1200     ///
1201     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1202     ///
1203     /// // gives us the list of answers
1204     /// assert_eq!(Ok(vec![1, 3]), result);
1205     /// ```
1206     #[inline]
1207     #[stable(feature = "rust1", since = "1.0.0")]
1208     fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1209         FromIterator::from_iter(self)
1210     }
1211
1212     /// Consumes an iterator, creating two collections from it.
1213     ///
1214     /// The predicate passed to `partition()` can return `true`, or `false`.
1215     /// `partition()` returns a pair, all of the elements for which it returned
1216     /// `true`, and all of the elements for which it returned `false`.
1217     ///
1218     /// # Examples
1219     ///
1220     /// Basic usage:
1221     ///
1222     /// ```
1223     /// let a = [1, 2, 3];
1224     ///
1225     /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1226     ///                                          .partition(|&n| n % 2 == 0);
1227     ///
1228     /// assert_eq!(even, vec![2]);
1229     /// assert_eq!(odd, vec![1, 3]);
1230     /// ```
1231     #[stable(feature = "rust1", since = "1.0.0")]
1232     fn partition<B, F>(self, mut f: F) -> (B, B) where
1233         Self: Sized,
1234         B: Default + Extend<Self::Item>,
1235         F: FnMut(&Self::Item) -> bool
1236     {
1237         let mut left: B = Default::default();
1238         let mut right: B = Default::default();
1239
1240         for x in self {
1241             if f(&x) {
1242                 left.extend(Some(x))
1243             } else {
1244                 right.extend(Some(x))
1245             }
1246         }
1247
1248         (left, right)
1249     }
1250
1251     /// An iterator adaptor that applies a function, producing a single, final value.
1252     ///
1253     /// `fold()` takes two arguments: an initial value, and a closure with two
1254     /// arguments: an 'accumulator', and an element. The closure returns the value that
1255     /// the accumulator should have for the next iteration.
1256     ///
1257     /// The initial value is the value the accumulator will have on the first
1258     /// call.
1259     ///
1260     /// After applying this closure to every element of the iterator, `fold()`
1261     /// returns the accumulator.
1262     ///
1263     /// This operation is sometimes called 'reduce' or 'inject'.
1264     ///
1265     /// Folding is useful whenever you have a collection of something, and want
1266     /// to produce a single value from it.
1267     ///
1268     /// # Examples
1269     ///
1270     /// Basic usage:
1271     ///
1272     /// ```
1273     /// let a = [1, 2, 3];
1274     ///
1275     /// // the sum of all of the elements of a
1276     /// let sum = a.iter()
1277     ///            .fold(0, |acc, &x| acc + x);
1278     ///
1279     /// assert_eq!(sum, 6);
1280     /// ```
1281     ///
1282     /// Let's walk through each step of the iteration here:
1283     ///
1284     /// | element | acc | x | result |
1285     /// |---------|-----|---|--------|
1286     /// |         | 0   |   |        |
1287     /// | 1       | 0   | 1 | 1      |
1288     /// | 2       | 1   | 2 | 3      |
1289     /// | 3       | 3   | 3 | 6      |
1290     ///
1291     /// And so, our final result, `6`.
1292     ///
1293     /// It's common for people who haven't used iterators a lot to
1294     /// use a `for` loop with a list of things to build up a result. Those
1295     /// can be turned into `fold()`s:
1296     ///
1297     /// ```
1298     /// let numbers = [1, 2, 3, 4, 5];
1299     ///
1300     /// let mut result = 0;
1301     ///
1302     /// // for loop:
1303     /// for i in &numbers {
1304     ///     result = result + i;
1305     /// }
1306     ///
1307     /// // fold:
1308     /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1309     ///
1310     /// // they're the same
1311     /// assert_eq!(result, result2);
1312     /// ```
1313     #[inline]
1314     #[stable(feature = "rust1", since = "1.0.0")]
1315     fn fold<B, F>(self, init: B, mut f: F) -> B where
1316         Self: Sized, F: FnMut(B, Self::Item) -> B,
1317     {
1318         let mut accum = init;
1319         for x in self {
1320             accum = f(accum, x);
1321         }
1322         accum
1323     }
1324
1325     /// Tests if every element of the iterator matches a predicate.
1326     ///
1327     /// `all()` takes a closure that returns `true` or `false`. It applies
1328     /// this closure to each element of the iterator, and if they all return
1329     /// `true`, then so does `all()`. If any of them return `false`, it
1330     /// returns `false`.
1331     ///
1332     /// `all()` is short-circuiting; in other words, it will stop processing
1333     /// as soon as it finds a `false`, given that no matter what else happens,
1334     /// the result will also be `false`.
1335     ///
1336     /// An empty iterator returns `true`.
1337     ///
1338     /// # Examples
1339     ///
1340     /// Basic usage:
1341     ///
1342     /// ```
1343     /// let a = [1, 2, 3];
1344     ///
1345     /// assert!(a.iter().all(|&x| x > 0));
1346     ///
1347     /// assert!(!a.iter().all(|&x| x > 2));
1348     /// ```
1349     ///
1350     /// Stopping at the first `false`:
1351     ///
1352     /// ```
1353     /// let a = [1, 2, 3];
1354     ///
1355     /// let mut iter = a.iter();
1356     ///
1357     /// assert!(!iter.all(|&x| x != 2));
1358     ///
1359     /// // we can still use `iter`, as there are more elements.
1360     /// assert_eq!(iter.next(), Some(&3));
1361     /// ```
1362     #[inline]
1363     #[stable(feature = "rust1", since = "1.0.0")]
1364     fn all<F>(&mut self, mut f: F) -> bool where
1365         Self: Sized, F: FnMut(Self::Item) -> bool
1366     {
1367         for x in self {
1368             if !f(x) {
1369                 return false;
1370             }
1371         }
1372         true
1373     }
1374
1375     /// Tests if any element of the iterator matches a predicate.
1376     ///
1377     /// `any()` takes a closure that returns `true` or `false`. It applies
1378     /// this closure to each element of the iterator, and if any of them return
1379     /// `true`, then so does `any()`. If they all return `false`, it
1380     /// returns `false`.
1381     ///
1382     /// `any()` is short-circuiting; in other words, it will stop processing
1383     /// as soon as it finds a `true`, given that no matter what else happens,
1384     /// the result will also be `true`.
1385     ///
1386     /// An empty iterator returns `false`.
1387     ///
1388     /// # Examples
1389     ///
1390     /// Basic usage:
1391     ///
1392     /// ```
1393     /// let a = [1, 2, 3];
1394     ///
1395     /// assert!(a.iter().any(|&x| x > 0));
1396     ///
1397     /// assert!(!a.iter().any(|&x| x > 5));
1398     /// ```
1399     ///
1400     /// Stopping at the first `true`:
1401     ///
1402     /// ```
1403     /// let a = [1, 2, 3];
1404     ///
1405     /// let mut iter = a.iter();
1406     ///
1407     /// assert!(iter.any(|&x| x != 2));
1408     ///
1409     /// // we can still use `iter`, as there are more elements.
1410     /// assert_eq!(iter.next(), Some(&2));
1411     /// ```
1412     #[inline]
1413     #[stable(feature = "rust1", since = "1.0.0")]
1414     fn any<F>(&mut self, mut f: F) -> bool where
1415         Self: Sized,
1416         F: FnMut(Self::Item) -> bool
1417     {
1418         for x in self {
1419             if f(x) {
1420                 return true;
1421             }
1422         }
1423         false
1424     }
1425
1426     /// Searches for an element of an iterator that satisfies a predicate.
1427     ///
1428     /// `find()` takes a closure that returns `true` or `false`. It applies
1429     /// this closure to each element of the iterator, and if any of them return
1430     /// `true`, then `find()` returns `Some(element)`. If they all return
1431     /// `false`, it returns `None`.
1432     ///
1433     /// `find()` is short-circuiting; in other words, it will stop processing
1434     /// as soon as the closure returns `true`.
1435     ///
1436     /// Because `find()` takes a reference, and many iterators iterate over
1437     /// references, this leads to a possibly confusing situation where the
1438     /// argument is a double reference. You can see this effect in the
1439     /// examples below, with `&&x`.
1440     ///
1441     /// # Examples
1442     ///
1443     /// Basic usage:
1444     ///
1445     /// ```
1446     /// let a = [1, 2, 3];
1447     ///
1448     /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1449     ///
1450     /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1451     /// ```
1452     ///
1453     /// Stopping at the first `true`:
1454     ///
1455     /// ```
1456     /// let a = [1, 2, 3];
1457     ///
1458     /// let mut iter = a.iter();
1459     ///
1460     /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1461     ///
1462     /// // we can still use `iter`, as there are more elements.
1463     /// assert_eq!(iter.next(), Some(&3));
1464     /// ```
1465     #[inline]
1466     #[stable(feature = "rust1", since = "1.0.0")]
1467     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1468         Self: Sized,
1469         P: FnMut(&Self::Item) -> bool,
1470     {
1471         for x in self {
1472             if predicate(&x) { return Some(x) }
1473         }
1474         None
1475     }
1476
1477     /// Searches for an element in an iterator, returning its index.
1478     ///
1479     /// `position()` takes a closure that returns `true` or `false`. It applies
1480     /// this closure to each element of the iterator, and if one of them
1481     /// returns `true`, then `position()` returns `Some(index)`. If all of
1482     /// them return `false`, it returns `None`.
1483     ///
1484     /// `position()` is short-circuiting; in other words, it will stop
1485     /// processing as soon as it finds a `true`.
1486     ///
1487     /// # Overflow Behavior
1488     ///
1489     /// The method does no guarding against overflows, so if there are more
1490     /// than `usize::MAX` non-matching elements, it either produces the wrong
1491     /// result or panics. If debug assertions are enabled, a panic is
1492     /// guaranteed.
1493     ///
1494     /// # Panics
1495     ///
1496     /// This function might panic if the iterator has more than `usize::MAX`
1497     /// non-matching elements.
1498     ///
1499     /// # Examples
1500     ///
1501     /// Basic usage:
1502     ///
1503     /// ```
1504     /// let a = [1, 2, 3];
1505     ///
1506     /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1507     ///
1508     /// assert_eq!(a.iter().position(|&x| x == 5), None);
1509     /// ```
1510     ///
1511     /// Stopping at the first `true`:
1512     ///
1513     /// ```
1514     /// let a = [1, 2, 3];
1515     ///
1516     /// let mut iter = a.iter();
1517     ///
1518     /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1519     ///
1520     /// // we can still use `iter`, as there are more elements.
1521     /// assert_eq!(iter.next(), Some(&3));
1522     /// ```
1523     #[inline]
1524     #[stable(feature = "rust1", since = "1.0.0")]
1525     fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1526         Self: Sized,
1527         P: FnMut(Self::Item) -> bool,
1528     {
1529         // `enumerate` might overflow.
1530         for (i, x) in self.enumerate() {
1531             if predicate(x) {
1532                 return Some(i);
1533             }
1534         }
1535         None
1536     }
1537
1538     /// Searches for an element in an iterator from the right, returning its
1539     /// index.
1540     ///
1541     /// `rposition()` takes a closure that returns `true` or `false`. It applies
1542     /// this closure to each element of the iterator, starting from the end,
1543     /// and if one of them returns `true`, then `rposition()` returns
1544     /// `Some(index)`. If all of them return `false`, it returns `None`.
1545     ///
1546     /// `rposition()` is short-circuiting; in other words, it will stop
1547     /// processing as soon as it finds a `true`.
1548     ///
1549     /// # Examples
1550     ///
1551     /// Basic usage:
1552     ///
1553     /// ```
1554     /// let a = [1, 2, 3];
1555     ///
1556     /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1557     ///
1558     /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1559     /// ```
1560     ///
1561     /// Stopping at the first `true`:
1562     ///
1563     /// ```
1564     /// let a = [1, 2, 3];
1565     ///
1566     /// let mut iter = a.iter();
1567     ///
1568     /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1569     ///
1570     /// // we can still use `iter`, as there are more elements.
1571     /// assert_eq!(iter.next(), Some(&1));
1572     /// ```
1573     #[inline]
1574     #[stable(feature = "rust1", since = "1.0.0")]
1575     fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1576         P: FnMut(Self::Item) -> bool,
1577         Self: Sized + ExactSizeIterator + DoubleEndedIterator
1578     {
1579         let mut i = self.len();
1580
1581         while let Some(v) = self.next_back() {
1582             if predicate(v) {
1583                 return Some(i - 1);
1584             }
1585             // No need for an overflow check here, because `ExactSizeIterator`
1586             // implies that the number of elements fits into a `usize`.
1587             i -= 1;
1588         }
1589         None
1590     }
1591
1592     /// Returns the maximum element of an iterator.
1593     ///
1594     /// If the two elements are equally maximum, the latest element is
1595     /// returned.
1596     ///
1597     /// # Examples
1598     ///
1599     /// Basic usage:
1600     ///
1601     /// ```
1602     /// let a = [1, 2, 3];
1603     ///
1604     /// assert_eq!(a.iter().max(), Some(&3));
1605     /// ```
1606     #[inline]
1607     #[stable(feature = "rust1", since = "1.0.0")]
1608     fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1609     {
1610         select_fold1(self,
1611                      |_| (),
1612                      // switch to y even if it is only equal, to preserve
1613                      // stability.
1614                      |_, x, _, y| *x <= *y)
1615             .map(|(_, x)| x)
1616     }
1617
1618     /// Returns the minimum element of an iterator.
1619     ///
1620     /// If the two elements are equally minimum, the first element is
1621     /// returned.
1622     ///
1623     /// # Examples
1624     ///
1625     /// Basic usage:
1626     ///
1627     /// ```
1628     /// let a = [1, 2, 3];
1629     ///
1630     /// assert_eq!(a.iter().min(), Some(&1));
1631     /// ```
1632     #[inline]
1633     #[stable(feature = "rust1", since = "1.0.0")]
1634     fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1635     {
1636         select_fold1(self,
1637                      |_| (),
1638                      // only switch to y if it is strictly smaller, to
1639                      // preserve stability.
1640                      |_, x, _, y| *x > *y)
1641             .map(|(_, x)| x)
1642     }
1643
1644     /// Returns the element that gives the maximum value from the
1645     /// specified function.
1646     ///
1647     /// Returns the rightmost element if the comparison determines two elements
1648     /// to be equally maximum.
1649     ///
1650     /// # Examples
1651     ///
1652     /// ```
1653     /// let a = [-3_i32, 0, 1, 5, -10];
1654     /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1655     /// ```
1656     #[inline]
1657     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1658     fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1659         where Self: Sized, F: FnMut(&Self::Item) -> B,
1660     {
1661         select_fold1(self,
1662                      f,
1663                      // switch to y even if it is only equal, to preserve
1664                      // stability.
1665                      |x_p, _, y_p, _| x_p <= y_p)
1666             .map(|(_, x)| x)
1667     }
1668
1669     /// Returns the element that gives the minimum value from the
1670     /// specified function.
1671     ///
1672     /// Returns the latest element if the comparison determines two elements
1673     /// to be equally minimum.
1674     ///
1675     /// # Examples
1676     ///
1677     /// ```
1678     /// let a = [-3_i32, 0, 1, 5, -10];
1679     /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1680     /// ```
1681     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1682     fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1683         where Self: Sized, F: FnMut(&Self::Item) -> B,
1684     {
1685         select_fold1(self,
1686                      f,
1687                      // only switch to y if it is strictly smaller, to
1688                      // preserve stability.
1689                      |x_p, _, y_p, _| x_p > y_p)
1690             .map(|(_, x)| x)
1691     }
1692
1693     /// Reverses an iterator's direction.
1694     ///
1695     /// Usually, iterators iterate from left to right. After using `rev()`,
1696     /// an iterator will instead iterate from right to left.
1697     ///
1698     /// This is only possible if the iterator has an end, so `rev()` only
1699     /// works on [`DoubleEndedIterator`]s.
1700     ///
1701     /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1702     ///
1703     /// # Examples
1704     ///
1705     /// ```
1706     /// let a = [1, 2, 3];
1707     ///
1708     /// let mut iter = a.iter().rev();
1709     ///
1710     /// assert_eq!(iter.next(), Some(&3));
1711     /// assert_eq!(iter.next(), Some(&2));
1712     /// assert_eq!(iter.next(), Some(&1));
1713     ///
1714     /// assert_eq!(iter.next(), None);
1715     /// ```
1716     #[inline]
1717     #[stable(feature = "rust1", since = "1.0.0")]
1718     fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1719         Rev{iter: self}
1720     }
1721
1722     /// Converts an iterator of pairs into a pair of containers.
1723     ///
1724     /// `unzip()` consumes an entire iterator of pairs, producing two
1725     /// collections: one from the left elements of the pairs, and one
1726     /// from the right elements.
1727     ///
1728     /// This function is, in some sense, the opposite of [`zip()`].
1729     ///
1730     /// [`zip()`]: #method.zip
1731     ///
1732     /// # Examples
1733     ///
1734     /// Basic usage:
1735     ///
1736     /// ```
1737     /// let a = [(1, 2), (3, 4)];
1738     ///
1739     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1740     ///
1741     /// assert_eq!(left, [1, 3]);
1742     /// assert_eq!(right, [2, 4]);
1743     /// ```
1744     #[stable(feature = "rust1", since = "1.0.0")]
1745     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1746         FromA: Default + Extend<A>,
1747         FromB: Default + Extend<B>,
1748         Self: Sized + Iterator<Item=(A, B)>,
1749     {
1750         let mut ts: FromA = Default::default();
1751         let mut us: FromB = Default::default();
1752
1753         for (t, u) in self {
1754             ts.extend(Some(t));
1755             us.extend(Some(u));
1756         }
1757
1758         (ts, us)
1759     }
1760
1761     /// Creates an iterator which `clone()`s all of its elements.
1762     ///
1763     /// This is useful when you have an iterator over `&T`, but you need an
1764     /// iterator over `T`.
1765     ///
1766     /// # Examples
1767     ///
1768     /// Basic usage:
1769     ///
1770     /// ```
1771     /// let a = [1, 2, 3];
1772     ///
1773     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1774     ///
1775     /// // cloned is the same as .map(|&x| x), for integers
1776     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1777     ///
1778     /// assert_eq!(v_cloned, vec![1, 2, 3]);
1779     /// assert_eq!(v_map, vec![1, 2, 3]);
1780     /// ```
1781     #[stable(feature = "rust1", since = "1.0.0")]
1782     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1783         where Self: Sized + Iterator<Item=&'a T>, T: Clone
1784     {
1785         Cloned { it: self }
1786     }
1787
1788     /// Repeats an iterator endlessly.
1789     ///
1790     /// Instead of stopping at `None`, the iterator will instead start again,
1791     /// from the beginning. After iterating again, it will start at the
1792     /// beginning again. And again. And again. Forever.
1793     ///
1794     /// # Examples
1795     ///
1796     /// Basic usage:
1797     ///
1798     /// ```
1799     /// let a = [1, 2, 3];
1800     ///
1801     /// let mut it = a.iter().cycle();
1802     ///
1803     /// assert_eq!(it.next(), Some(&1));
1804     /// assert_eq!(it.next(), Some(&2));
1805     /// assert_eq!(it.next(), Some(&3));
1806     /// assert_eq!(it.next(), Some(&1));
1807     /// assert_eq!(it.next(), Some(&2));
1808     /// assert_eq!(it.next(), Some(&3));
1809     /// assert_eq!(it.next(), Some(&1));
1810     /// ```
1811     #[stable(feature = "rust1", since = "1.0.0")]
1812     #[inline]
1813     fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1814         Cycle{orig: self.clone(), iter: self}
1815     }
1816
1817     /// Sums the elements of an iterator.
1818     ///
1819     /// Takes each element, adds them together, and returns the result.
1820     ///
1821     /// An empty iterator returns the zero value of the type.
1822     ///
1823     /// # Examples
1824     ///
1825     /// Basic usage:
1826     ///
1827     /// ```
1828     /// #![feature(iter_arith)]
1829     ///
1830     /// let a = [1, 2, 3];
1831     /// let sum: i32 = a.iter().sum();
1832     ///
1833     /// assert_eq!(sum, 6);
1834     /// ```
1835     #[unstable(feature = "iter_arith", reason = "bounds recently changed",
1836                issue = "27739")]
1837     fn sum<S>(self) -> S where
1838         S: Add<Self::Item, Output=S> + Zero,
1839         Self: Sized,
1840     {
1841         self.fold(Zero::zero(), |s, e| s + e)
1842     }
1843
1844     /// Iterates over the entire iterator, multiplying all the elements
1845     ///
1846     /// An empty iterator returns the one value of the type.
1847     ///
1848     /// # Examples
1849     ///
1850     /// ```
1851     /// #![feature(iter_arith)]
1852     ///
1853     /// fn factorial(n: u32) -> u32 {
1854     ///     (1..).take_while(|&i| i <= n).product()
1855     /// }
1856     /// assert_eq!(factorial(0), 1);
1857     /// assert_eq!(factorial(1), 1);
1858     /// assert_eq!(factorial(5), 120);
1859     /// ```
1860     #[unstable(feature="iter_arith", reason = "bounds recently changed",
1861                issue = "27739")]
1862     fn product<P>(self) -> P where
1863         P: Mul<Self::Item, Output=P> + One,
1864         Self: Sized,
1865     {
1866         self.fold(One::one(), |p, e| p * e)
1867     }
1868
1869     /// Lexicographically compares the elements of this `Iterator` with those
1870     /// of another.
1871     #[stable(feature = "iter_order", since = "1.5.0")]
1872     fn cmp<I>(mut self, other: I) -> Ordering where
1873         I: IntoIterator<Item = Self::Item>,
1874         Self::Item: Ord,
1875         Self: Sized,
1876     {
1877         let mut other = other.into_iter();
1878
1879         loop {
1880             match (self.next(), other.next()) {
1881                 (None, None) => return Ordering::Equal,
1882                 (None, _   ) => return Ordering::Less,
1883                 (_   , None) => return Ordering::Greater,
1884                 (Some(x), Some(y)) => match x.cmp(&y) {
1885                     Ordering::Equal => (),
1886                     non_eq => return non_eq,
1887                 },
1888             }
1889         }
1890     }
1891
1892     /// Lexicographically compares the elements of this `Iterator` with those
1893     /// of another.
1894     #[stable(feature = "iter_order", since = "1.5.0")]
1895     fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
1896         I: IntoIterator,
1897         Self::Item: PartialOrd<I::Item>,
1898         Self: Sized,
1899     {
1900         let mut other = other.into_iter();
1901
1902         loop {
1903             match (self.next(), other.next()) {
1904                 (None, None) => return Some(Ordering::Equal),
1905                 (None, _   ) => return Some(Ordering::Less),
1906                 (_   , None) => return Some(Ordering::Greater),
1907                 (Some(x), Some(y)) => match x.partial_cmp(&y) {
1908                     Some(Ordering::Equal) => (),
1909                     non_eq => return non_eq,
1910                 },
1911             }
1912         }
1913     }
1914
1915     /// Determines if the elements of this `Iterator` are equal to those of
1916     /// another.
1917     #[stable(feature = "iter_order", since = "1.5.0")]
1918     fn eq<I>(mut self, other: I) -> bool where
1919         I: IntoIterator,
1920         Self::Item: PartialEq<I::Item>,
1921         Self: Sized,
1922     {
1923         let mut other = other.into_iter();
1924
1925         loop {
1926             match (self.next(), other.next()) {
1927                 (None, None) => return true,
1928                 (None, _) | (_, None) => return false,
1929                 (Some(x), Some(y)) => if x != y { return false },
1930             }
1931         }
1932     }
1933
1934     /// Determines if the elements of this `Iterator` are unequal to those of
1935     /// another.
1936     #[stable(feature = "iter_order", since = "1.5.0")]
1937     fn ne<I>(mut self, other: I) -> bool where
1938         I: IntoIterator,
1939         Self::Item: PartialEq<I::Item>,
1940         Self: Sized,
1941     {
1942         let mut other = other.into_iter();
1943
1944         loop {
1945             match (self.next(), other.next()) {
1946                 (None, None) => return false,
1947                 (None, _) | (_, None) => return true,
1948                 (Some(x), Some(y)) => if x.ne(&y) { return true },
1949             }
1950         }
1951     }
1952
1953     /// Determines if the elements of this `Iterator` are lexicographically
1954     /// less than those of another.
1955     #[stable(feature = "iter_order", since = "1.5.0")]
1956     fn lt<I>(mut self, other: I) -> bool where
1957         I: IntoIterator,
1958         Self::Item: PartialOrd<I::Item>,
1959         Self: Sized,
1960     {
1961         let mut other = other.into_iter();
1962
1963         loop {
1964             match (self.next(), other.next()) {
1965                 (None, None) => return false,
1966                 (None, _   ) => return true,
1967                 (_   , None) => return false,
1968                 (Some(x), Some(y)) => {
1969                     match x.partial_cmp(&y) {
1970                         Some(Ordering::Less) => return true,
1971                         Some(Ordering::Equal) => {}
1972                         Some(Ordering::Greater) => return false,
1973                         None => return false,
1974                     }
1975                 },
1976             }
1977         }
1978     }
1979
1980     /// Determines if the elements of this `Iterator` are lexicographically
1981     /// less or equal to those of another.
1982     #[stable(feature = "iter_order", since = "1.5.0")]
1983     fn le<I>(mut self, other: I) -> bool where
1984         I: IntoIterator,
1985         Self::Item: PartialOrd<I::Item>,
1986         Self: Sized,
1987     {
1988         let mut other = other.into_iter();
1989
1990         loop {
1991             match (self.next(), other.next()) {
1992                 (None, None) => return true,
1993                 (None, _   ) => return true,
1994                 (_   , None) => return false,
1995                 (Some(x), Some(y)) => {
1996                     match x.partial_cmp(&y) {
1997                         Some(Ordering::Less) => return true,
1998                         Some(Ordering::Equal) => {}
1999                         Some(Ordering::Greater) => return false,
2000                         None => return false,
2001                     }
2002                 },
2003             }
2004         }
2005     }
2006
2007     /// Determines if the elements of this `Iterator` are lexicographically
2008     /// greater than those of another.
2009     #[stable(feature = "iter_order", since = "1.5.0")]
2010     fn gt<I>(mut self, other: I) -> bool where
2011         I: IntoIterator,
2012         Self::Item: PartialOrd<I::Item>,
2013         Self: Sized,
2014     {
2015         let mut other = other.into_iter();
2016
2017         loop {
2018             match (self.next(), other.next()) {
2019                 (None, None) => return false,
2020                 (None, _   ) => return false,
2021                 (_   , None) => return true,
2022                 (Some(x), Some(y)) => {
2023                     match x.partial_cmp(&y) {
2024                         Some(Ordering::Less) => return false,
2025                         Some(Ordering::Equal) => {}
2026                         Some(Ordering::Greater) => return true,
2027                         None => return false,
2028                     }
2029                 }
2030             }
2031         }
2032     }
2033
2034     /// Determines if the elements of this `Iterator` are lexicographically
2035     /// greater than or equal to those of another.
2036     #[stable(feature = "iter_order", since = "1.5.0")]
2037     fn ge<I>(mut self, other: I) -> bool where
2038         I: IntoIterator,
2039         Self::Item: PartialOrd<I::Item>,
2040         Self: Sized,
2041     {
2042         let mut other = other.into_iter();
2043
2044         loop {
2045             match (self.next(), other.next()) {
2046                 (None, None) => return true,
2047                 (None, _   ) => return false,
2048                 (_   , None) => return true,
2049                 (Some(x), Some(y)) => {
2050                     match x.partial_cmp(&y) {
2051                         Some(Ordering::Less) => return false,
2052                         Some(Ordering::Equal) => {}
2053                         Some(Ordering::Greater) => return true,
2054                         None => return false,
2055                     }
2056                 },
2057             }
2058         }
2059     }
2060 }
2061
2062 /// Select an element from an iterator based on the given projection
2063 /// and "comparison" function.
2064 ///
2065 /// This is an idiosyncratic helper to try to factor out the
2066 /// commonalities of {max,min}{,_by}. In particular, this avoids
2067 /// having to implement optimizations several times.
2068 #[inline]
2069 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2070                                   mut f_proj: FProj,
2071                                   mut f_cmp: FCmp) -> Option<(B, I::Item)>
2072     where I: Iterator,
2073           FProj: FnMut(&I::Item) -> B,
2074           FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2075 {
2076     // start with the first element as our selection. This avoids
2077     // having to use `Option`s inside the loop, translating to a
2078     // sizeable performance gain (6x in one case).
2079     it.next().map(|mut sel| {
2080         let mut sel_p = f_proj(&sel);
2081
2082         for x in it {
2083             let x_p = f_proj(&x);
2084             if f_cmp(&sel_p,  &sel, &x_p, &x) {
2085                 sel = x;
2086                 sel_p = x_p;
2087             }
2088         }
2089         (sel_p, sel)
2090     })
2091 }
2092
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2095     type Item = I::Item;
2096     fn next(&mut self) -> Option<I::Item> { (**self).next() }
2097     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2098 }