]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/iterator.rs
Fix invalid associated type rendering in rustdoc
[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 of
633     /// the [`next`] method will occur.
634     ///
635     /// [`peek`]: struct.Peekable.html#method.peek
636     /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
637     ///
638     /// # Examples
639     ///
640     /// Basic usage:
641     ///
642     /// ```
643     /// let xs = [1, 2, 3];
644     ///
645     /// let mut iter = xs.iter().peekable();
646     ///
647     /// // peek() lets us see into the future
648     /// assert_eq!(iter.peek(), Some(&&1));
649     /// assert_eq!(iter.next(), Some(&1));
650     ///
651     /// assert_eq!(iter.next(), Some(&2));
652     ///
653     /// // we can peek() multiple times, the iterator won't advance
654     /// assert_eq!(iter.peek(), Some(&&3));
655     /// assert_eq!(iter.peek(), Some(&&3));
656     ///
657     /// assert_eq!(iter.next(), Some(&3));
658     ///
659     /// // after the iterator is finished, so is peek()
660     /// assert_eq!(iter.peek(), None);
661     /// assert_eq!(iter.next(), None);
662     /// ```
663     #[inline]
664     #[stable(feature = "rust1", since = "1.0.0")]
665     fn peekable(self) -> Peekable<Self> where Self: Sized {
666         Peekable{iter: self, peeked: None}
667     }
668
669     /// Creates an iterator that [`skip`]s elements based on a predicate.
670     ///
671     /// [`skip`]: #method.skip
672     ///
673     /// `skip_while()` takes a closure as an argument. It will call this
674     /// closure on each element of the iterator, and ignore elements
675     /// until it returns `false`.
676     ///
677     /// After `false` is returned, `skip_while()`'s job is over, and the
678     /// rest of the elements are yielded.
679     ///
680     /// # Examples
681     ///
682     /// Basic usage:
683     ///
684     /// ```
685     /// let a = [-1i32, 0, 1];
686     ///
687     /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
688     ///
689     /// assert_eq!(iter.next(), Some(&0));
690     /// assert_eq!(iter.next(), Some(&1));
691     /// assert_eq!(iter.next(), None);
692     /// ```
693     ///
694     /// Because the closure passed to `skip_while()` takes a reference, and many
695     /// iterators iterate over references, this leads to a possibly confusing
696     /// situation, where the type of the closure is a double reference:
697     ///
698     /// ```
699     /// let a = [-1, 0, 1];
700     ///
701     /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
702     ///
703     /// assert_eq!(iter.next(), Some(&0));
704     /// assert_eq!(iter.next(), Some(&1));
705     /// assert_eq!(iter.next(), None);
706     /// ```
707     ///
708     /// Stopping after an initial `false`:
709     ///
710     /// ```
711     /// let a = [-1, 0, 1, -2];
712     ///
713     /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
714     ///
715     /// assert_eq!(iter.next(), Some(&0));
716     /// assert_eq!(iter.next(), Some(&1));
717     ///
718     /// // while this would have been false, since we already got a false,
719     /// // skip_while() isn't used any more
720     /// assert_eq!(iter.next(), Some(&-2));
721     ///
722     /// assert_eq!(iter.next(), None);
723     /// ```
724     #[inline]
725     #[stable(feature = "rust1", since = "1.0.0")]
726     fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
727         Self: Sized, P: FnMut(&Self::Item) -> bool,
728     {
729         SkipWhile{iter: self, flag: false, predicate: predicate}
730     }
731
732     /// Creates an iterator that yields elements based on a predicate.
733     ///
734     /// `take_while()` takes a closure as an argument. It will call this
735     /// closure on each element of the iterator, and yield elements
736     /// while it returns `true`.
737     ///
738     /// After `false` is returned, `take_while()`'s job is over, and the
739     /// rest of the elements are ignored.
740     ///
741     /// # Examples
742     ///
743     /// Basic usage:
744     ///
745     /// ```
746     /// let a = [-1i32, 0, 1];
747     ///
748     /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
749     ///
750     /// assert_eq!(iter.next(), Some(&-1));
751     /// assert_eq!(iter.next(), None);
752     /// ```
753     ///
754     /// Because the closure passed to `take_while()` takes a reference, and many
755     /// iterators iterate over references, this leads to a possibly confusing
756     /// situation, where the type of the closure is a double reference:
757     ///
758     /// ```
759     /// let a = [-1, 0, 1];
760     ///
761     /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
762     ///
763     /// assert_eq!(iter.next(), Some(&-1));
764     /// assert_eq!(iter.next(), None);
765     /// ```
766     ///
767     /// Stopping after an initial `false`:
768     ///
769     /// ```
770     /// let a = [-1, 0, 1, -2];
771     ///
772     /// let mut iter = a.into_iter().take_while(|x| **x < 0);
773     ///
774     /// assert_eq!(iter.next(), Some(&-1));
775     ///
776     /// // We have more elements that are less than zero, but since we already
777     /// // got a false, take_while() isn't used any more
778     /// assert_eq!(iter.next(), None);
779     /// ```
780     ///
781     /// Because `take_while()` needs to look at the value in order to see if it
782     /// should be included or not, consuming iterators will see that it is
783     /// removed:
784     ///
785     /// ```
786     /// let a = [1, 2, 3, 4];
787     /// let mut iter = a.into_iter();
788     ///
789     /// let result: Vec<i32> = iter.by_ref()
790     ///                            .take_while(|n| **n != 3)
791     ///                            .cloned()
792     ///                            .collect();
793     ///
794     /// assert_eq!(result, &[1, 2]);
795     ///
796     /// let result: Vec<i32> = iter.cloned().collect();
797     ///
798     /// assert_eq!(result, &[4]);
799     /// ```
800     ///
801     /// The `3` is no longer there, because it was consumed in order to see if
802     /// the iteration should stop, but wasn't placed back into the iterator or
803     /// some similar thing.
804     #[inline]
805     #[stable(feature = "rust1", since = "1.0.0")]
806     fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
807         Self: Sized, P: FnMut(&Self::Item) -> bool,
808     {
809         TakeWhile{iter: self, flag: false, predicate: predicate}
810     }
811
812     /// Creates an iterator that skips the first `n` elements.
813     ///
814     /// After they have been consumed, the rest of the elements are yielded.
815     ///
816     /// # Examples
817     ///
818     /// Basic usage:
819     ///
820     /// ```
821     /// let a = [1, 2, 3];
822     ///
823     /// let mut iter = a.iter().skip(2);
824     ///
825     /// assert_eq!(iter.next(), Some(&3));
826     /// assert_eq!(iter.next(), None);
827     /// ```
828     #[inline]
829     #[stable(feature = "rust1", since = "1.0.0")]
830     fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
831         Skip{iter: self, n: n}
832     }
833
834     /// Creates an iterator that yields its first `n` elements.
835     ///
836     /// # Examples
837     ///
838     /// Basic usage:
839     ///
840     /// ```
841     /// let a = [1, 2, 3];
842     ///
843     /// let mut iter = a.iter().take(2);
844     ///
845     /// assert_eq!(iter.next(), Some(&1));
846     /// assert_eq!(iter.next(), Some(&2));
847     /// assert_eq!(iter.next(), None);
848     /// ```
849     ///
850     /// `take()` is often used with an infinite iterator, to make it finite:
851     ///
852     /// ```
853     /// let mut iter = (0..).take(3);
854     ///
855     /// assert_eq!(iter.next(), Some(0));
856     /// assert_eq!(iter.next(), Some(1));
857     /// assert_eq!(iter.next(), Some(2));
858     /// assert_eq!(iter.next(), None);
859     /// ```
860     #[inline]
861     #[stable(feature = "rust1", since = "1.0.0")]
862     fn take(self, n: usize) -> Take<Self> where Self: Sized, {
863         Take{iter: self, n: n}
864     }
865
866     /// An iterator adaptor similar to [`fold`] that holds internal state and
867     /// produces a new iterator.
868     ///
869     /// [`fold`]: #method.fold
870     ///
871     /// `scan()` takes two arguments: an initial value which seeds the internal
872     /// state, and a closure with two arguments, the first being a mutable
873     /// reference to the internal state and the second an iterator element.
874     /// The closure can assign to the internal state to share state between
875     /// iterations.
876     ///
877     /// On iteration, the closure will be applied to each element of the
878     /// iterator and the return value from the closure, an [`Option`], is
879     /// yielded by the iterator.
880     ///
881     /// [`Option`]: ../../std/option/enum.Option.html
882     ///
883     /// # Examples
884     ///
885     /// Basic usage:
886     ///
887     /// ```
888     /// let a = [1, 2, 3];
889     ///
890     /// let mut iter = a.iter().scan(1, |state, &x| {
891     ///     // each iteration, we'll multiply the state by the element
892     ///     *state = *state * x;
893     ///
894     ///     // the value passed on to the next iteration
895     ///     Some(*state)
896     /// });
897     ///
898     /// assert_eq!(iter.next(), Some(1));
899     /// assert_eq!(iter.next(), Some(2));
900     /// assert_eq!(iter.next(), Some(6));
901     /// assert_eq!(iter.next(), None);
902     /// ```
903     #[inline]
904     #[stable(feature = "rust1", since = "1.0.0")]
905     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
906         where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
907     {
908         Scan{iter: self, f: f, state: initial_state}
909     }
910
911     /// Creates an iterator that works like map, but flattens nested structure.
912     ///
913     /// The [`map`] adapter is very useful, but only when the closure
914     /// argument produces values. If it produces an iterator instead, there's
915     /// an extra layer of indirection. `flat_map()` will remove this extra layer
916     /// on its own.
917     ///
918     /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
919     /// one item for each element, and `flat_map()`'s closure returns an
920     /// iterator for each element.
921     ///
922     /// [`map`]: #method.map
923     ///
924     /// # Examples
925     ///
926     /// Basic usage:
927     ///
928     /// ```
929     /// let words = ["alpha", "beta", "gamma"];
930     ///
931     /// // chars() returns an iterator
932     /// let merged: String = words.iter()
933     ///                           .flat_map(|s| s.chars())
934     ///                           .collect();
935     /// assert_eq!(merged, "alphabetagamma");
936     /// ```
937     #[inline]
938     #[stable(feature = "rust1", since = "1.0.0")]
939     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
940         where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
941     {
942         FlatMap{iter: self, f: f, frontiter: None, backiter: None }
943     }
944
945     /// Creates an iterator which ends after the first [`None`].
946     ///
947     /// After an iterator returns [`None`], future calls may or may not yield
948     /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
949     /// [`None`] is given, it will always return [`None`] forever.
950     ///
951     /// [`None`]: ../../std/option/enum.Option.html#variant.None
952     /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
953     ///
954     /// # Examples
955     ///
956     /// Basic usage:
957     ///
958     /// ```
959     /// // an iterator which alternates between Some and None
960     /// struct Alternate {
961     ///     state: i32,
962     /// }
963     ///
964     /// impl Iterator for Alternate {
965     ///     type Item = i32;
966     ///
967     ///     fn next(&mut self) -> Option<i32> {
968     ///         let val = self.state;
969     ///         self.state = self.state + 1;
970     ///
971     ///         // if it's even, Some(i32), else None
972     ///         if val % 2 == 0 {
973     ///             Some(val)
974     ///         } else {
975     ///             None
976     ///         }
977     ///     }
978     /// }
979     ///
980     /// let mut iter = Alternate { state: 0 };
981     ///
982     /// // we can see our iterator going back and forth
983     /// assert_eq!(iter.next(), Some(0));
984     /// assert_eq!(iter.next(), None);
985     /// assert_eq!(iter.next(), Some(2));
986     /// assert_eq!(iter.next(), None);
987     ///
988     /// // however, once we fuse it...
989     /// let mut iter = iter.fuse();
990     ///
991     /// assert_eq!(iter.next(), Some(4));
992     /// assert_eq!(iter.next(), None);
993     ///
994     /// // it will always return None after the first time.
995     /// assert_eq!(iter.next(), None);
996     /// assert_eq!(iter.next(), None);
997     /// assert_eq!(iter.next(), None);
998     /// ```
999     #[inline]
1000     #[stable(feature = "rust1", since = "1.0.0")]
1001     fn fuse(self) -> Fuse<Self> where Self: Sized {
1002         Fuse{iter: self, done: false}
1003     }
1004
1005     /// Do something with each element of an iterator, passing the value on.
1006     ///
1007     /// When using iterators, you'll often chain several of them together.
1008     /// While working on such code, you might want to check out what's
1009     /// happening at various parts in the pipeline. To do that, insert
1010     /// a call to `inspect()`.
1011     ///
1012     /// It's much more common for `inspect()` to be used as a debugging tool
1013     /// than to exist in your final code, but never say never.
1014     ///
1015     /// # Examples
1016     ///
1017     /// Basic usage:
1018     ///
1019     /// ```
1020     /// let a = [1, 4, 2, 3];
1021     ///
1022     /// // this iterator sequence is complex.
1023     /// let sum = a.iter()
1024     ///             .cloned()
1025     ///             .filter(|&x| x % 2 == 0)
1026     ///             .fold(0, |sum, i| sum + i);
1027     ///
1028     /// println!("{}", sum);
1029     ///
1030     /// // let's add some inspect() calls to investigate what's happening
1031     /// let sum = a.iter()
1032     ///             .cloned()
1033     ///             .inspect(|x| println!("about to filter: {}", x))
1034     ///             .filter(|&x| x % 2 == 0)
1035     ///             .inspect(|x| println!("made it through filter: {}", x))
1036     ///             .fold(0, |sum, i| sum + i);
1037     ///
1038     /// println!("{}", sum);
1039     /// ```
1040     ///
1041     /// This will print:
1042     ///
1043     /// ```text
1044     /// about to filter: 1
1045     /// about to filter: 4
1046     /// made it through filter: 4
1047     /// about to filter: 2
1048     /// made it through filter: 2
1049     /// about to filter: 3
1050     /// 6
1051     /// ```
1052     #[inline]
1053     #[stable(feature = "rust1", since = "1.0.0")]
1054     fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1055         Self: Sized, F: FnMut(&Self::Item),
1056     {
1057         Inspect{iter: self, f: f}
1058     }
1059
1060     /// Borrows an iterator, rather than consuming it.
1061     ///
1062     /// This is useful to allow applying iterator adaptors while still
1063     /// retaining ownership of the original iterator.
1064     ///
1065     /// # Examples
1066     ///
1067     /// Basic usage:
1068     ///
1069     /// ```
1070     /// let a = [1, 2, 3];
1071     ///
1072     /// let iter = a.into_iter();
1073     ///
1074     /// let sum: i32 = iter.take(5)
1075     ///                    .fold(0, |acc, &i| acc + i );
1076     ///
1077     /// assert_eq!(sum, 6);
1078     ///
1079     /// // if we try to use iter again, it won't work. The following line
1080     /// // gives "error: use of moved value: `iter`
1081     /// // assert_eq!(iter.next(), None);
1082     ///
1083     /// // let's try that again
1084     /// let a = [1, 2, 3];
1085     ///
1086     /// let mut iter = a.into_iter();
1087     ///
1088     /// // instead, we add in a .by_ref()
1089     /// let sum: i32 = iter.by_ref()
1090     ///                    .take(2)
1091     ///                    .fold(0, |acc, &i| acc + i );
1092     ///
1093     /// assert_eq!(sum, 3);
1094     ///
1095     /// // now this is just fine:
1096     /// assert_eq!(iter.next(), Some(&3));
1097     /// assert_eq!(iter.next(), None);
1098     /// ```
1099     #[stable(feature = "rust1", since = "1.0.0")]
1100     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1101
1102     /// Transforms an iterator into a collection.
1103     ///
1104     /// `collect()` can take anything iterable, and turn it into a relevant
1105     /// collection. This is one of the more powerful methods in the standard
1106     /// library, used in a variety of contexts.
1107     ///
1108     /// The most basic pattern in which `collect()` is used is to turn one
1109     /// collection into another. You take a collection, call [`iter`] on it,
1110     /// do a bunch of transformations, and then `collect()` at the end.
1111     ///
1112     /// One of the keys to `collect()`'s power is that many things you might
1113     /// not think of as 'collections' actually are. For example, a [`String`]
1114     /// is a collection of [`char`]s. And a collection of
1115     /// [`Result<T, E>`][`Result`] can be thought of as single
1116     /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
1117     ///
1118     /// Because `collect()` is so general, it can cause problems with type
1119     /// inference. As such, `collect()` is one of the few times you'll see
1120     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1121     /// helps the inference algorithm understand specifically which collection
1122     /// you're trying to collect into.
1123     ///
1124     /// # Examples
1125     ///
1126     /// Basic usage:
1127     ///
1128     /// ```
1129     /// let a = [1, 2, 3];
1130     ///
1131     /// let doubled: Vec<i32> = a.iter()
1132     ///                          .map(|&x| x * 2)
1133     ///                          .collect();
1134     ///
1135     /// assert_eq!(vec![2, 4, 6], doubled);
1136     /// ```
1137     ///
1138     /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1139     /// we could collect into, for example, a [`VecDeque<T>`] instead:
1140     ///
1141     /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1142     ///
1143     /// ```
1144     /// use std::collections::VecDeque;
1145     ///
1146     /// let a = [1, 2, 3];
1147     ///
1148     /// let doubled: VecDeque<i32> = a.iter()
1149     ///                               .map(|&x| x * 2)
1150     ///                               .collect();
1151     ///
1152     /// assert_eq!(2, doubled[0]);
1153     /// assert_eq!(4, doubled[1]);
1154     /// assert_eq!(6, doubled[2]);
1155     /// ```
1156     ///
1157     /// Using the 'turbofish' instead of annotating `doubled`:
1158     ///
1159     /// ```
1160     /// let a = [1, 2, 3];
1161     ///
1162     /// let doubled = a.iter()
1163     ///                .map(|&x| x * 2)
1164     ///                .collect::<Vec<i32>>();
1165     ///
1166     /// assert_eq!(vec![2, 4, 6], doubled);
1167     /// ```
1168     ///
1169     /// Because `collect()` cares about what you're collecting into, you can
1170     /// still use a partial type hint, `_`, with the turbofish:
1171     ///
1172     /// ```
1173     /// let a = [1, 2, 3];
1174     ///
1175     /// let doubled = a.iter()
1176     ///                .map(|&x| x * 2)
1177     ///                .collect::<Vec<_>>();
1178     ///
1179     /// assert_eq!(vec![2, 4, 6], doubled);
1180     /// ```
1181     ///
1182     /// Using `collect()` to make a [`String`]:
1183     ///
1184     /// ```
1185     /// let chars = ['g', 'd', 'k', 'k', 'n'];
1186     ///
1187     /// let hello: String = chars.iter()
1188     ///                          .map(|&x| x as u8)
1189     ///                          .map(|x| (x + 1) as char)
1190     ///                          .collect();
1191     ///
1192     /// assert_eq!("hello", hello);
1193     /// ```
1194     ///
1195     /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1196     /// see if any of them failed:
1197     ///
1198     /// ```
1199     /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1200     ///
1201     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1202     ///
1203     /// // gives us the first error
1204     /// assert_eq!(Err("nope"), result);
1205     ///
1206     /// let results = [Ok(1), Ok(3)];
1207     ///
1208     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1209     ///
1210     /// // gives us the list of answers
1211     /// assert_eq!(Ok(vec![1, 3]), result);
1212     /// ```
1213     ///
1214     /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
1215     /// [`String`]: ../../std/string/struct.String.html
1216     /// [`char`]: ../../std/primitive.char.html
1217     /// [`Result`]: ../../std/result/enum.Result.html
1218     #[inline]
1219     #[stable(feature = "rust1", since = "1.0.0")]
1220     fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1221         FromIterator::from_iter(self)
1222     }
1223
1224     /// Consumes an iterator, creating two collections from it.
1225     ///
1226     /// The predicate passed to `partition()` can return `true`, or `false`.
1227     /// `partition()` returns a pair, all of the elements for which it returned
1228     /// `true`, and all of the elements for which it returned `false`.
1229     ///
1230     /// # Examples
1231     ///
1232     /// Basic usage:
1233     ///
1234     /// ```
1235     /// let a = [1, 2, 3];
1236     ///
1237     /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1238     ///                                          .partition(|&n| n % 2 == 0);
1239     ///
1240     /// assert_eq!(even, vec![2]);
1241     /// assert_eq!(odd, vec![1, 3]);
1242     /// ```
1243     #[stable(feature = "rust1", since = "1.0.0")]
1244     fn partition<B, F>(self, mut f: F) -> (B, B) where
1245         Self: Sized,
1246         B: Default + Extend<Self::Item>,
1247         F: FnMut(&Self::Item) -> bool
1248     {
1249         let mut left: B = Default::default();
1250         let mut right: B = Default::default();
1251
1252         for x in self {
1253             if f(&x) {
1254                 left.extend(Some(x))
1255             } else {
1256                 right.extend(Some(x))
1257             }
1258         }
1259
1260         (left, right)
1261     }
1262
1263     /// An iterator adaptor that applies a function, producing a single, final value.
1264     ///
1265     /// `fold()` takes two arguments: an initial value, and a closure with two
1266     /// arguments: an 'accumulator', and an element. The closure returns the value that
1267     /// the accumulator should have for the next iteration.
1268     ///
1269     /// The initial value is the value the accumulator will have on the first
1270     /// call.
1271     ///
1272     /// After applying this closure to every element of the iterator, `fold()`
1273     /// returns the accumulator.
1274     ///
1275     /// This operation is sometimes called 'reduce' or 'inject'.
1276     ///
1277     /// Folding is useful whenever you have a collection of something, and want
1278     /// to produce a single value from it.
1279     ///
1280     /// # Examples
1281     ///
1282     /// Basic usage:
1283     ///
1284     /// ```
1285     /// let a = [1, 2, 3];
1286     ///
1287     /// // the sum of all of the elements of a
1288     /// let sum = a.iter()
1289     ///            .fold(0, |acc, &x| acc + x);
1290     ///
1291     /// assert_eq!(sum, 6);
1292     /// ```
1293     ///
1294     /// Let's walk through each step of the iteration here:
1295     ///
1296     /// | element | acc | x | result |
1297     /// |---------|-----|---|--------|
1298     /// |         | 0   |   |        |
1299     /// | 1       | 0   | 1 | 1      |
1300     /// | 2       | 1   | 2 | 3      |
1301     /// | 3       | 3   | 3 | 6      |
1302     ///
1303     /// And so, our final result, `6`.
1304     ///
1305     /// It's common for people who haven't used iterators a lot to
1306     /// use a `for` loop with a list of things to build up a result. Those
1307     /// can be turned into `fold()`s:
1308     ///
1309     /// [`for`]: ../../book/first-edition/loops.html#for
1310     ///
1311     /// ```
1312     /// let numbers = [1, 2, 3, 4, 5];
1313     ///
1314     /// let mut result = 0;
1315     ///
1316     /// // for loop:
1317     /// for i in &numbers {
1318     ///     result = result + i;
1319     /// }
1320     ///
1321     /// // fold:
1322     /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1323     ///
1324     /// // they're the same
1325     /// assert_eq!(result, result2);
1326     /// ```
1327     #[inline]
1328     #[stable(feature = "rust1", since = "1.0.0")]
1329     fn fold<B, F>(self, init: B, mut f: F) -> B where
1330         Self: Sized, F: FnMut(B, Self::Item) -> B,
1331     {
1332         let mut accum = init;
1333         for x in self {
1334             accum = f(accum, x);
1335         }
1336         accum
1337     }
1338
1339     /// Tests if every element of the iterator matches a predicate.
1340     ///
1341     /// `all()` takes a closure that returns `true` or `false`. It applies
1342     /// this closure to each element of the iterator, and if they all return
1343     /// `true`, then so does `all()`. If any of them return `false`, it
1344     /// returns `false`.
1345     ///
1346     /// `all()` is short-circuiting; in other words, it will stop processing
1347     /// as soon as it finds a `false`, given that no matter what else happens,
1348     /// the result will also be `false`.
1349     ///
1350     /// An empty iterator returns `true`.
1351     ///
1352     /// # Examples
1353     ///
1354     /// Basic usage:
1355     ///
1356     /// ```
1357     /// let a = [1, 2, 3];
1358     ///
1359     /// assert!(a.iter().all(|&x| x > 0));
1360     ///
1361     /// assert!(!a.iter().all(|&x| x > 2));
1362     /// ```
1363     ///
1364     /// Stopping at the first `false`:
1365     ///
1366     /// ```
1367     /// let a = [1, 2, 3];
1368     ///
1369     /// let mut iter = a.iter();
1370     ///
1371     /// assert!(!iter.all(|&x| x != 2));
1372     ///
1373     /// // we can still use `iter`, as there are more elements.
1374     /// assert_eq!(iter.next(), Some(&3));
1375     /// ```
1376     #[inline]
1377     #[stable(feature = "rust1", since = "1.0.0")]
1378     fn all<F>(&mut self, mut f: F) -> bool where
1379         Self: Sized, F: FnMut(Self::Item) -> bool
1380     {
1381         for x in self {
1382             if !f(x) {
1383                 return false;
1384             }
1385         }
1386         true
1387     }
1388
1389     /// Tests if any element of the iterator matches a predicate.
1390     ///
1391     /// `any()` takes a closure that returns `true` or `false`. It applies
1392     /// this closure to each element of the iterator, and if any of them return
1393     /// `true`, then so does `any()`. If they all return `false`, it
1394     /// returns `false`.
1395     ///
1396     /// `any()` is short-circuiting; in other words, it will stop processing
1397     /// as soon as it finds a `true`, given that no matter what else happens,
1398     /// the result will also be `true`.
1399     ///
1400     /// An empty iterator returns `false`.
1401     ///
1402     /// # Examples
1403     ///
1404     /// Basic usage:
1405     ///
1406     /// ```
1407     /// let a = [1, 2, 3];
1408     ///
1409     /// assert!(a.iter().any(|&x| x > 0));
1410     ///
1411     /// assert!(!a.iter().any(|&x| x > 5));
1412     /// ```
1413     ///
1414     /// Stopping at the first `true`:
1415     ///
1416     /// ```
1417     /// let a = [1, 2, 3];
1418     ///
1419     /// let mut iter = a.iter();
1420     ///
1421     /// assert!(iter.any(|&x| x != 2));
1422     ///
1423     /// // we can still use `iter`, as there are more elements.
1424     /// assert_eq!(iter.next(), Some(&2));
1425     /// ```
1426     #[inline]
1427     #[stable(feature = "rust1", since = "1.0.0")]
1428     fn any<F>(&mut self, mut f: F) -> bool where
1429         Self: Sized,
1430         F: FnMut(Self::Item) -> bool
1431     {
1432         for x in self {
1433             if f(x) {
1434                 return true;
1435             }
1436         }
1437         false
1438     }
1439
1440     /// Searches for an element of an iterator that satisfies a predicate.
1441     ///
1442     /// `find()` takes a closure that returns `true` or `false`. It applies
1443     /// this closure to each element of the iterator, and if any of them return
1444     /// `true`, then `find()` returns [`Some(element)`]. If they all return
1445     /// `false`, it returns [`None`].
1446     ///
1447     /// `find()` is short-circuiting; in other words, it will stop processing
1448     /// as soon as the closure returns `true`.
1449     ///
1450     /// Because `find()` takes a reference, and many iterators iterate over
1451     /// references, this leads to a possibly confusing situation where the
1452     /// argument is a double reference. You can see this effect in the
1453     /// examples below, with `&&x`.
1454     ///
1455     /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
1456     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1457     ///
1458     /// # Examples
1459     ///
1460     /// Basic usage:
1461     ///
1462     /// ```
1463     /// let a = [1, 2, 3];
1464     ///
1465     /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1466     ///
1467     /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1468     /// ```
1469     ///
1470     /// Stopping at the first `true`:
1471     ///
1472     /// ```
1473     /// let a = [1, 2, 3];
1474     ///
1475     /// let mut iter = a.iter();
1476     ///
1477     /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1478     ///
1479     /// // we can still use `iter`, as there are more elements.
1480     /// assert_eq!(iter.next(), Some(&3));
1481     /// ```
1482     #[inline]
1483     #[stable(feature = "rust1", since = "1.0.0")]
1484     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1485         Self: Sized,
1486         P: FnMut(&Self::Item) -> bool,
1487     {
1488         for x in self {
1489             if predicate(&x) { return Some(x) }
1490         }
1491         None
1492     }
1493
1494     /// Searches for an element in an iterator, returning its index.
1495     ///
1496     /// `position()` takes a closure that returns `true` or `false`. It applies
1497     /// this closure to each element of the iterator, and if one of them
1498     /// returns `true`, then `position()` returns [`Some(index)`]. If all of
1499     /// them return `false`, it returns [`None`].
1500     ///
1501     /// `position()` is short-circuiting; in other words, it will stop
1502     /// processing as soon as it finds a `true`.
1503     ///
1504     /// # Overflow Behavior
1505     ///
1506     /// The method does no guarding against overflows, so if there are more
1507     /// than [`usize::MAX`] non-matching elements, it either produces the wrong
1508     /// result or panics. If debug assertions are enabled, a panic is
1509     /// guaranteed.
1510     ///
1511     /// # Panics
1512     ///
1513     /// This function might panic if the iterator has more than `usize::MAX`
1514     /// non-matching elements.
1515     ///
1516     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1517     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1518     /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
1519     ///
1520     /// # Examples
1521     ///
1522     /// Basic usage:
1523     ///
1524     /// ```
1525     /// let a = [1, 2, 3];
1526     ///
1527     /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1528     ///
1529     /// assert_eq!(a.iter().position(|&x| x == 5), None);
1530     /// ```
1531     ///
1532     /// Stopping at the first `true`:
1533     ///
1534     /// ```
1535     /// let a = [1, 2, 3];
1536     ///
1537     /// let mut iter = a.iter();
1538     ///
1539     /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1540     ///
1541     /// // we can still use `iter`, as there are more elements.
1542     /// assert_eq!(iter.next(), Some(&3));
1543     /// ```
1544     #[inline]
1545     #[stable(feature = "rust1", since = "1.0.0")]
1546     fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1547         Self: Sized,
1548         P: FnMut(Self::Item) -> bool,
1549     {
1550         // `enumerate` might overflow.
1551         for (i, x) in self.enumerate() {
1552             if predicate(x) {
1553                 return Some(i);
1554             }
1555         }
1556         None
1557     }
1558
1559     /// Searches for an element in an iterator from the right, returning its
1560     /// index.
1561     ///
1562     /// `rposition()` takes a closure that returns `true` or `false`. It applies
1563     /// this closure to each element of the iterator, starting from the end,
1564     /// and if one of them returns `true`, then `rposition()` returns
1565     /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
1566     ///
1567     /// `rposition()` is short-circuiting; in other words, it will stop
1568     /// processing as soon as it finds a `true`.
1569     ///
1570     /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
1571     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1572     ///
1573     /// # Examples
1574     ///
1575     /// Basic usage:
1576     ///
1577     /// ```
1578     /// let a = [1, 2, 3];
1579     ///
1580     /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1581     ///
1582     /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1583     /// ```
1584     ///
1585     /// Stopping at the first `true`:
1586     ///
1587     /// ```
1588     /// let a = [1, 2, 3];
1589     ///
1590     /// let mut iter = a.iter();
1591     ///
1592     /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1593     ///
1594     /// // we can still use `iter`, as there are more elements.
1595     /// assert_eq!(iter.next(), Some(&1));
1596     /// ```
1597     #[inline]
1598     #[stable(feature = "rust1", since = "1.0.0")]
1599     fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1600         P: FnMut(Self::Item) -> bool,
1601         Self: Sized + ExactSizeIterator + DoubleEndedIterator
1602     {
1603         let mut i = self.len();
1604
1605         while let Some(v) = self.next_back() {
1606             // No need for an overflow check here, because `ExactSizeIterator`
1607             // implies that the number of elements fits into a `usize`.
1608             i -= 1;
1609             if predicate(v) {
1610                 return Some(i);
1611             }
1612         }
1613         None
1614     }
1615
1616     /// Returns the maximum element of an iterator.
1617     ///
1618     /// If several elements are equally maximum, the last element is
1619     /// returned. If the iterator is empty, [`None`] is returned.
1620     ///
1621     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1622     ///
1623     /// # Examples
1624     ///
1625     /// Basic usage:
1626     ///
1627     /// ```
1628     /// let a = [1, 2, 3];
1629     /// let b: Vec<u32> = Vec::new();
1630     ///
1631     /// assert_eq!(a.iter().max(), Some(&3));
1632     /// assert_eq!(b.iter().max(), None);
1633     /// ```
1634     #[inline]
1635     #[stable(feature = "rust1", since = "1.0.0")]
1636     fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1637     {
1638         select_fold1(self,
1639                      |_| (),
1640                      // switch to y even if it is only equal, to preserve
1641                      // stability.
1642                      |_, x, _, y| *x <= *y)
1643             .map(|(_, x)| x)
1644     }
1645
1646     /// Returns the minimum element of an iterator.
1647     ///
1648     /// If several elements are equally minimum, the first element is
1649     /// returned. If the iterator is empty, [`None`] is returned.
1650     ///
1651     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1652     ///
1653     /// # Examples
1654     ///
1655     /// Basic usage:
1656     ///
1657     /// ```
1658     /// let a = [1, 2, 3];
1659     /// let b: Vec<u32> = Vec::new();
1660     ///
1661     /// assert_eq!(a.iter().min(), Some(&1));
1662     /// assert_eq!(b.iter().min(), None);
1663     /// ```
1664     #[inline]
1665     #[stable(feature = "rust1", since = "1.0.0")]
1666     fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1667     {
1668         select_fold1(self,
1669                      |_| (),
1670                      // only switch to y if it is strictly smaller, to
1671                      // preserve stability.
1672                      |_, x, _, y| *x > *y)
1673             .map(|(_, x)| x)
1674     }
1675
1676     /// Returns the element that gives the maximum value from the
1677     /// specified function.
1678     ///
1679     /// If several elements are equally maximum, the last element is
1680     /// returned. If the iterator is empty, [`None`] is returned.
1681     ///
1682     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1683     ///
1684     /// # Examples
1685     ///
1686     /// ```
1687     /// let a = [-3_i32, 0, 1, 5, -10];
1688     /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1689     /// ```
1690     #[inline]
1691     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1692     fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1693         where Self: Sized, F: FnMut(&Self::Item) -> B,
1694     {
1695         select_fold1(self,
1696                      f,
1697                      // switch to y even if it is only equal, to preserve
1698                      // stability.
1699                      |x_p, _, y_p, _| x_p <= y_p)
1700             .map(|(_, x)| x)
1701     }
1702
1703     /// Returns the element that gives the maximum value with respect to the
1704     /// specified comparison function.
1705     ///
1706     /// If several elements are equally maximum, the last element is
1707     /// returned. If the iterator is empty, [`None`] is returned.
1708     ///
1709     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1710     ///
1711     /// # Examples
1712     ///
1713     /// ```
1714     /// let a = [-3_i32, 0, 1, 5, -10];
1715     /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
1716     /// ```
1717     #[inline]
1718     #[stable(feature = "iter_max_by", since = "1.15.0")]
1719     fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
1720         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1721     {
1722         select_fold1(self,
1723                      |_| (),
1724                      // switch to y even if it is only equal, to preserve
1725                      // stability.
1726                      |_, x, _, y| Ordering::Greater != compare(x, y))
1727             .map(|(_, x)| x)
1728     }
1729
1730     /// Returns the element that gives the minimum value from the
1731     /// specified function.
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     /// ```
1741     /// let a = [-3_i32, 0, 1, 5, -10];
1742     /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1743     /// ```
1744     #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1745     fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1746         where Self: Sized, F: FnMut(&Self::Item) -> B,
1747     {
1748         select_fold1(self,
1749                      f,
1750                      // only switch to y if it is strictly smaller, to
1751                      // preserve stability.
1752                      |x_p, _, y_p, _| x_p > y_p)
1753             .map(|(_, x)| x)
1754     }
1755
1756     /// Returns the element that gives the minimum value with respect to the
1757     /// specified comparison function.
1758     ///
1759     /// If several elements are equally minimum, the first element is
1760     /// returned. If the iterator is empty, [`None`] is returned.
1761     ///
1762     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1763     ///
1764     /// # Examples
1765     ///
1766     /// ```
1767     /// let a = [-3_i32, 0, 1, 5, -10];
1768     /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
1769     /// ```
1770     #[inline]
1771     #[stable(feature = "iter_min_by", since = "1.15.0")]
1772     fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
1773         where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
1774     {
1775         select_fold1(self,
1776                      |_| (),
1777                      // switch to y even if it is strictly smaller, to
1778                      // preserve stability.
1779                      |_, x, _, y| Ordering::Greater == compare(x, y))
1780             .map(|(_, x)| x)
1781     }
1782
1783
1784     /// Reverses an iterator's direction.
1785     ///
1786     /// Usually, iterators iterate from left to right. After using `rev()`,
1787     /// an iterator will instead iterate from right to left.
1788     ///
1789     /// This is only possible if the iterator has an end, so `rev()` only
1790     /// works on [`DoubleEndedIterator`]s.
1791     ///
1792     /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1793     ///
1794     /// # Examples
1795     ///
1796     /// ```
1797     /// let a = [1, 2, 3];
1798     ///
1799     /// let mut iter = a.iter().rev();
1800     ///
1801     /// assert_eq!(iter.next(), Some(&3));
1802     /// assert_eq!(iter.next(), Some(&2));
1803     /// assert_eq!(iter.next(), Some(&1));
1804     ///
1805     /// assert_eq!(iter.next(), None);
1806     /// ```
1807     #[inline]
1808     #[stable(feature = "rust1", since = "1.0.0")]
1809     fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1810         Rev{iter: self}
1811     }
1812
1813     /// Converts an iterator of pairs into a pair of containers.
1814     ///
1815     /// `unzip()` consumes an entire iterator of pairs, producing two
1816     /// collections: one from the left elements of the pairs, and one
1817     /// from the right elements.
1818     ///
1819     /// This function is, in some sense, the opposite of [`zip`].
1820     ///
1821     /// [`zip`]: #method.zip
1822     ///
1823     /// # Examples
1824     ///
1825     /// Basic usage:
1826     ///
1827     /// ```
1828     /// let a = [(1, 2), (3, 4)];
1829     ///
1830     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1831     ///
1832     /// assert_eq!(left, [1, 3]);
1833     /// assert_eq!(right, [2, 4]);
1834     /// ```
1835     #[stable(feature = "rust1", since = "1.0.0")]
1836     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1837         FromA: Default + Extend<A>,
1838         FromB: Default + Extend<B>,
1839         Self: Sized + Iterator<Item=(A, B)>,
1840     {
1841         let mut ts: FromA = Default::default();
1842         let mut us: FromB = Default::default();
1843
1844         for (t, u) in self {
1845             ts.extend(Some(t));
1846             us.extend(Some(u));
1847         }
1848
1849         (ts, us)
1850     }
1851
1852     /// Creates an iterator which [`clone`]s all of its elements.
1853     ///
1854     /// This is useful when you have an iterator over `&T`, but you need an
1855     /// iterator over `T`.
1856     ///
1857     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
1858     ///
1859     /// # Examples
1860     ///
1861     /// Basic usage:
1862     ///
1863     /// ```
1864     /// let a = [1, 2, 3];
1865     ///
1866     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1867     ///
1868     /// // cloned is the same as .map(|&x| x), for integers
1869     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1870     ///
1871     /// assert_eq!(v_cloned, vec![1, 2, 3]);
1872     /// assert_eq!(v_map, vec![1, 2, 3]);
1873     /// ```
1874     #[stable(feature = "rust1", since = "1.0.0")]
1875     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1876         where Self: Sized + Iterator<Item=&'a T>, T: Clone
1877     {
1878         Cloned { it: self }
1879     }
1880
1881     /// Repeats an iterator endlessly.
1882     ///
1883     /// Instead of stopping at [`None`], the iterator will instead start again,
1884     /// from the beginning. After iterating again, it will start at the
1885     /// beginning again. And again. And again. Forever.
1886     ///
1887     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1888     ///
1889     /// # Examples
1890     ///
1891     /// Basic usage:
1892     ///
1893     /// ```
1894     /// let a = [1, 2, 3];
1895     ///
1896     /// let mut it = a.iter().cycle();
1897     ///
1898     /// assert_eq!(it.next(), Some(&1));
1899     /// assert_eq!(it.next(), Some(&2));
1900     /// assert_eq!(it.next(), Some(&3));
1901     /// assert_eq!(it.next(), Some(&1));
1902     /// assert_eq!(it.next(), Some(&2));
1903     /// assert_eq!(it.next(), Some(&3));
1904     /// assert_eq!(it.next(), Some(&1));
1905     /// ```
1906     #[stable(feature = "rust1", since = "1.0.0")]
1907     #[inline]
1908     fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1909         Cycle{orig: self.clone(), iter: self}
1910     }
1911
1912     /// Sums the elements of an iterator.
1913     ///
1914     /// Takes each element, adds them together, and returns the result.
1915     ///
1916     /// An empty iterator returns the zero value of the type.
1917     ///
1918     /// # Panics
1919     ///
1920     /// When calling `sum()` and a primitive integer type is being returned, this
1921     /// method will panic if the computation overflows and debug assertions are
1922     /// enabled.
1923     ///
1924     /// # Examples
1925     ///
1926     /// Basic usage:
1927     ///
1928     /// ```
1929     /// let a = [1, 2, 3];
1930     /// let sum: i32 = a.iter().sum();
1931     ///
1932     /// assert_eq!(sum, 6);
1933     /// ```
1934     #[stable(feature = "iter_arith", since = "1.11.0")]
1935     fn sum<S>(self) -> S
1936         where Self: Sized,
1937               S: Sum<Self::Item>,
1938     {
1939         Sum::sum(self)
1940     }
1941
1942     /// Iterates over the entire iterator, multiplying all the elements
1943     ///
1944     /// An empty iterator returns the one value of the type.
1945     ///
1946     /// # Panics
1947     ///
1948     /// When calling `product()` and a primitive integer type is being returned,
1949     /// method will panic if the computation overflows and debug assertions are
1950     /// enabled.
1951     ///
1952     /// # Examples
1953     ///
1954     /// ```
1955     /// fn factorial(n: u32) -> u32 {
1956     ///     (1..).take_while(|&i| i <= n).product()
1957     /// }
1958     /// assert_eq!(factorial(0), 1);
1959     /// assert_eq!(factorial(1), 1);
1960     /// assert_eq!(factorial(5), 120);
1961     /// ```
1962     #[stable(feature = "iter_arith", since = "1.11.0")]
1963     fn product<P>(self) -> P
1964         where Self: Sized,
1965               P: Product<Self::Item>,
1966     {
1967         Product::product(self)
1968     }
1969
1970     /// Lexicographically compares the elements of this `Iterator` with those
1971     /// of another.
1972     #[stable(feature = "iter_order", since = "1.5.0")]
1973     fn cmp<I>(mut self, other: I) -> Ordering where
1974         I: IntoIterator<Item = Self::Item>,
1975         Self::Item: Ord,
1976         Self: Sized,
1977     {
1978         let mut other = other.into_iter();
1979
1980         loop {
1981             match (self.next(), other.next()) {
1982                 (None, None) => return Ordering::Equal,
1983                 (None, _   ) => return Ordering::Less,
1984                 (_   , None) => return Ordering::Greater,
1985                 (Some(x), Some(y)) => match x.cmp(&y) {
1986                     Ordering::Equal => (),
1987                     non_eq => return non_eq,
1988                 },
1989             }
1990         }
1991     }
1992
1993     /// Lexicographically compares the elements of this `Iterator` with those
1994     /// of another.
1995     #[stable(feature = "iter_order", since = "1.5.0")]
1996     fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
1997         I: IntoIterator,
1998         Self::Item: PartialOrd<I::Item>,
1999         Self: Sized,
2000     {
2001         let mut other = other.into_iter();
2002
2003         loop {
2004             match (self.next(), other.next()) {
2005                 (None, None) => return Some(Ordering::Equal),
2006                 (None, _   ) => return Some(Ordering::Less),
2007                 (_   , None) => return Some(Ordering::Greater),
2008                 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2009                     Some(Ordering::Equal) => (),
2010                     non_eq => return non_eq,
2011                 },
2012             }
2013         }
2014     }
2015
2016     /// Determines if the elements of this `Iterator` are equal to those of
2017     /// another.
2018     #[stable(feature = "iter_order", since = "1.5.0")]
2019     fn eq<I>(mut self, other: I) -> bool where
2020         I: IntoIterator,
2021         Self::Item: PartialEq<I::Item>,
2022         Self: Sized,
2023     {
2024         let mut other = other.into_iter();
2025
2026         loop {
2027             match (self.next(), other.next()) {
2028                 (None, None) => return true,
2029                 (None, _) | (_, None) => return false,
2030                 (Some(x), Some(y)) => if x != y { return false },
2031             }
2032         }
2033     }
2034
2035     /// Determines if the elements of this `Iterator` are unequal to those of
2036     /// another.
2037     #[stable(feature = "iter_order", since = "1.5.0")]
2038     fn ne<I>(mut self, other: I) -> bool where
2039         I: IntoIterator,
2040         Self::Item: PartialEq<I::Item>,
2041         Self: Sized,
2042     {
2043         let mut other = other.into_iter();
2044
2045         loop {
2046             match (self.next(), other.next()) {
2047                 (None, None) => return false,
2048                 (None, _) | (_, None) => return true,
2049                 (Some(x), Some(y)) => if x.ne(&y) { return true },
2050             }
2051         }
2052     }
2053
2054     /// Determines if the elements of this `Iterator` are lexicographically
2055     /// less than those of another.
2056     #[stable(feature = "iter_order", since = "1.5.0")]
2057     fn lt<I>(mut self, other: I) -> bool where
2058         I: IntoIterator,
2059         Self::Item: PartialOrd<I::Item>,
2060         Self: Sized,
2061     {
2062         let mut other = other.into_iter();
2063
2064         loop {
2065             match (self.next(), other.next()) {
2066                 (None, None) => return false,
2067                 (None, _   ) => return true,
2068                 (_   , None) => return false,
2069                 (Some(x), Some(y)) => {
2070                     match x.partial_cmp(&y) {
2071                         Some(Ordering::Less) => return true,
2072                         Some(Ordering::Equal) => {}
2073                         Some(Ordering::Greater) => return false,
2074                         None => return false,
2075                     }
2076                 },
2077             }
2078         }
2079     }
2080
2081     /// Determines if the elements of this `Iterator` are lexicographically
2082     /// less or equal to those of another.
2083     #[stable(feature = "iter_order", since = "1.5.0")]
2084     fn le<I>(mut self, other: I) -> bool where
2085         I: IntoIterator,
2086         Self::Item: PartialOrd<I::Item>,
2087         Self: Sized,
2088     {
2089         let mut other = other.into_iter();
2090
2091         loop {
2092             match (self.next(), other.next()) {
2093                 (None, None) => return true,
2094                 (None, _   ) => return true,
2095                 (_   , None) => return false,
2096                 (Some(x), Some(y)) => {
2097                     match x.partial_cmp(&y) {
2098                         Some(Ordering::Less) => return true,
2099                         Some(Ordering::Equal) => {}
2100                         Some(Ordering::Greater) => return false,
2101                         None => return false,
2102                     }
2103                 },
2104             }
2105         }
2106     }
2107
2108     /// Determines if the elements of this `Iterator` are lexicographically
2109     /// greater than those of another.
2110     #[stable(feature = "iter_order", since = "1.5.0")]
2111     fn gt<I>(mut self, other: I) -> bool where
2112         I: IntoIterator,
2113         Self::Item: PartialOrd<I::Item>,
2114         Self: Sized,
2115     {
2116         let mut other = other.into_iter();
2117
2118         loop {
2119             match (self.next(), other.next()) {
2120                 (None, None) => return false,
2121                 (None, _   ) => return false,
2122                 (_   , None) => return true,
2123                 (Some(x), Some(y)) => {
2124                     match x.partial_cmp(&y) {
2125                         Some(Ordering::Less) => return false,
2126                         Some(Ordering::Equal) => {}
2127                         Some(Ordering::Greater) => return true,
2128                         None => return false,
2129                     }
2130                 }
2131             }
2132         }
2133     }
2134
2135     /// Determines if the elements of this `Iterator` are lexicographically
2136     /// greater than or equal to those of another.
2137     #[stable(feature = "iter_order", since = "1.5.0")]
2138     fn ge<I>(mut self, other: I) -> bool where
2139         I: IntoIterator,
2140         Self::Item: PartialOrd<I::Item>,
2141         Self: Sized,
2142     {
2143         let mut other = other.into_iter();
2144
2145         loop {
2146             match (self.next(), other.next()) {
2147                 (None, None) => return true,
2148                 (None, _   ) => return false,
2149                 (_   , None) => return true,
2150                 (Some(x), Some(y)) => {
2151                     match x.partial_cmp(&y) {
2152                         Some(Ordering::Less) => return false,
2153                         Some(Ordering::Equal) => {}
2154                         Some(Ordering::Greater) => return true,
2155                         None => return false,
2156                     }
2157                 },
2158             }
2159         }
2160     }
2161 }
2162
2163 /// Select an element from an iterator based on the given projection
2164 /// and "comparison" function.
2165 ///
2166 /// This is an idiosyncratic helper to try to factor out the
2167 /// commonalities of {max,min}{,_by}. In particular, this avoids
2168 /// having to implement optimizations several times.
2169 #[inline]
2170 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2171                                   mut f_proj: FProj,
2172                                   mut f_cmp: FCmp) -> Option<(B, I::Item)>
2173     where I: Iterator,
2174           FProj: FnMut(&I::Item) -> B,
2175           FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2176 {
2177     // start with the first element as our selection. This avoids
2178     // having to use `Option`s inside the loop, translating to a
2179     // sizeable performance gain (6x in one case).
2180     it.next().map(|mut sel| {
2181         let mut sel_p = f_proj(&sel);
2182
2183         for x in it {
2184             let x_p = f_proj(&x);
2185             if f_cmp(&sel_p,  &sel, &x_p, &x) {
2186                 sel = x;
2187                 sel_p = x_p;
2188             }
2189         }
2190         (sel_p, sel)
2191     })
2192 }
2193
2194 #[stable(feature = "rust1", since = "1.0.0")]
2195 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2196     type Item = I::Item;
2197     fn next(&mut self) -> Option<I::Item> { (**self).next() }
2198     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2199     fn nth(&mut self, n: usize) -> Option<Self::Item> {
2200         (**self).nth(n)
2201     }
2202 }