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