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