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