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