]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter.rs
Auto merge of #29256 - alexcrichton:less-flaky, r=brson
[rust.git] / src / libcore / iter.rs
1 // Copyright 2013-2014 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 //! Composable external iteration
12 //!
13 //! If you've found yourself with a collection of some kind, and needed to
14 //! perform an operation on the elements of said collection, you'll quickly run
15 //! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
16 //! it's worth becoming familiar with them.
17 //!
18 //! Before explaining more, let's talk about how this module is structured:
19 //!
20 //! # Organization
21 //!
22 //! This module is largely organized by type:
23 //!
24 //! * [Traits] are the core portion: these traits define what kind of iterators
25 //!   exist and what you can do with them. The methods of these traits are worth
26 //!   putting some extra study time into.
27 //! * [Functions] provide some helpful ways to create some basic iterators.
28 //! * [Structs] are often the return types of the various methods on this
29 //!   module's traits. You'll usually want to look at the method that creates
30 //!   the `struct`, rather than the `struct` itself. For more detail about why,
31 //!   see '[Implementing Iterator](#implementing-iterator)'.
32 //!
33 //! [Traits]: #traits
34 //! [Functions]: #functions
35 //! [Structs]: #structs
36 //!
37 //! That's it! Let's dig into iterators.
38 //!
39 //! # Iterator
40 //!
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
43 //!
44 //! ```
45 //! trait Iterator {
46 //!     type Item;
47 //!     fn next(&mut self) -> Option<Self::Item>;
48 //! }
49 //! ```
50 //!
51 //! An iterator has a method, [`next()`], which when called, returns an
52 //! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
53 //! are elements, and once they've all been exhausted, will return `None` to
54 //! indicate that iteration is finished. Individual iterators may choose to
55 //! resume iteration, and so calling [`next()`] again may or may not eventually
56 //! start returning `Some(Item)` again at some point.
57 //!
58 //! [`Iterator`]'s full definition includes a number of other methods as well,
59 //! but they are default methods, built on top of [`next()`], and so you get
60 //! them for free.
61 //!
62 //! Iterators are also composable, and it's common to chain them together to do
63 //! more complex forms of processing. See the [Adapters](#adapters) section
64 //! below for more details.
65 //!
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../option/enum.Option.html
69 //!
70 //! # The three forms of iteration
71 //!
72 //! There are three common methods which can create iterators from a collection:
73 //!
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
77 //!
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
80 //!
81 //! # Implementing Iterator
82 //!
83 //! Creating an iterator of your own involves two steps: creating a `struct` to
84 //! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
85 //! `struct`. This is why there are so many `struct`s in this module: there is
86 //! one for each iterator and iterator adapter.
87 //!
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
89 //!
90 //! ```
91 //! // First, the struct:
92 //!
93 //! /// An iterator which counts from one to five
94 //! struct Counter {
95 //!     count: usize,
96 //! }
97 //!
98 //! // we want our count to start at one, so let's add a new() method to help.
99 //! // This isn't strictly necessary, but is convenient. Note that we start
100 //! // `count` at zero, we'll see why in `next()`'s implementation below.
101 //! impl Counter {
102 //!     fn new() -> Counter {
103 //!         Counter { count: 0 }
104 //!     }
105 //! }
106 //!
107 //! // Then, we implement `Iterator` for our `Counter`:
108 //!
109 //! impl Iterator for Counter {
110 //!     // we will be counting with usize
111 //!     type Item = usize;
112 //!
113 //!     // next() is the only required method
114 //!     fn next(&mut self) -> Option<usize> {
115 //!         // increment our count. This is why we started at zero.
116 //!         self.count += 1;
117 //!
118 //!         // check to see if we've finished counting or not.
119 //!         if self.count < 6 {
120 //!             Some(self.count)
121 //!         } else {
122 //!             None
123 //!         }
124 //!     }
125 //! }
126 //!
127 //! // And now we can use it!
128 //!
129 //! let mut counter = Counter::new();
130 //!
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
133 //!
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
136 //!
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
139 //!
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
142 //!
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
145 //! ```
146 //!
147 //! This will print `1` through `5`, each on their own line.
148 //!
149 //! Calling `next()` this way gets repetitive. Rust has a construct which can
150 //! call `next()` on your iterator, until it reaches `None`. Let's go over that
151 //! next.
152 //!
153 //! # for Loops and IntoIterator
154 //!
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
157 //!
158 //! ```
159 //! let values = vec![1, 2, 3, 4, 5];
160 //!
161 //! for x in values {
162 //!     println!("{}", x);
163 //! }
164 //! ```
165 //!
166 //! This will print the numbers one through five, each on their own line. But
167 //! you'll notice something here: we never called anything on our vector to
168 //! produce an iterator. What gives?
169 //!
170 //! There's a trait in the standard library for converting something into an
171 //! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
172 //! which converts the thing implementing [`IntoIterator`] into an iterator.
173 //! Let's take a look at that `for` loop again, and what the compiler converts
174 //! it into:
175 //!
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
178 //!
179 //! ```
180 //! let values = vec![1, 2, 3, 4, 5];
181 //!
182 //! for x in values {
183 //!     println!("{}", x);
184 //! }
185 //! ```
186 //!
187 //! Rust de-sugars this into:
188 //!
189 //! ```
190 //! let values = vec![1, 2, 3, 4, 5];
191 //! {
192 //!     let result = match values.into_iter() {
193 //!         mut iter => loop {
194 //!             match iter.next() {
195 //!                 Some(x) => { println!("{}", x); },
196 //!                 None => break,
197 //!             }
198 //!         },
199 //!     };
200 //!     result
201 //! }
202 //! ```
203 //!
204 //! First, we call `into_iter()` on the value. Then, we match on the iterator
205 //! that returns, calling [`next()`] over and over until we see a `None`. At
206 //! that point, we `break` out of the loop, and we're done iterating.
207 //!
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
210 //!
211 //! ```ignore
212 //! impl<I: Iterator> IntoIterator for I
213 //! ```
214 //!
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
217 //!
218 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
219 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
220 //!    will allow your collection to be used with the `for` loop.
221 //!
222 //! # Adapters
223 //!
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
226 //! pattern'.
227 //!
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
230 //!
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
234 //!
235 //! # Laziness
236 //!
237 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
238 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
239 //! until you call [`next()`]. This is sometimes a source of confusion when
240 //! creating an iterator solely for its side effects. For example, the [`map()`]
241 //! method calls a closure on each element it iterates over:
242 //!
243 //! ```
244 //! let v = vec![1, 2, 3, 4, 5];
245 //! v.iter().map(|x| println!("{}", x));
246 //! ```
247 //!
248 //! This will not print any values, as we only created an iterator, rather than
249 //! using it. The compiler will warn us about this kind of behavior:
250 //!
251 //! ```text
252 //! warning: unused result which must be used: iterator adaptors are lazy and
253 //! do nothing unless consumed
254 //! ```
255 //!
256 //! The idiomatic way to write a [`map()`] for its side effects is to use a
257 //! `for` loop instead:
258 //!
259 //! ```
260 //! let v = vec![1, 2, 3, 4, 5];
261 //!
262 //! for x in &v {
263 //!     println!("{}", x);
264 //! }
265 //! ```
266 //!
267 //! [`map()`]: trait.Iterator.html#method.map
268 //!
269 //! The two most common ways to evaluate an iterator are to use a `for` loop
270 //! like this, or using the [`collect()`] adapter to produce a new collection.
271 //!
272 //! [`collect()`]: trait.Iterator.html#method.collect
273 //!
274 //! # Infinity
275 //!
276 //! Iterators do not have to be finite. As an example, an open-ended range is
277 //! an infinite iterator:
278 //!
279 //! ```
280 //! let numbers = 0..;
281 //! ```
282 //!
283 //! It is common to use the [`take()`] iterator adapter to turn an infinite
284 //! iterator into a finite one:
285 //!
286 //! ```
287 //! let numbers = 0..;
288 //! let five_numbers = numbers.take(5);
289 //!
290 //! for number in five_numbers {
291 //!     println!("{}", number);
292 //! }
293 //! ```
294 //!
295 //! This will print the numbers `0` through `4`, each on their own line.
296 //!
297 //! [`take()`]: trait.Iterator.html#method.take
298
299 #![stable(feature = "rust1", since = "1.0.0")]
300
301 use clone::Clone;
302 use cmp;
303 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
304 use default::Default;
305 use marker;
306 use mem;
307 use num::{Zero, One};
308 use ops::{self, Add, Sub, FnMut, Mul, RangeFrom};
309 use option::Option::{self, Some, None};
310 use marker::Sized;
311 use usize;
312
313 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
314
315 /// An interface for dealing with "external iterators". These types of iterators
316 /// can be resumed at any time as all state is stored internally as opposed to
317 /// being located on the call stack.
318 ///
319 /// The Iterator protocol states that an iterator yields a (potentially-empty,
320 /// potentially-infinite) sequence of values, and returns `None` to signal that
321 /// it's finished. The Iterator protocol does not define behavior after `None`
322 /// is returned. A concrete Iterator implementation may choose to behave however
323 /// it wishes, either by returning `None` infinitely, or by doing something
324 /// else.
325 #[lang = "iterator"]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
328                             `.iter()` or a similar method"]
329 pub trait Iterator {
330     /// The type of the elements being iterated
331     #[stable(feature = "rust1", since = "1.0.0")]
332     type Item;
333
334     /// Advances the iterator and returns the next value. Returns `None` when the
335     /// end is reached.
336     #[stable(feature = "rust1", since = "1.0.0")]
337     fn next(&mut self) -> Option<Self::Item>;
338
339     /// Returns a lower and upper bound on the remaining length of the iterator.
340     ///
341     /// An upper bound of `None` means either there is no known upper bound, or
342     /// the upper bound does not fit within a `usize`.
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// let it = (0..10).filter(|x| x % 2 == 0).chain(15..20);
348     /// assert_eq!((5, Some(15)), it.size_hint());
349     /// ```
350     #[inline]
351     #[stable(feature = "rust1", since = "1.0.0")]
352     fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
353
354     /// Counts the number of elements in this iterator.
355     ///
356     /// # Overflow Behavior
357     ///
358     /// The method does no guarding against overflows, so counting elements of
359     /// an iterator with more than `usize::MAX` elements either produces the
360     /// wrong result or panics. If debug assertions are enabled, a panic is
361     /// guaranteed.
362     ///
363     /// # Panics
364     ///
365     /// This functions might panic if the iterator has more than `usize::MAX`
366     /// elements.
367     ///
368     /// # Examples
369     ///
370     /// ```
371     /// let a = [1, 2, 3, 4, 5];
372     /// assert_eq!(a.iter().count(), 5);
373     /// ```
374     #[inline]
375     #[stable(feature = "rust1", since = "1.0.0")]
376     fn count(self) -> usize where Self: Sized {
377         // Might overflow.
378         self.fold(0, |cnt, _| cnt + 1)
379     }
380
381     /// Loops through the entire iterator, returning the last element.
382     ///
383     /// # Examples
384     ///
385     /// ```
386     /// let a = [1, 2, 3, 4, 5];
387     /// assert_eq!(a.iter().last(), Some(&5));
388     /// ```
389     #[inline]
390     #[stable(feature = "rust1", since = "1.0.0")]
391     fn last(self) -> Option<Self::Item> where Self: Sized {
392         let mut last = None;
393         for x in self { last = Some(x); }
394         last
395     }
396
397     /// Skips the `n` first elements of the iterator and returns the next one.
398     ///
399     /// # Examples
400     ///
401     /// ```
402     /// let a = [1, 2, 3, 4, 5];
403     /// let mut it = a.iter();
404     /// assert_eq!(it.nth(2), Some(&3));
405     /// assert_eq!(it.nth(2), None);
406     /// ```
407     #[inline]
408     #[stable(feature = "rust1", since = "1.0.0")]
409     fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
410         for x in self {
411             if n == 0 { return Some(x) }
412             n -= 1;
413         }
414         None
415     }
416
417     /// Chain this iterator with another, returning a new iterator that will
418     /// finish iterating over the current iterator, and then iterate
419     /// over the other specified iterator.
420     ///
421     /// # Examples
422     ///
423     /// ```
424     /// let a = [0];
425     /// let b = [1];
426     /// let mut it = a.iter().chain(&b);
427     /// assert_eq!(it.next(), Some(&0));
428     /// assert_eq!(it.next(), Some(&1));
429     /// assert!(it.next().is_none());
430     /// ```
431     #[inline]
432     #[stable(feature = "rust1", since = "1.0.0")]
433     fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
434         Self: Sized, U: IntoIterator<Item=Self::Item>,
435     {
436         Chain{a: self, b: other.into_iter(), state: ChainState::Both}
437     }
438
439     /// Creates an iterator that iterates over both this and the specified
440     /// iterators simultaneously, yielding the two elements as pairs. When
441     /// either iterator returns `None`, all further invocations of `next()`
442     /// will return `None`.
443     ///
444     /// # Examples
445     ///
446     /// ```
447     /// let a = [0];
448     /// let b = [1];
449     /// let mut it = a.iter().zip(&b);
450     /// assert_eq!(it.next(), Some((&0, &1)));
451     /// assert!(it.next().is_none());
452     /// ```
453     ///
454     /// `zip` can provide similar functionality to `enumerate`:
455     ///
456     /// ```
457     /// for pair in "foo".chars().enumerate() {
458     ///     println!("{:?}", pair);
459     /// }
460     ///
461     /// for pair in (0..).zip("foo".chars()) {
462     ///     println!("{:?}", pair);
463     /// }
464     /// ```
465     ///
466     /// both produce the same output.
467     #[inline]
468     #[stable(feature = "rust1", since = "1.0.0")]
469     fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
470         Self: Sized, U: IntoIterator
471     {
472         Zip{a: self, b: other.into_iter()}
473     }
474
475     /// Creates a new iterator that will apply the specified function to each
476     /// element returned by the first, yielding the mapped element instead.
477     ///
478     /// # Examples
479     ///
480     /// ```
481     /// let a = [1, 2];
482     /// let mut it = a.iter().map(|&x| 2 * x);
483     /// assert_eq!(it.next(), Some(2));
484     /// assert_eq!(it.next(), Some(4));
485     /// assert!(it.next().is_none());
486     /// ```
487     #[inline]
488     #[stable(feature = "rust1", since = "1.0.0")]
489     fn map<B, F>(self, f: F) -> Map<Self, F> where
490         Self: Sized, F: FnMut(Self::Item) -> B,
491     {
492         Map{iter: self, f: f}
493     }
494
495     /// Creates an iterator that applies the predicate to each element returned
496     /// by this iterator. The only elements that will be yielded are those that
497     /// make the predicate evaluate to `true`.
498     ///
499     /// # Examples
500     ///
501     /// ```
502     /// let a = [1, 2];
503     /// let mut it = a.iter().filter(|&x| *x > 1);
504     /// assert_eq!(it.next(), Some(&2));
505     /// assert!(it.next().is_none());
506     /// ```
507     #[inline]
508     #[stable(feature = "rust1", since = "1.0.0")]
509     fn filter<P>(self, predicate: P) -> Filter<Self, P> where
510         Self: Sized, P: FnMut(&Self::Item) -> bool,
511     {
512         Filter{iter: self, predicate: predicate}
513     }
514
515     /// Creates an iterator that both filters and maps elements.
516     /// If the specified function returns `None`, the element is skipped.
517     /// Otherwise the option is unwrapped and the new value is yielded.
518     ///
519     /// # Examples
520     ///
521     /// ```
522     /// let a = [1, 2];
523     /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
524     /// assert_eq!(it.next(), Some(4));
525     /// assert!(it.next().is_none());
526     /// ```
527     #[inline]
528     #[stable(feature = "rust1", since = "1.0.0")]
529     fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
530         Self: Sized, F: FnMut(Self::Item) -> Option<B>,
531     {
532         FilterMap { iter: self, f: f }
533     }
534
535     /// Creates an iterator that yields pairs `(i, val)` where `i` is the
536     /// current index of iteration and `val` is the value returned by the
537     /// iterator.
538     ///
539     /// `enumerate` keeps its count as a `usize`. If you want to count by a
540     /// different sized integer, the `zip` function provides similar
541     /// functionality.
542     ///
543     /// # Overflow Behavior
544     ///
545     /// The method does no guarding against overflows, so enumerating more than
546     /// `usize::MAX` elements either produces the wrong result or panics. If
547     /// debug assertions are enabled, a panic is guaranteed.
548     ///
549     /// # Panics
550     ///
551     /// The returned iterator might panic if the to-be-returned index would
552     /// overflow a `usize`.
553     ///
554     /// # Examples
555     ///
556     /// ```
557     /// let a = [100, 200];
558     /// let mut it = a.iter().enumerate();
559     /// assert_eq!(it.next(), Some((0, &100)));
560     /// assert_eq!(it.next(), Some((1, &200)));
561     /// assert!(it.next().is_none());
562     /// ```
563     #[inline]
564     #[stable(feature = "rust1", since = "1.0.0")]
565     fn enumerate(self) -> Enumerate<Self> where Self: Sized {
566         Enumerate { iter: self, count: 0 }
567     }
568
569     /// Creates an iterator that has a `.peek()` method
570     /// that returns an optional reference to the next element.
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// let xs = [100, 200, 300];
576     /// let mut it = xs.iter().cloned().peekable();
577     /// assert_eq!(*it.peek().unwrap(), 100);
578     /// assert_eq!(it.next().unwrap(), 100);
579     /// assert_eq!(it.next().unwrap(), 200);
580     /// assert_eq!(*it.peek().unwrap(), 300);
581     /// assert_eq!(*it.peek().unwrap(), 300);
582     /// assert_eq!(it.next().unwrap(), 300);
583     /// assert!(it.peek().is_none());
584     /// assert!(it.next().is_none());
585     /// ```
586     #[inline]
587     #[stable(feature = "rust1", since = "1.0.0")]
588     fn peekable(self) -> Peekable<Self> where Self: Sized {
589         Peekable{iter: self, peeked: None}
590     }
591
592     /// Creates an iterator that invokes the predicate on elements
593     /// until it returns false. Once the predicate returns false, that
594     /// element and all further elements are yielded.
595     ///
596     /// # Examples
597     ///
598     /// ```
599     /// let a = [1, 2, 3, 4, 5];
600     /// let mut it = a.iter().skip_while(|&a| *a < 3);
601     /// assert_eq!(it.next(), Some(&3));
602     /// assert_eq!(it.next(), Some(&4));
603     /// assert_eq!(it.next(), Some(&5));
604     /// assert!(it.next().is_none());
605     /// ```
606     #[inline]
607     #[stable(feature = "rust1", since = "1.0.0")]
608     fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
609         Self: Sized, P: FnMut(&Self::Item) -> bool,
610     {
611         SkipWhile{iter: self, flag: false, predicate: predicate}
612     }
613
614     /// Creates an iterator that yields elements so long as the predicate
615     /// returns true. After the predicate returns false for the first time, no
616     /// further elements will be yielded.
617     ///
618     /// # Examples
619     ///
620     /// ```
621     /// let a = [1, 2, 3, 4, 5];
622     /// let mut it = a.iter().take_while(|&a| *a < 3);
623     /// assert_eq!(it.next(), Some(&1));
624     /// assert_eq!(it.next(), Some(&2));
625     /// assert!(it.next().is_none());
626     /// ```
627     #[inline]
628     #[stable(feature = "rust1", since = "1.0.0")]
629     fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
630         Self: Sized, P: FnMut(&Self::Item) -> bool,
631     {
632         TakeWhile{iter: self, flag: false, predicate: predicate}
633     }
634
635     /// Creates an iterator that skips the first `n` elements of this iterator,
636     /// and then yields all further items.
637     ///
638     /// # Examples
639     ///
640     /// ```
641     /// let a = [1, 2, 3, 4, 5];
642     /// let mut it = a.iter().skip(3);
643     /// assert_eq!(it.next(), Some(&4));
644     /// assert_eq!(it.next(), Some(&5));
645     /// assert!(it.next().is_none());
646     /// ```
647     #[inline]
648     #[stable(feature = "rust1", since = "1.0.0")]
649     fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
650         Skip{iter: self, n: n}
651     }
652
653     /// Creates an iterator that yields the first `n` elements of this
654     /// iterator.
655     ///
656     /// # Examples
657     ///
658     /// ```
659     /// let a = [1, 2, 3, 4, 5];
660     /// let mut it = a.iter().take(3);
661     /// assert_eq!(it.next(), Some(&1));
662     /// assert_eq!(it.next(), Some(&2));
663     /// assert_eq!(it.next(), Some(&3));
664     /// assert!(it.next().is_none());
665     /// ```
666     #[inline]
667     #[stable(feature = "rust1", since = "1.0.0")]
668     fn take(self, n: usize) -> Take<Self> where Self: Sized, {
669         Take{iter: self, n: n}
670     }
671
672     /// Creates a new iterator that behaves in a similar fashion to fold.
673     /// There is a state which is passed between each iteration and can be
674     /// mutated as necessary. The yielded values from the closure are yielded
675     /// from the Scan instance when not `None`.
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// let a = [1, 2, 3, 4, 5];
681     /// let mut it = a.iter().scan(1, |fac, &x| {
682     ///   *fac = *fac * x;
683     ///   Some(*fac)
684     /// });
685     /// assert_eq!(it.next(), Some(1));
686     /// assert_eq!(it.next(), Some(2));
687     /// assert_eq!(it.next(), Some(6));
688     /// assert_eq!(it.next(), Some(24));
689     /// assert_eq!(it.next(), Some(120));
690     /// assert!(it.next().is_none());
691     /// ```
692     #[inline]
693     #[stable(feature = "rust1", since = "1.0.0")]
694     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
695         where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
696     {
697         Scan{iter: self, f: f, state: initial_state}
698     }
699
700     /// Takes a function that maps each element to a new iterator and yields
701     /// all the elements of the produced iterators.
702     ///
703     /// This is useful for unraveling nested structures.
704     ///
705     /// # Examples
706     ///
707     /// ```
708     /// let words = ["alpha", "beta", "gamma"];
709     /// let merged: String = words.iter()
710     ///                           .flat_map(|s| s.chars())
711     ///                           .collect();
712     /// assert_eq!(merged, "alphabetagamma");
713     /// ```
714     #[inline]
715     #[stable(feature = "rust1", since = "1.0.0")]
716     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
717         where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
718     {
719         FlatMap{iter: self, f: f, frontiter: None, backiter: None }
720     }
721
722     /// Creates an iterator that yields `None` forever after the underlying
723     /// iterator yields `None`. Random-access iterator behavior is not
724     /// affected, only single and double-ended iterator behavior.
725     ///
726     /// # Examples
727     ///
728     /// ```
729     /// fn process<U: Iterator<Item=i32>>(it: U) -> i32 {
730     ///     let mut it = it.fuse();
731     ///     let mut sum = 0;
732     ///     for x in it.by_ref() {
733     ///         if x > 5 {
734     ///             break;
735     ///         }
736     ///         sum += x;
737     ///     }
738     ///     // did we exhaust the iterator?
739     ///     if it.next().is_none() {
740     ///         sum += 1000;
741     ///     }
742     ///     sum
743     /// }
744     /// let x = vec![1, 2, 3, 7, 8, 9];
745     /// assert_eq!(process(x.into_iter()), 6);
746     /// let x = vec![1, 2, 3];
747     /// assert_eq!(process(x.into_iter()), 1006);
748     /// ```
749     #[inline]
750     #[stable(feature = "rust1", since = "1.0.0")]
751     fn fuse(self) -> Fuse<Self> where Self: Sized {
752         Fuse{iter: self, done: false}
753     }
754
755     /// Creates an iterator that calls a function with a reference to each
756     /// element before yielding it. This is often useful for debugging an
757     /// iterator pipeline.
758     ///
759     /// # Examples
760     ///
761     /// ```
762     /// let a = [1, 4, 2, 3, 8, 9, 6];
763     /// let sum: i32 = a.iter()
764     ///                 .map(|x| *x)
765     ///                 .inspect(|&x| println!("filtering {}", x))
766     ///                 .filter(|&x| x % 2 == 0)
767     ///                 .inspect(|&x| println!("{} made it through", x))
768     ///                 .fold(0, |sum, i| sum + i);
769     /// println!("{}", sum);
770     /// ```
771     #[inline]
772     #[stable(feature = "rust1", since = "1.0.0")]
773     fn inspect<F>(self, f: F) -> Inspect<Self, F> where
774         Self: Sized, F: FnMut(&Self::Item),
775     {
776         Inspect{iter: self, f: f}
777     }
778
779     /// Creates a wrapper around a mutable reference to the iterator.
780     ///
781     /// This is useful to allow applying iterator adaptors while still
782     /// retaining ownership of the original iterator value.
783     ///
784     /// # Examples
785     ///
786     /// ```
787     /// let mut it = 0..10;
788     /// // sum the first five values
789     /// let partial_sum = it.by_ref().take(5).fold(0, |a, b| a + b);
790     /// assert_eq!(partial_sum, 10);
791     /// assert_eq!(it.next(), Some(5));
792     /// ```
793     #[stable(feature = "rust1", since = "1.0.0")]
794     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
795
796     /// Loops through the entire iterator, collecting all of the elements into
797     /// a container implementing `FromIterator`.
798     ///
799     /// # Examples
800     ///
801     /// ```
802     /// let expected = [1, 2, 3, 4, 5];
803     /// let actual: Vec<_> = expected.iter().cloned().collect();
804     /// assert_eq!(actual, expected);
805     /// ```
806     #[inline]
807     #[stable(feature = "rust1", since = "1.0.0")]
808     fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
809         FromIterator::from_iter(self)
810     }
811
812     /// Loops through the entire iterator, collecting all of the elements into
813     /// one of two containers, depending on a predicate. The elements of the
814     /// first container satisfy the predicate, while the elements of the second
815     /// do not.
816     ///
817     /// ```
818     /// let vec = vec![1, 2, 3, 4];
819     /// let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0);
820     /// assert_eq!(even, [2, 4]);
821     /// assert_eq!(odd, [1, 3]);
822     /// ```
823     #[stable(feature = "rust1", since = "1.0.0")]
824     fn partition<B, F>(self, mut f: F) -> (B, B) where
825         Self: Sized,
826         B: Default + Extend<Self::Item>,
827         F: FnMut(&Self::Item) -> bool
828     {
829         let mut left: B = Default::default();
830         let mut right: B = Default::default();
831
832         for x in self {
833             if f(&x) {
834                 left.extend(Some(x))
835             } else {
836                 right.extend(Some(x))
837             }
838         }
839
840         (left, right)
841     }
842
843     /// Performs a fold operation over the entire iterator, returning the
844     /// eventual state at the end of the iteration.
845     ///
846     /// This operation is sometimes called 'reduce' or 'inject'.
847     ///
848     /// # Examples
849     ///
850     /// ```
851     /// let a = [1, 2, 3, 4, 5];
852     /// assert_eq!(a.iter().fold(0, |acc, &item| acc + item), 15);
853     /// ```
854     #[inline]
855     #[stable(feature = "rust1", since = "1.0.0")]
856     fn fold<B, F>(self, init: B, mut f: F) -> B where
857         Self: Sized, F: FnMut(B, Self::Item) -> B,
858     {
859         let mut accum = init;
860         for x in self {
861             accum = f(accum, x);
862         }
863         accum
864     }
865
866     /// Tests whether the predicate holds true for all elements in the iterator.
867     ///
868     /// Does not consume the iterator past the first non-matching element.
869     ///
870     /// # Examples
871     ///
872     /// ```
873     /// let a = [1, 2, 3, 4, 5];
874     /// assert!(a.iter().all(|x| *x > 0));
875     /// assert!(!a.iter().all(|x| *x > 2));
876     /// ```
877     #[inline]
878     #[stable(feature = "rust1", since = "1.0.0")]
879     fn all<F>(&mut self, mut f: F) -> bool where
880         Self: Sized, F: FnMut(Self::Item) -> bool
881     {
882         for x in self {
883             if !f(x) {
884                 return false;
885             }
886         }
887         true
888     }
889
890     /// Tests whether any element of an iterator satisfies the specified
891     /// predicate.
892     ///
893     /// Does not consume the iterator past the first found element.
894     ///
895     /// # Examples
896     ///
897     /// ```
898     /// let a = [1, 2, 3, 4, 5];
899     /// let mut it = a.iter();
900     /// assert!(it.any(|x| *x == 3));
901     /// assert_eq!(it.collect::<Vec<_>>(), [&4, &5]);
902     /// ```
903     #[inline]
904     #[stable(feature = "rust1", since = "1.0.0")]
905     fn any<F>(&mut self, mut f: F) -> bool where
906         Self: Sized,
907         F: FnMut(Self::Item) -> bool
908     {
909         for x in self {
910             if f(x) {
911                 return true;
912             }
913         }
914         false
915     }
916
917     /// Returns the first element satisfying the specified predicate.
918     ///
919     /// Does not consume the iterator past the first found element.
920     ///
921     /// # Examples
922     ///
923     /// ```
924     /// let a = [1, 2, 3, 4, 5];
925     /// let mut it = a.iter();
926     /// assert_eq!(it.find(|&x| *x == 3), Some(&3));
927     /// assert_eq!(it.collect::<Vec<_>>(), [&4, &5]);
928     #[inline]
929     #[stable(feature = "rust1", since = "1.0.0")]
930     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
931         Self: Sized,
932         P: FnMut(&Self::Item) -> bool,
933     {
934         for x in self {
935             if predicate(&x) { return Some(x) }
936         }
937         None
938     }
939
940     /// Returns the index of the first element satisfying the specified predicate
941     ///
942     /// Does not consume the iterator past the first found element.
943     ///
944     /// # Overflow Behavior
945     ///
946     /// The method does no guarding against overflows, so if there are more
947     /// than `usize::MAX` non-matching elements, it either produces the wrong
948     /// result or panics. If debug assertions are enabled, a panic is
949     /// guaranteed.
950     ///
951     /// # Panics
952     ///
953     /// This functions might panic if the iterator has more than `usize::MAX`
954     /// non-matching elements.
955     ///
956     /// # Examples
957     ///
958     /// ```
959     /// let a = [1, 2, 3, 4, 5];
960     /// let mut it = a.iter();
961     /// assert_eq!(it.position(|x| *x == 3), Some(2));
962     /// assert_eq!(it.collect::<Vec<_>>(), [&4, &5]);
963     #[inline]
964     #[stable(feature = "rust1", since = "1.0.0")]
965     fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
966         Self: Sized,
967         P: FnMut(Self::Item) -> bool,
968     {
969         // `enumerate` might overflow.
970         for (i, x) in self.enumerate() {
971             if predicate(x) {
972                 return Some(i);
973             }
974         }
975         None
976     }
977
978     /// Returns the index of the last element satisfying the specified predicate
979     ///
980     /// If no element matches, `None` is returned.
981     ///
982     /// Does not consume the iterator *before* the first found element.
983     ///
984     /// # Examples
985     ///
986     /// ```
987     /// let a = [1, 2, 2, 4, 5];
988     /// let mut it = a.iter();
989     /// assert_eq!(it.rposition(|x| *x == 2), Some(2));
990     /// assert_eq!(it.collect::<Vec<_>>(), [&1, &2]);
991     #[inline]
992     #[stable(feature = "rust1", since = "1.0.0")]
993     fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
994         P: FnMut(Self::Item) -> bool,
995         Self: Sized + ExactSizeIterator + DoubleEndedIterator
996     {
997         let mut i = self.len();
998
999         while let Some(v) = self.next_back() {
1000             if predicate(v) {
1001                 return Some(i - 1);
1002             }
1003             // No need for an overflow check here, because `ExactSizeIterator`
1004             // implies that the number of elements fits into a `usize`.
1005             i -= 1;
1006         }
1007         None
1008     }
1009
1010     /// Consumes the entire iterator to return the maximum element.
1011     ///
1012     /// Returns the rightmost element if the comparison determines two elements
1013     /// to be equally maximum.
1014     ///
1015     /// # Examples
1016     ///
1017     /// ```
1018     /// let a = [1, 2, 3, 4, 5];
1019     /// assert_eq!(a.iter().max(), Some(&5));
1020     /// ```
1021     #[inline]
1022     #[stable(feature = "rust1", since = "1.0.0")]
1023     fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1024     {
1025         select_fold1(self,
1026                      |_| (),
1027                      // switch to y even if it is only equal, to preserve
1028                      // stability.
1029                      |_, x, _, y| *x <= *y)
1030             .map(|(_, x)| x)
1031     }
1032
1033     /// Consumes the entire iterator to return the minimum element.
1034     ///
1035     /// Returns the leftmost element if the comparison determines two elements
1036     /// to be equally minimum.
1037     ///
1038     /// # Examples
1039     ///
1040     /// ```
1041     /// let a = [1, 2, 3, 4, 5];
1042     /// assert_eq!(a.iter().min(), Some(&1));
1043     /// ```
1044     #[inline]
1045     #[stable(feature = "rust1", since = "1.0.0")]
1046     fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1047     {
1048         select_fold1(self,
1049                      |_| (),
1050                      // only switch to y if it is strictly smaller, to
1051                      // preserve stability.
1052                      |_, x, _, y| *x > *y)
1053             .map(|(_, x)| x)
1054     }
1055
1056     /// Returns the element that gives the maximum value from the
1057     /// specified function.
1058     ///
1059     /// Returns the rightmost element if the comparison determines two elements
1060     /// to be equally maximum.
1061     ///
1062     /// # Examples
1063     ///
1064     /// ```
1065     /// #![feature(iter_cmp)]
1066     ///
1067     /// let a = [-3_i32, 0, 1, 5, -10];
1068     /// assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10);
1069     /// ```
1070     #[inline]
1071     #[unstable(feature = "iter_cmp",
1072                reason = "may want to produce an Ordering directly; see #15311",
1073                issue = "27724")]
1074     fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1075         Self: Sized,
1076         F: FnMut(&Self::Item) -> B,
1077     {
1078         select_fold1(self,
1079                      f,
1080                      // switch to y even if it is only equal, to preserve
1081                      // stability.
1082                      |x_p, _, y_p, _| x_p <= y_p)
1083             .map(|(_, x)| x)
1084     }
1085
1086     /// Returns the element that gives the minimum value from the
1087     /// specified function.
1088     ///
1089     /// Returns the leftmost element if the comparison determines two elements
1090     /// to be equally minimum.
1091     ///
1092     /// # Examples
1093     ///
1094     /// ```
1095     /// #![feature(iter_cmp)]
1096     ///
1097     /// let a = [-3_i32, 0, 1, 5, -10];
1098     /// assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0);
1099     /// ```
1100     #[inline]
1101     #[unstable(feature = "iter_cmp",
1102                reason = "may want to produce an Ordering directly; see #15311",
1103                issue = "27724")]
1104     fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1105         Self: Sized,
1106         F: FnMut(&Self::Item) -> B,
1107     {
1108         select_fold1(self,
1109                      f,
1110                      // only switch to y if it is strictly smaller, to
1111                      // preserve stability.
1112                      |x_p, _, y_p, _| x_p > y_p)
1113             .map(|(_, x)| x)
1114     }
1115
1116     /// Change the direction of the iterator
1117     ///
1118     /// The flipped iterator swaps the ends on an iterator that can already
1119     /// be iterated from the front and from the back.
1120     ///
1121     ///
1122     /// If the iterator also implements RandomAccessIterator, the flipped
1123     /// iterator is also random access, with the indices starting at the back
1124     /// of the original iterator.
1125     ///
1126     /// Note: Random access with flipped indices still only applies to the first
1127     /// `std::usize::MAX` elements of the original iterator.
1128     #[inline]
1129     #[stable(feature = "rust1", since = "1.0.0")]
1130     fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1131         Rev{iter: self}
1132     }
1133
1134     /// Converts an iterator of pairs into a pair of containers.
1135     ///
1136     /// Loops through the entire iterator, collecting the first component of
1137     /// each item into one new container, and the second component into another.
1138     ///
1139     /// # Examples
1140     ///
1141     /// ```
1142     /// let a = [(1, 2), (3, 4)];
1143     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1144     /// assert_eq!(left, [1, 3]);
1145     /// assert_eq!(right, [2, 4]);
1146     /// ```
1147     #[stable(feature = "rust1", since = "1.0.0")]
1148     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1149         FromA: Default + Extend<A>,
1150         FromB: Default + Extend<B>,
1151         Self: Sized + Iterator<Item=(A, B)>,
1152     {
1153         struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
1154         impl<A> Iterator for SizeHint<A> {
1155             type Item = A;
1156
1157             fn next(&mut self) -> Option<A> { None }
1158             fn size_hint(&self) -> (usize, Option<usize>) {
1159                 (self.0, self.1)
1160             }
1161         }
1162
1163         let (lo, hi) = self.size_hint();
1164         let mut ts: FromA = Default::default();
1165         let mut us: FromB = Default::default();
1166
1167         ts.extend(SizeHint(lo, hi, marker::PhantomData));
1168         us.extend(SizeHint(lo, hi, marker::PhantomData));
1169
1170         for (t, u) in self {
1171             ts.extend(Some(t));
1172             us.extend(Some(u));
1173         }
1174
1175         (ts, us)
1176     }
1177
1178     /// Creates an iterator that clones the elements it yields.
1179     ///
1180     /// This is useful for converting an `Iterator<&T>` to an`Iterator<T>`,
1181     /// so it's a more convenient form of `map(|&x| x)`.
1182     ///
1183     /// # Examples
1184     ///
1185     /// ```
1186     /// let a = [0, 1, 2];
1187     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
1188     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
1189     /// assert_eq!(v_cloned, v_map);
1190     /// ```
1191     #[stable(feature = "rust1", since = "1.0.0")]
1192     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
1193         where Self: Sized + Iterator<Item=&'a T>, T: Clone
1194     {
1195         Cloned { it: self }
1196     }
1197
1198     /// Repeats an iterator endlessly
1199     ///
1200     /// # Examples
1201     ///
1202     /// ```
1203     /// let a = [1, 2];
1204     /// let mut it = a.iter().cycle();
1205     /// assert_eq!(it.next(), Some(&1));
1206     /// assert_eq!(it.next(), Some(&2));
1207     /// assert_eq!(it.next(), Some(&1));
1208     /// ```
1209     #[stable(feature = "rust1", since = "1.0.0")]
1210     #[inline]
1211     fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
1212         Cycle{orig: self.clone(), iter: self}
1213     }
1214
1215     /// Iterates over the entire iterator, summing up all the elements
1216     ///
1217     /// # Examples
1218     ///
1219     /// ```
1220     /// #![feature(iter_arith)]
1221     ///
1222     /// let a = [1, 2, 3, 4, 5];
1223     /// let it = a.iter();
1224     /// assert_eq!(it.sum::<i32>(), 15);
1225     /// ```
1226     #[unstable(feature = "iter_arith", reason = "bounds recently changed",
1227                issue = "27739")]
1228     fn sum<S=<Self as Iterator>::Item>(self) -> S where
1229         S: Add<Self::Item, Output=S> + Zero,
1230         Self: Sized,
1231     {
1232         self.fold(Zero::zero(), |s, e| s + e)
1233     }
1234
1235     /// Iterates over the entire iterator, multiplying all the elements
1236     ///
1237     /// # Examples
1238     ///
1239     /// ```
1240     /// #![feature(iter_arith)]
1241     ///
1242     /// fn factorial(n: u32) -> u32 {
1243     ///     (1..).take_while(|&i| i <= n).product()
1244     /// }
1245     /// assert_eq!(factorial(0), 1);
1246     /// assert_eq!(factorial(1), 1);
1247     /// assert_eq!(factorial(5), 120);
1248     /// ```
1249     #[unstable(feature="iter_arith", reason = "bounds recently changed",
1250                issue = "27739")]
1251     fn product<P=<Self as Iterator>::Item>(self) -> P where
1252         P: Mul<Self::Item, Output=P> + One,
1253         Self: Sized,
1254     {
1255         self.fold(One::one(), |p, e| p * e)
1256     }
1257
1258     /// Lexicographically compares the elements of this `Iterator` with those
1259     /// of another.
1260     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1261     fn cmp<I>(mut self, other: I) -> Ordering where
1262         I: IntoIterator<Item = Self::Item>,
1263         Self::Item: Ord,
1264         Self: Sized,
1265     {
1266         let mut other = other.into_iter();
1267
1268         loop {
1269             match (self.next(), other.next()) {
1270                 (None, None) => return Ordering::Equal,
1271                 (None, _   ) => return Ordering::Less,
1272                 (_   , None) => return Ordering::Greater,
1273                 (Some(x), Some(y)) => match x.cmp(&y) {
1274                     Ordering::Equal => (),
1275                     non_eq => return non_eq,
1276                 },
1277             }
1278         }
1279     }
1280
1281     /// Lexicographically compares the elements of this `Iterator` with those
1282     /// of another.
1283     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1284     fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
1285         I: IntoIterator,
1286         Self::Item: PartialOrd<I::Item>,
1287         Self: Sized,
1288     {
1289         let mut other = other.into_iter();
1290
1291         loop {
1292             match (self.next(), other.next()) {
1293                 (None, None) => return Some(Ordering::Equal),
1294                 (None, _   ) => return Some(Ordering::Less),
1295                 (_   , None) => return Some(Ordering::Greater),
1296                 (Some(x), Some(y)) => match x.partial_cmp(&y) {
1297                     Some(Ordering::Equal) => (),
1298                     non_eq => return non_eq,
1299                 },
1300             }
1301         }
1302     }
1303
1304     /// Determines if the elements of this `Iterator` are equal to those of
1305     /// another.
1306     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1307     fn eq<I>(mut self, other: I) -> bool where
1308         I: IntoIterator,
1309         Self::Item: PartialEq<I::Item>,
1310         Self: Sized,
1311     {
1312         let mut other = other.into_iter();
1313
1314         loop {
1315             match (self.next(), other.next()) {
1316                 (None, None) => return true,
1317                 (None, _) | (_, None) => return false,
1318                 (Some(x), Some(y)) => if x != y { return false },
1319             }
1320         }
1321     }
1322
1323     /// Determines if the elements of this `Iterator` are unequal to those of
1324     /// another.
1325     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1326     fn ne<I>(mut self, other: I) -> bool where
1327         I: IntoIterator,
1328         Self::Item: PartialEq<I::Item>,
1329         Self: Sized,
1330     {
1331         let mut other = other.into_iter();
1332
1333         loop {
1334             match (self.next(), other.next()) {
1335                 (None, None) => return false,
1336                 (None, _) | (_, None) => return true,
1337                 (Some(x), Some(y)) => if x.ne(&y) { return true },
1338             }
1339         }
1340     }
1341
1342     /// Determines if the elements of this `Iterator` are lexicographically
1343     /// less than those of another.
1344     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1345     fn lt<I>(mut self, other: I) -> bool where
1346         I: IntoIterator,
1347         Self::Item: PartialOrd<I::Item>,
1348         Self: Sized,
1349     {
1350         let mut other = other.into_iter();
1351
1352         loop {
1353             match (self.next(), other.next()) {
1354                 (None, None) => return false,
1355                 (None, _   ) => return true,
1356                 (_   , None) => return false,
1357                 (Some(x), Some(y)) => {
1358                     match x.partial_cmp(&y) {
1359                         Some(Ordering::Less) => return true,
1360                         Some(Ordering::Equal) => {}
1361                         Some(Ordering::Greater) => return false,
1362                         None => return false,
1363                     }
1364                 },
1365             }
1366         }
1367     }
1368
1369     /// Determines if the elements of this `Iterator` are lexicographically
1370     /// less or equal to those of another.
1371     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1372     fn le<I>(mut self, other: I) -> bool where
1373         I: IntoIterator,
1374         Self::Item: PartialOrd<I::Item>,
1375         Self: Sized,
1376     {
1377         let mut other = other.into_iter();
1378
1379         loop {
1380             match (self.next(), other.next()) {
1381                 (None, None) => return true,
1382                 (None, _   ) => return true,
1383                 (_   , None) => return false,
1384                 (Some(x), Some(y)) => {
1385                     match x.partial_cmp(&y) {
1386                         Some(Ordering::Less) => return true,
1387                         Some(Ordering::Equal) => {}
1388                         Some(Ordering::Greater) => return false,
1389                         None => return false,
1390                     }
1391                 },
1392             }
1393         }
1394     }
1395
1396     /// Determines if the elements of this `Iterator` are lexicographically
1397     /// greater than those of another.
1398     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1399     fn gt<I>(mut self, other: I) -> bool where
1400         I: IntoIterator,
1401         Self::Item: PartialOrd<I::Item>,
1402         Self: Sized,
1403     {
1404         let mut other = other.into_iter();
1405
1406         loop {
1407             match (self.next(), other.next()) {
1408                 (None, None) => return false,
1409                 (None, _   ) => return false,
1410                 (_   , None) => return true,
1411                 (Some(x), Some(y)) => {
1412                     match x.partial_cmp(&y) {
1413                         Some(Ordering::Less) => return false,
1414                         Some(Ordering::Equal) => {}
1415                         Some(Ordering::Greater) => return true,
1416                         None => return false,
1417                     }
1418                 }
1419             }
1420         }
1421     }
1422
1423     /// Determines if the elements of this `Iterator` are lexicographically
1424     /// greater than or equal to those of another.
1425     #[unstable(feature = "iter_order", reason = "needs review and revision", issue = "27737")]
1426     fn ge<I>(mut self, other: I) -> bool where
1427         I: IntoIterator,
1428         Self::Item: PartialOrd<I::Item>,
1429         Self: Sized,
1430     {
1431         let mut other = other.into_iter();
1432
1433         loop {
1434             match (self.next(), other.next()) {
1435                 (None, None) => return true,
1436                 (None, _   ) => return false,
1437                 (_   , None) => return true,
1438                 (Some(x), Some(y)) => {
1439                     match x.partial_cmp(&y) {
1440                         Some(Ordering::Less) => return false,
1441                         Some(Ordering::Equal) => {}
1442                         Some(Ordering::Greater) => return true,
1443                         None => return false,
1444                     }
1445                 },
1446             }
1447         }
1448     }
1449 }
1450
1451 /// Select an element from an iterator based on the given projection
1452 /// and "comparison" function.
1453 ///
1454 /// This is an idiosyncratic helper to try to factor out the
1455 /// commonalities of {max,min}{,_by}. In particular, this avoids
1456 /// having to implement optimizations several times.
1457 #[inline]
1458 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
1459                                   mut f_proj: FProj,
1460                                   mut f_cmp: FCmp) -> Option<(B, I::Item)>
1461     where I: Iterator,
1462           FProj: FnMut(&I::Item) -> B,
1463           FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
1464 {
1465     // start with the first element as our selection. This avoids
1466     // having to use `Option`s inside the loop, translating to a
1467     // sizeable performance gain (6x in one case).
1468     it.next().map(|mut sel| {
1469         let mut sel_p = f_proj(&sel);
1470
1471         for x in it {
1472             let x_p = f_proj(&x);
1473             if f_cmp(&sel_p,  &sel, &x_p, &x) {
1474                 sel = x;
1475                 sel_p = x_p;
1476             }
1477         }
1478         (sel_p, sel)
1479     })
1480 }
1481
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
1484     type Item = I::Item;
1485     fn next(&mut self) -> Option<I::Item> { (**self).next() }
1486     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
1487 }
1488
1489 /// Conversion from an `Iterator`.
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
1492                           built from an iterator over elements of type `{A}`"]
1493 pub trait FromIterator<A> {
1494     /// Builds a container with elements from something iterable.
1495     ///
1496     /// # Examples
1497     ///
1498     /// ```
1499     /// use std::collections::HashSet;
1500     /// use std::iter::FromIterator;
1501     ///
1502     /// let colors_vec = vec!["red", "red", "yellow", "blue"];
1503     /// let colors_set = HashSet::<&str>::from_iter(colors_vec);
1504     /// assert_eq!(colors_set.len(), 3);
1505     /// ```
1506     ///
1507     /// `FromIterator` is more commonly used implicitly via the
1508     /// `Iterator::collect` method:
1509     ///
1510     /// ```
1511     /// use std::collections::HashSet;
1512     ///
1513     /// let colors_vec = vec!["red", "red", "yellow", "blue"];
1514     /// let colors_set = colors_vec.into_iter().collect::<HashSet<&str>>();
1515     /// assert_eq!(colors_set.len(), 3);
1516     /// ```
1517     #[stable(feature = "rust1", since = "1.0.0")]
1518     fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
1519 }
1520
1521 /// Conversion into an `Iterator`.
1522 ///
1523 /// By implementing `IntoIterator` for a type, you define how it will be
1524 /// converted to an iterator. This is common for types which describe a
1525 /// collection of some kind.
1526 ///
1527 /// One benefit of implementing `IntoIterator` is that your type will [work
1528 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
1529 ///
1530 /// # Examples
1531 ///
1532 /// Vectors implement `IntoIterator`:
1533 ///
1534 /// ```
1535 /// let v = vec![1, 2, 3];
1536 ///
1537 /// let mut iter = v.into_iter();
1538 ///
1539 /// let n = iter.next();
1540 /// assert_eq!(Some(1), n);
1541 ///
1542 /// let n = iter.next();
1543 /// assert_eq!(Some(2), n);
1544 ///
1545 /// let n = iter.next();
1546 /// assert_eq!(Some(3), n);
1547 ///
1548 /// let n = iter.next();
1549 /// assert_eq!(None, n);
1550 /// ```
1551 ///
1552 /// Implementing `IntoIterator` for your type:
1553 ///
1554 /// ```
1555 /// // A sample collection, that's just a wrapper over Vec<T>
1556 /// #[derive(Debug)]
1557 /// struct MyCollection(Vec<i32>);
1558 ///
1559 /// // Let's give it some methods so we can create one and add things
1560 /// // to it.
1561 /// impl MyCollection {
1562 ///     fn new() -> MyCollection {
1563 ///         MyCollection(Vec::new())
1564 ///     }
1565 ///
1566 ///     fn add(&mut self, elem: i32) {
1567 ///         self.0.push(elem);
1568 ///     }
1569 /// }
1570 ///
1571 /// // and we'll implement IntoIterator
1572 /// impl IntoIterator for MyCollection {
1573 ///     type Item = i32;
1574 ///     type IntoIter = ::std::vec::IntoIter<i32>;
1575 ///
1576 ///     fn into_iter(self) -> Self::IntoIter {
1577 ///         self.0.into_iter()
1578 ///     }
1579 /// }
1580 ///
1581 /// // Now we can make a new collection...
1582 /// let mut c = MyCollection::new();
1583 ///
1584 /// // ... add some stuff to it ...
1585 /// c.add(0);
1586 /// c.add(1);
1587 /// c.add(2);
1588 ///
1589 /// // ... and then turn it into an Iterator:
1590 /// for (i, n) in c.into_iter().enumerate() {
1591 ///     assert_eq!(i as i32, n);
1592 /// }
1593 /// ```
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 pub trait IntoIterator {
1596     /// The type of the elements being iterated over.
1597     #[stable(feature = "rust1", since = "1.0.0")]
1598     type Item;
1599
1600     /// Which kind of iterator are we turning this into?
1601     #[stable(feature = "rust1", since = "1.0.0")]
1602     type IntoIter: Iterator<Item=Self::Item>;
1603
1604     /// Consumes `Self` and returns an iterator over it.
1605     #[stable(feature = "rust1", since = "1.0.0")]
1606     fn into_iter(self) -> Self::IntoIter;
1607 }
1608
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 impl<I: Iterator> IntoIterator for I {
1611     type Item = I::Item;
1612     type IntoIter = I;
1613
1614     fn into_iter(self) -> I {
1615         self
1616     }
1617 }
1618
1619 /// Extend a collection with the contents of an iterator.
1620 ///
1621 /// Iterators produce a series of values, and collections can also be thought
1622 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
1623 /// to extend a collection by including the contents of that iterator.
1624 ///
1625 /// # Examples
1626 ///
1627 /// Basic usage:
1628 ///
1629 /// ```
1630 /// // You can extend a String with some chars:
1631 /// let mut message = String::from("The first three letters are: ");
1632 ///
1633 /// message.extend(&['a', 'b', 'c']);
1634 ///
1635 /// assert_eq!("abc", &message[29..32]);
1636 /// ```
1637 ///
1638 /// Implementing `Extend`:
1639 ///
1640 /// ```
1641 /// // A sample collection, that's just a wrapper over Vec<T>
1642 /// #[derive(Debug)]
1643 /// struct MyCollection(Vec<i32>);
1644 ///
1645 /// // Let's give it some methods so we can create one and add things
1646 /// // to it.
1647 /// impl MyCollection {
1648 ///     fn new() -> MyCollection {
1649 ///         MyCollection(Vec::new())
1650 ///     }
1651 ///
1652 ///     fn add(&mut self, elem: i32) {
1653 ///         self.0.push(elem);
1654 ///     }
1655 /// }
1656 ///
1657 /// // since MyCollection has a list of i32s, we implement Extend for i32
1658 /// impl Extend<i32> for MyCollection {
1659 ///
1660 ///     // This is a bit simpler with the concrete type signature: we can call
1661 ///     // extend on anything which can be turned into an Iterator which gives
1662 ///     // us i32s. Because we need i32s to put into MyCollection.
1663 ///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
1664 ///
1665 ///         // The implementation is very straightforward: loop through the
1666 ///         // iterator, and add() each element to ourselves.
1667 ///         for elem in iterable {
1668 ///             self.add(elem);
1669 ///         }
1670 ///     }
1671 /// }
1672 ///
1673 /// let mut c = MyCollection::new();
1674 ///
1675 /// c.add(5);
1676 /// c.add(6);
1677 /// c.add(7);
1678 ///
1679 /// // let's extend our collection with three more numbers
1680 /// c.extend(vec![1, 2, 3]);
1681 ///
1682 /// // we've added these elements onto the end
1683 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
1684 /// ```
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 pub trait Extend<A> {
1687     /// Extends a collection with the contents of an iterator.
1688     ///
1689     /// As this is the only method for this trait, the [trait-level] docs
1690     /// contain more details.
1691     ///
1692     /// [trait-level]: trait.Extend.html
1693     ///
1694     /// # Examples
1695     ///
1696     /// Basic usage:
1697     ///
1698     /// ```
1699     /// // You can extend a String with some chars:
1700     /// let mut message = String::from("The first three letters are: ");
1701     ///
1702     /// message.extend(['a', 'b', 'c'].iter());
1703     ///
1704     /// assert_eq!("abc", &message[29..32]);
1705     /// ```
1706     #[stable(feature = "rust1", since = "1.0.0")]
1707     fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
1708 }
1709
1710 /// An iterator able to yield elements from both ends.
1711 ///
1712 /// Something that implements `DoubleEndedIterator` has one extra capability
1713 /// over something that implements [`Iterator`]: the ability to also take
1714 /// `Item`s from the back, as well as the front.
1715 ///
1716 /// It is important to note that both back and forth work on the same range,
1717 /// and do not cross: iteration is over when they meet in the middle.
1718 ///
1719 /// [`Iterator`]: trait.Iterator.html
1720 /// # Examples
1721 ///
1722 /// Basic usage:
1723 ///
1724 /// ```
1725 /// let numbers = vec![1, 2, 3];
1726 ///
1727 /// let mut iter = numbers.iter();
1728 ///
1729 /// let n = iter.next();
1730 /// assert_eq!(Some(&1), n);
1731 ///
1732 /// let n = iter.next_back();
1733 /// assert_eq!(Some(&3), n);
1734 ///
1735 /// let n = iter.next_back();
1736 /// assert_eq!(Some(&2), n);
1737 ///
1738 /// let n = iter.next();
1739 /// assert_eq!(None, n);
1740 ///
1741 /// let n = iter.next_back();
1742 /// assert_eq!(None, n);
1743 /// ```
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub trait DoubleEndedIterator: Iterator {
1746     /// An iterator able to yield elements from both ends.
1747     ///
1748     /// As this is the only method for this trait, the [trait-level] docs
1749     /// contain more details.
1750     ///
1751     /// [trait-level]: trait.DoubleEndedIterator.html
1752     ///
1753     /// # Examples
1754     ///
1755     /// Basic usage:
1756     ///
1757     /// ```
1758     /// let numbers = vec![1, 2, 3];
1759     ///
1760     /// let mut iter = numbers.iter();
1761     ///
1762     /// let n = iter.next();
1763     /// assert_eq!(Some(&1), n);
1764     ///
1765     /// let n = iter.next_back();
1766     /// assert_eq!(Some(&3), n);
1767     ///
1768     /// let n = iter.next_back();
1769     /// assert_eq!(Some(&2), n);
1770     ///
1771     /// let n = iter.next();
1772     /// assert_eq!(None, n);
1773     ///
1774     /// let n = iter.next_back();
1775     /// assert_eq!(None, n);
1776     /// ```
1777     #[stable(feature = "rust1", since = "1.0.0")]
1778     fn next_back(&mut self) -> Option<Self::Item>;
1779 }
1780
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
1783     fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
1784 }
1785
1786 /// An iterator that knows its exact length.
1787 ///
1788 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
1789 /// If an iterator knows how many times it can iterate, providing access to
1790 /// that information can be useful. For example, if you want to iterate
1791 /// backwards, a good start is to know where the end is.
1792 ///
1793 /// When implementing an `ExactSizeIterator`, You must also implement
1794 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
1795 /// return the exact size of the iterator.
1796 ///
1797 /// [`Iterator`]: trait.Iterator.html
1798 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
1799 ///
1800 /// The [`len()`] method has a default implementation, so you usually shouldn't
1801 /// implement it. However, you may be able to provide a more performant
1802 /// implementation than the default, so overriding it in this case makes sense.
1803 ///
1804 /// [`len()`]: #method.len
1805 ///
1806 /// # Examples
1807 ///
1808 /// Basic usage:
1809 ///
1810 /// ```
1811 /// // a finite range knows exactly how many times it will iterate
1812 /// let five = (0..5);
1813 ///
1814 /// assert_eq!(5, five.len());
1815 /// ```
1816 ///
1817 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
1818 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
1819 ///
1820 /// [moddocs]: index.html
1821 ///
1822 /// ```
1823 /// # struct Counter {
1824 /// #     count: usize,
1825 /// # }
1826 /// # impl Counter {
1827 /// #     fn new() -> Counter {
1828 /// #         Counter { count: 0 }
1829 /// #     }
1830 /// # }
1831 /// # impl Iterator for Counter {
1832 /// #     type Item = usize;
1833 /// #     fn next(&mut self) -> Option<usize> {
1834 /// #         self.count += 1;
1835 /// #         if self.count < 6 {
1836 /// #             Some(self.count)
1837 /// #         } else {
1838 /// #             None
1839 /// #         }
1840 /// #     }
1841 /// # }
1842 /// impl ExactSizeIterator for Counter {
1843 ///     // We already have the number of iterations, so we can use it directly.
1844 ///     fn len(&self) -> usize {
1845 ///         self.count
1846 ///     }
1847 /// }
1848 ///
1849 /// // And now we can use it!
1850 ///
1851 /// let counter = Counter::new();
1852 ///
1853 /// assert_eq!(0, counter.len());
1854 /// ```
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 pub trait ExactSizeIterator: Iterator {
1857     #[inline]
1858     #[stable(feature = "rust1", since = "1.0.0")]
1859     /// Returns the exact number of times the iterator will iterate.
1860     ///
1861     /// This method has a default implementation, so you usually should not
1862     /// implement it directly. However, if you can provide a more efficient
1863     /// implementation, you can do so. See the [trait-level] docs for an
1864     /// example.
1865     ///
1866     /// [trait-level]: trait.ExactSizeIterator.html
1867     ///
1868     /// # Examples
1869     ///
1870     /// Basic usage:
1871     ///
1872     /// ```
1873     /// // a finite range knows exactly how many times it will iterate
1874     /// let five = (0..5);
1875     ///
1876     /// assert_eq!(5, five.len());
1877     /// ```
1878     fn len(&self) -> usize {
1879         let (lower, upper) = self.size_hint();
1880         // Note: This assertion is overly defensive, but it checks the invariant
1881         // guaranteed by the trait. If this trait were rust-internal,
1882         // we could use debug_assert!; assert_eq! will check all Rust user
1883         // implementations too.
1884         assert_eq!(upper, Some(lower));
1885         lower
1886     }
1887 }
1888
1889 #[stable(feature = "rust1", since = "1.0.0")]
1890 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
1891
1892 // All adaptors that preserve the size of the wrapped iterator are fine
1893 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
1898     F: FnMut(&I::Item),
1899 {}
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl<I> ExactSizeIterator for Rev<I>
1902     where I: ExactSizeIterator + DoubleEndedIterator {}
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
1905     F: FnMut(I::Item) -> B,
1906 {}
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 impl<A, B> ExactSizeIterator for Zip<A, B>
1909     where A: ExactSizeIterator, B: ExactSizeIterator {}
1910
1911 /// An double-ended iterator with the direction inverted.
1912 ///
1913 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
1914 /// documentation for more.
1915 ///
1916 /// [`rev()`]: trait.Iterator.html#method.rev
1917 /// [`Iterator`]: trait.Iterator.html
1918 #[derive(Clone)]
1919 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 pub struct Rev<T> {
1922     iter: T
1923 }
1924
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
1927     type Item = <I as Iterator>::Item;
1928
1929     #[inline]
1930     fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1931     #[inline]
1932     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1933 }
1934
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
1937     #[inline]
1938     fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1939 }
1940
1941 /// An iterator that clones the elements of an underlying iterator.
1942 ///
1943 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
1944 /// documentation for more.
1945 ///
1946 /// [`cloned()`]: trait.Iterator.html#method.cloned
1947 /// [`Iterator`]: trait.Iterator.html
1948 #[stable(feature = "iter_cloned", since = "1.1.0")]
1949 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1950 #[derive(Clone)]
1951 pub struct Cloned<I> {
1952     it: I,
1953 }
1954
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<'a, I, T: 'a> Iterator for Cloned<I>
1957     where I: Iterator<Item=&'a T>, T: Clone
1958 {
1959     type Item = T;
1960
1961     fn next(&mut self) -> Option<T> {
1962         self.it.next().cloned()
1963     }
1964
1965     fn size_hint(&self) -> (usize, Option<usize>) {
1966         self.it.size_hint()
1967     }
1968 }
1969
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
1972     where I: DoubleEndedIterator<Item=&'a T>, T: Clone
1973 {
1974     fn next_back(&mut self) -> Option<T> {
1975         self.it.next_back().cloned()
1976     }
1977 }
1978
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
1981     where I: ExactSizeIterator<Item=&'a T>, T: Clone
1982 {}
1983
1984 /// An iterator that repeats endlessly.
1985 ///
1986 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
1987 /// documentation for more.
1988 ///
1989 /// [`cycle()`]: trait.Iterator.html#method.cycle
1990 /// [`Iterator`]: trait.Iterator.html
1991 #[derive(Clone)]
1992 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 pub struct Cycle<I> {
1995     orig: I,
1996     iter: I,
1997 }
1998
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
2001     type Item = <I as Iterator>::Item;
2002
2003     #[inline]
2004     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2005         match self.iter.next() {
2006             None => { self.iter = self.orig.clone(); self.iter.next() }
2007             y => y
2008         }
2009     }
2010
2011     #[inline]
2012     fn size_hint(&self) -> (usize, Option<usize>) {
2013         // the cycle iterator is either empty or infinite
2014         match self.orig.size_hint() {
2015             sz @ (0, Some(0)) => sz,
2016             (0, _) => (0, None),
2017             _ => (usize::MAX, None)
2018         }
2019     }
2020 }
2021
2022 /// An iterator that strings two iterators together.
2023 ///
2024 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
2025 /// documentation for more.
2026 ///
2027 /// [`chain()`]: trait.Iterator.html#method.chain
2028 /// [`Iterator`]: trait.Iterator.html
2029 #[derive(Clone)]
2030 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 pub struct Chain<A, B> {
2033     a: A,
2034     b: B,
2035     state: ChainState,
2036 }
2037
2038 // The iterator protocol specifies that iteration ends with the return value
2039 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
2040 // further calls return. The chain adaptor must account for this since it uses
2041 // two subiterators.
2042 //
2043 //  It uses three states:
2044 //
2045 //  - Both: `a` and `b` are remaining
2046 //  - Front: `a` remaining
2047 //  - Back: `b` remaining
2048 //
2049 //  The fourth state (neither iterator is remaining) only occurs after Chain has
2050 //  returned None once, so we don't need to store this state.
2051 #[derive(Clone)]
2052 enum ChainState {
2053     // both front and back iterator are remaining
2054     Both,
2055     // only front is remaining
2056     Front,
2057     // only back is remaining
2058     Back,
2059 }
2060
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 impl<A, B> Iterator for Chain<A, B> where
2063     A: Iterator,
2064     B: Iterator<Item = A::Item>
2065 {
2066     type Item = A::Item;
2067
2068     #[inline]
2069     fn next(&mut self) -> Option<A::Item> {
2070         match self.state {
2071             ChainState::Both => match self.a.next() {
2072                 elt @ Some(..) => elt,
2073                 None => {
2074                     self.state = ChainState::Back;
2075                     self.b.next()
2076                 }
2077             },
2078             ChainState::Front => self.a.next(),
2079             ChainState::Back => self.b.next(),
2080         }
2081     }
2082
2083     #[inline]
2084     fn count(self) -> usize {
2085         match self.state {
2086             ChainState::Both => self.a.count() + self.b.count(),
2087             ChainState::Front => self.a.count(),
2088             ChainState::Back => self.b.count(),
2089         }
2090     }
2091
2092     #[inline]
2093     fn nth(&mut self, mut n: usize) -> Option<A::Item> {
2094         match self.state {
2095             ChainState::Both | ChainState::Front => {
2096                 for x in self.a.by_ref() {
2097                     if n == 0 {
2098                         return Some(x)
2099                     }
2100                     n -= 1;
2101                 }
2102                 if let ChainState::Both = self.state {
2103                     self.state = ChainState::Back;
2104                 }
2105             }
2106             ChainState::Back => {}
2107         }
2108         if let ChainState::Back = self.state {
2109             self.b.nth(n)
2110         } else {
2111             None
2112         }
2113     }
2114
2115     #[inline]
2116     fn last(self) -> Option<A::Item> {
2117         match self.state {
2118             ChainState::Both => {
2119                 // Must exhaust a before b.
2120                 let a_last = self.a.last();
2121                 let b_last = self.b.last();
2122                 b_last.or(a_last)
2123             },
2124             ChainState::Front => self.a.last(),
2125             ChainState::Back => self.b.last()
2126         }
2127     }
2128
2129     #[inline]
2130     fn size_hint(&self) -> (usize, Option<usize>) {
2131         let (a_lower, a_upper) = self.a.size_hint();
2132         let (b_lower, b_upper) = self.b.size_hint();
2133
2134         let lower = a_lower.saturating_add(b_lower);
2135
2136         let upper = match (a_upper, b_upper) {
2137             (Some(x), Some(y)) => x.checked_add(y),
2138             _ => None
2139         };
2140
2141         (lower, upper)
2142     }
2143 }
2144
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 impl<A, B> DoubleEndedIterator for Chain<A, B> where
2147     A: DoubleEndedIterator,
2148     B: DoubleEndedIterator<Item=A::Item>,
2149 {
2150     #[inline]
2151     fn next_back(&mut self) -> Option<A::Item> {
2152         match self.state {
2153             ChainState::Both => match self.b.next_back() {
2154                 elt @ Some(..) => elt,
2155                 None => {
2156                     self.state = ChainState::Front;
2157                     self.a.next_back()
2158                 }
2159             },
2160             ChainState::Front => self.a.next_back(),
2161             ChainState::Back => self.b.next_back(),
2162         }
2163     }
2164 }
2165
2166 /// An iterator that iterates two other iterators simultaneously.
2167 ///
2168 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
2169 /// documentation for more.
2170 ///
2171 /// [`zip()`]: trait.Iterator.html#method.zip
2172 /// [`Iterator`]: trait.Iterator.html
2173 #[derive(Clone)]
2174 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 pub struct Zip<A, B> {
2177     a: A,
2178     b: B
2179 }
2180
2181 #[stable(feature = "rust1", since = "1.0.0")]
2182 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
2183 {
2184     type Item = (A::Item, B::Item);
2185
2186     #[inline]
2187     fn next(&mut self) -> Option<(A::Item, B::Item)> {
2188         self.a.next().and_then(|x| {
2189             self.b.next().and_then(|y| {
2190                 Some((x, y))
2191             })
2192         })
2193     }
2194
2195     #[inline]
2196     fn size_hint(&self) -> (usize, Option<usize>) {
2197         let (a_lower, a_upper) = self.a.size_hint();
2198         let (b_lower, b_upper) = self.b.size_hint();
2199
2200         let lower = cmp::min(a_lower, b_lower);
2201
2202         let upper = match (a_upper, b_upper) {
2203             (Some(x), Some(y)) => Some(cmp::min(x,y)),
2204             (Some(x), None) => Some(x),
2205             (None, Some(y)) => Some(y),
2206             (None, None) => None
2207         };
2208
2209         (lower, upper)
2210     }
2211 }
2212
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 impl<A, B> DoubleEndedIterator for Zip<A, B> where
2215     A: DoubleEndedIterator + ExactSizeIterator,
2216     B: DoubleEndedIterator + ExactSizeIterator,
2217 {
2218     #[inline]
2219     fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
2220         let a_sz = self.a.len();
2221         let b_sz = self.b.len();
2222         if a_sz != b_sz {
2223             // Adjust a, b to equal length
2224             if a_sz > b_sz {
2225                 for _ in 0..a_sz - b_sz { self.a.next_back(); }
2226             } else {
2227                 for _ in 0..b_sz - a_sz { self.b.next_back(); }
2228             }
2229         }
2230         match (self.a.next_back(), self.b.next_back()) {
2231             (Some(x), Some(y)) => Some((x, y)),
2232             (None, None) => None,
2233             _ => unreachable!(),
2234         }
2235     }
2236 }
2237
2238 /// An iterator that maps the values of `iter` with `f`.
2239 ///
2240 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
2241 /// documentation for more.
2242 ///
2243 /// [`map()`]: trait.Iterator.html#method.map
2244 /// [`Iterator`]: trait.Iterator.html
2245 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 #[derive(Clone)]
2248 pub struct Map<I, F> {
2249     iter: I,
2250     f: F,
2251 }
2252
2253 #[stable(feature = "rust1", since = "1.0.0")]
2254 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
2255     type Item = B;
2256
2257     #[inline]
2258     fn next(&mut self) -> Option<B> {
2259         self.iter.next().map(&mut self.f)
2260     }
2261
2262     #[inline]
2263     fn size_hint(&self) -> (usize, Option<usize>) {
2264         self.iter.size_hint()
2265     }
2266 }
2267
2268 #[stable(feature = "rust1", since = "1.0.0")]
2269 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
2270     F: FnMut(I::Item) -> B,
2271 {
2272     #[inline]
2273     fn next_back(&mut self) -> Option<B> {
2274         self.iter.next_back().map(&mut self.f)
2275     }
2276 }
2277
2278 /// An iterator that filters the elements of `iter` with `predicate`.
2279 ///
2280 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
2281 /// documentation for more.
2282 ///
2283 /// [`filter()`]: trait.Iterator.html#method.filter
2284 /// [`Iterator`]: trait.Iterator.html
2285 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2286 #[stable(feature = "rust1", since = "1.0.0")]
2287 #[derive(Clone)]
2288 pub struct Filter<I, P> {
2289     iter: I,
2290     predicate: P,
2291 }
2292
2293 #[stable(feature = "rust1", since = "1.0.0")]
2294 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
2295     type Item = I::Item;
2296
2297     #[inline]
2298     fn next(&mut self) -> Option<I::Item> {
2299         for x in self.iter.by_ref() {
2300             if (self.predicate)(&x) {
2301                 return Some(x);
2302             }
2303         }
2304         None
2305     }
2306
2307     #[inline]
2308     fn size_hint(&self) -> (usize, Option<usize>) {
2309         let (_, upper) = self.iter.size_hint();
2310         (0, upper) // can't know a lower bound, due to the predicate
2311     }
2312 }
2313
2314 #[stable(feature = "rust1", since = "1.0.0")]
2315 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
2316     where P: FnMut(&I::Item) -> bool,
2317 {
2318     #[inline]
2319     fn next_back(&mut self) -> Option<I::Item> {
2320         for x in self.iter.by_ref().rev() {
2321             if (self.predicate)(&x) {
2322                 return Some(x);
2323             }
2324         }
2325         None
2326     }
2327 }
2328
2329 /// An iterator that uses `f` to both filter and map elements from `iter`.
2330 ///
2331 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
2332 /// documentation for more.
2333 ///
2334 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
2335 /// [`Iterator`]: trait.Iterator.html
2336 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2337 #[stable(feature = "rust1", since = "1.0.0")]
2338 #[derive(Clone)]
2339 pub struct FilterMap<I, F> {
2340     iter: I,
2341     f: F,
2342 }
2343
2344 #[stable(feature = "rust1", since = "1.0.0")]
2345 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
2346     where F: FnMut(I::Item) -> Option<B>,
2347 {
2348     type Item = B;
2349
2350     #[inline]
2351     fn next(&mut self) -> Option<B> {
2352         for x in self.iter.by_ref() {
2353             if let Some(y) = (self.f)(x) {
2354                 return Some(y);
2355             }
2356         }
2357         None
2358     }
2359
2360     #[inline]
2361     fn size_hint(&self) -> (usize, Option<usize>) {
2362         let (_, upper) = self.iter.size_hint();
2363         (0, upper) // can't know a lower bound, due to the predicate
2364     }
2365 }
2366
2367 #[stable(feature = "rust1", since = "1.0.0")]
2368 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
2369     where F: FnMut(I::Item) -> Option<B>,
2370 {
2371     #[inline]
2372     fn next_back(&mut self) -> Option<B> {
2373         for x in self.iter.by_ref().rev() {
2374             if let Some(y) = (self.f)(x) {
2375                 return Some(y);
2376             }
2377         }
2378         None
2379     }
2380 }
2381
2382 /// An iterator that yields the current count and the element during iteration.
2383 ///
2384 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
2385 /// documentation for more.
2386 ///
2387 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
2388 /// [`Iterator`]: trait.Iterator.html
2389 #[derive(Clone)]
2390 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 pub struct Enumerate<I> {
2393     iter: I,
2394     count: usize,
2395 }
2396
2397 #[stable(feature = "rust1", since = "1.0.0")]
2398 impl<I> Iterator for Enumerate<I> where I: Iterator {
2399     type Item = (usize, <I as Iterator>::Item);
2400
2401     /// # Overflow Behavior
2402     ///
2403     /// The method does no guarding against overflows, so enumerating more than
2404     /// `usize::MAX` elements either produces the wrong result or panics. If
2405     /// debug assertions are enabled, a panic is guaranteed.
2406     ///
2407     /// # Panics
2408     ///
2409     /// Might panic if the index of the element overflows a `usize`.
2410     #[inline]
2411     fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
2412         self.iter.next().map(|a| {
2413             let ret = (self.count, a);
2414             // Possible undefined overflow.
2415             self.count += 1;
2416             ret
2417         })
2418     }
2419
2420     #[inline]
2421     fn size_hint(&self) -> (usize, Option<usize>) {
2422         self.iter.size_hint()
2423     }
2424
2425     #[inline]
2426     fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
2427         self.iter.nth(n).map(|a| {
2428             let i = self.count + n;
2429             self.count = i + 1;
2430             (i, a)
2431         })
2432     }
2433
2434     #[inline]
2435     fn count(self) -> usize {
2436         self.iter.count()
2437     }
2438 }
2439
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 impl<I> DoubleEndedIterator for Enumerate<I> where
2442     I: ExactSizeIterator + DoubleEndedIterator
2443 {
2444     #[inline]
2445     fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
2446         self.iter.next_back().map(|a| {
2447             let len = self.iter.len();
2448             // Can safely add, `ExactSizeIterator` promises that the number of
2449             // elements fits into a `usize`.
2450             (self.count + len, a)
2451         })
2452     }
2453 }
2454
2455 /// An iterator with a `peek()` that returns an optional reference to the next
2456 /// element.
2457 ///
2458 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
2459 /// documentation for more.
2460 ///
2461 /// [`peekable()`]: trait.Iterator.html#method.peekable
2462 /// [`Iterator`]: trait.Iterator.html
2463 #[derive(Clone)]
2464 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 pub struct Peekable<I: Iterator> {
2467     iter: I,
2468     peeked: Option<I::Item>,
2469 }
2470
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 impl<I: Iterator> Iterator for Peekable<I> {
2473     type Item = I::Item;
2474
2475     #[inline]
2476     fn next(&mut self) -> Option<I::Item> {
2477         match self.peeked {
2478             Some(_) => self.peeked.take(),
2479             None => self.iter.next(),
2480         }
2481     }
2482
2483     #[inline]
2484     fn count(self) -> usize {
2485         (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
2486     }
2487
2488     #[inline]
2489     fn nth(&mut self, n: usize) -> Option<I::Item> {
2490         match self.peeked {
2491             Some(_) if n == 0 => self.peeked.take(),
2492             Some(_) => {
2493                 self.peeked = None;
2494                 self.iter.nth(n-1)
2495             },
2496             None => self.iter.nth(n)
2497         }
2498     }
2499
2500     #[inline]
2501     fn last(self) -> Option<I::Item> {
2502         self.iter.last().or(self.peeked)
2503     }
2504
2505     #[inline]
2506     fn size_hint(&self) -> (usize, Option<usize>) {
2507         let (lo, hi) = self.iter.size_hint();
2508         if self.peeked.is_some() {
2509             let lo = lo.saturating_add(1);
2510             let hi = hi.and_then(|x| x.checked_add(1));
2511             (lo, hi)
2512         } else {
2513             (lo, hi)
2514         }
2515     }
2516 }
2517
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
2520
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl<I: Iterator> Peekable<I> {
2523     /// Returns a reference to the next element of the iterator with out
2524     /// advancing it, or None if the iterator is exhausted.
2525     #[inline]
2526     #[stable(feature = "rust1", since = "1.0.0")]
2527     pub fn peek(&mut self) -> Option<&I::Item> {
2528         if self.peeked.is_none() {
2529             self.peeked = self.iter.next();
2530         }
2531         match self.peeked {
2532             Some(ref value) => Some(value),
2533             None => None,
2534         }
2535     }
2536
2537     /// Checks whether peekable iterator is empty or not.
2538     #[inline]
2539     pub fn is_empty(&mut self) -> bool {
2540         self.peek().is_none()
2541     }
2542 }
2543
2544 /// An iterator that rejects elements while `predicate` is true.
2545 ///
2546 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
2547 /// documentation for more.
2548 ///
2549 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
2550 /// [`Iterator`]: trait.Iterator.html
2551 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2552 #[stable(feature = "rust1", since = "1.0.0")]
2553 #[derive(Clone)]
2554 pub struct SkipWhile<I, P> {
2555     iter: I,
2556     flag: bool,
2557     predicate: P,
2558 }
2559
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
2562     where P: FnMut(&I::Item) -> bool
2563 {
2564     type Item = I::Item;
2565
2566     #[inline]
2567     fn next(&mut self) -> Option<I::Item> {
2568         for x in self.iter.by_ref() {
2569             if self.flag || !(self.predicate)(&x) {
2570                 self.flag = true;
2571                 return Some(x);
2572             }
2573         }
2574         None
2575     }
2576
2577     #[inline]
2578     fn size_hint(&self) -> (usize, Option<usize>) {
2579         let (_, upper) = self.iter.size_hint();
2580         (0, upper) // can't know a lower bound, due to the predicate
2581     }
2582 }
2583
2584 /// An iterator that only accepts elements while `predicate` is true.
2585 ///
2586 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
2587 /// documentation for more.
2588 ///
2589 /// [`take_while()`]: trait.Iterator.html#method.take_while
2590 /// [`Iterator`]: trait.Iterator.html
2591 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2592 #[stable(feature = "rust1", since = "1.0.0")]
2593 #[derive(Clone)]
2594 pub struct TakeWhile<I, P> {
2595     iter: I,
2596     flag: bool,
2597     predicate: P,
2598 }
2599
2600 #[stable(feature = "rust1", since = "1.0.0")]
2601 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
2602     where P: FnMut(&I::Item) -> bool
2603 {
2604     type Item = I::Item;
2605
2606     #[inline]
2607     fn next(&mut self) -> Option<I::Item> {
2608         if self.flag {
2609             None
2610         } else {
2611             self.iter.next().and_then(|x| {
2612                 if (self.predicate)(&x) {
2613                     Some(x)
2614                 } else {
2615                     self.flag = true;
2616                     None
2617                 }
2618             })
2619         }
2620     }
2621
2622     #[inline]
2623     fn size_hint(&self) -> (usize, Option<usize>) {
2624         let (_, upper) = self.iter.size_hint();
2625         (0, upper) // can't know a lower bound, due to the predicate
2626     }
2627 }
2628
2629 /// An iterator that skips over `n` elements of `iter`.
2630 ///
2631 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
2632 /// documentation for more.
2633 ///
2634 /// [`skip()`]: trait.Iterator.html#method.skip
2635 /// [`Iterator`]: trait.Iterator.html
2636 #[derive(Clone)]
2637 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 pub struct Skip<I> {
2640     iter: I,
2641     n: usize
2642 }
2643
2644 #[stable(feature = "rust1", since = "1.0.0")]
2645 impl<I> Iterator for Skip<I> where I: Iterator {
2646     type Item = <I as Iterator>::Item;
2647
2648     #[inline]
2649     fn next(&mut self) -> Option<I::Item> {
2650         if self.n == 0 {
2651             self.iter.next()
2652         } else {
2653             let old_n = self.n;
2654             self.n = 0;
2655             self.iter.nth(old_n)
2656         }
2657     }
2658
2659     #[inline]
2660     fn nth(&mut self, n: usize) -> Option<I::Item> {
2661         // Can't just add n + self.n due to overflow.
2662         if self.n == 0 {
2663             self.iter.nth(n)
2664         } else {
2665             let to_skip = self.n;
2666             self.n = 0;
2667             // nth(n) skips n+1
2668             if self.iter.nth(to_skip-1).is_none() {
2669                 return None;
2670             }
2671             self.iter.nth(n)
2672         }
2673     }
2674
2675     #[inline]
2676     fn count(self) -> usize {
2677         self.iter.count().saturating_sub(self.n)
2678     }
2679
2680     #[inline]
2681     fn last(mut self) -> Option<I::Item> {
2682         if self.n == 0 {
2683             self.iter.last()
2684         } else {
2685             let next = self.next();
2686             if next.is_some() {
2687                 // recurse. n should be 0.
2688                 self.last().or(next)
2689             } else {
2690                 None
2691             }
2692         }
2693     }
2694
2695     #[inline]
2696     fn size_hint(&self) -> (usize, Option<usize>) {
2697         let (lower, upper) = self.iter.size_hint();
2698
2699         let lower = lower.saturating_sub(self.n);
2700         let upper = upper.map(|x| x.saturating_sub(self.n));
2701
2702         (lower, upper)
2703     }
2704 }
2705
2706 #[stable(feature = "rust1", since = "1.0.0")]
2707 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2708
2709 /// An iterator that only iterates over the first `n` iterations of `iter`.
2710 ///
2711 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
2712 /// documentation for more.
2713 ///
2714 /// [`take()`]: trait.Iterator.html#method.take
2715 /// [`Iterator`]: trait.Iterator.html
2716 #[derive(Clone)]
2717 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 pub struct Take<I> {
2720     iter: I,
2721     n: usize
2722 }
2723
2724 #[stable(feature = "rust1", since = "1.0.0")]
2725 impl<I> Iterator for Take<I> where I: Iterator{
2726     type Item = <I as Iterator>::Item;
2727
2728     #[inline]
2729     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2730         if self.n != 0 {
2731             self.n -= 1;
2732             self.iter.next()
2733         } else {
2734             None
2735         }
2736     }
2737
2738     #[inline]
2739     fn nth(&mut self, n: usize) -> Option<I::Item> {
2740         if self.n > n {
2741             self.n -= n + 1;
2742             self.iter.nth(n)
2743         } else {
2744             if self.n > 0 {
2745                 self.iter.nth(self.n - 1);
2746                 self.n = 0;
2747             }
2748             None
2749         }
2750     }
2751
2752     #[inline]
2753     fn size_hint(&self) -> (usize, Option<usize>) {
2754         let (lower, upper) = self.iter.size_hint();
2755
2756         let lower = cmp::min(lower, self.n);
2757
2758         let upper = match upper {
2759             Some(x) if x < self.n => Some(x),
2760             _ => Some(self.n)
2761         };
2762
2763         (lower, upper)
2764     }
2765 }
2766
2767 #[stable(feature = "rust1", since = "1.0.0")]
2768 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2769
2770
2771 /// An iterator to maintain state while iterating another iterator.
2772 ///
2773 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
2774 /// documentation for more.
2775 ///
2776 /// [`scan()`]: trait.Iterator.html#method.scan
2777 /// [`Iterator`]: trait.Iterator.html
2778 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2779 #[stable(feature = "rust1", since = "1.0.0")]
2780 #[derive(Clone)]
2781 pub struct Scan<I, St, F> {
2782     iter: I,
2783     f: F,
2784     state: St,
2785 }
2786
2787 #[stable(feature = "rust1", since = "1.0.0")]
2788 impl<B, I, St, F> Iterator for Scan<I, St, F> where
2789     I: Iterator,
2790     F: FnMut(&mut St, I::Item) -> Option<B>,
2791 {
2792     type Item = B;
2793
2794     #[inline]
2795     fn next(&mut self) -> Option<B> {
2796         self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2797     }
2798
2799     #[inline]
2800     fn size_hint(&self) -> (usize, Option<usize>) {
2801         let (_, upper) = self.iter.size_hint();
2802         (0, upper) // can't know a lower bound, due to the scan function
2803     }
2804 }
2805
2806 /// An iterator that maps each element to an iterator, and yields the elements
2807 /// of the produced iterators.
2808 ///
2809 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
2810 /// documentation for more.
2811 ///
2812 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
2813 /// [`Iterator`]: trait.Iterator.html
2814 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2815 #[stable(feature = "rust1", since = "1.0.0")]
2816 #[derive(Clone)]
2817 pub struct FlatMap<I, U: IntoIterator, F> {
2818     iter: I,
2819     f: F,
2820     frontiter: Option<U::IntoIter>,
2821     backiter: Option<U::IntoIter>,
2822 }
2823
2824 #[stable(feature = "rust1", since = "1.0.0")]
2825 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
2826     where F: FnMut(I::Item) -> U,
2827 {
2828     type Item = U::Item;
2829
2830     #[inline]
2831     fn next(&mut self) -> Option<U::Item> {
2832         loop {
2833             if let Some(ref mut inner) = self.frontiter {
2834                 if let Some(x) = inner.by_ref().next() {
2835                     return Some(x)
2836                 }
2837             }
2838             match self.iter.next().map(&mut self.f) {
2839                 None => return self.backiter.as_mut().and_then(|it| it.next()),
2840                 next => self.frontiter = next.map(IntoIterator::into_iter),
2841             }
2842         }
2843     }
2844
2845     #[inline]
2846     fn size_hint(&self) -> (usize, Option<usize>) {
2847         let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2848         let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2849         let lo = flo.saturating_add(blo);
2850         match (self.iter.size_hint(), fhi, bhi) {
2851             ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2852             _ => (lo, None)
2853         }
2854     }
2855 }
2856
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
2859     F: FnMut(I::Item) -> U,
2860     U: IntoIterator,
2861     U::IntoIter: DoubleEndedIterator
2862 {
2863     #[inline]
2864     fn next_back(&mut self) -> Option<U::Item> {
2865         loop {
2866             if let Some(ref mut inner) = self.backiter {
2867                 if let Some(y) = inner.next_back() {
2868                     return Some(y)
2869                 }
2870             }
2871             match self.iter.next_back().map(&mut self.f) {
2872                 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2873                 next => self.backiter = next.map(IntoIterator::into_iter),
2874             }
2875         }
2876     }
2877 }
2878
2879 /// An iterator that yields `None` forever after the underlying iterator
2880 /// yields `None` once.
2881 ///
2882 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
2883 /// documentation for more.
2884 ///
2885 /// [`fuse()`]: trait.Iterator.html#method.fuse
2886 /// [`Iterator`]: trait.Iterator.html
2887 #[derive(Clone)]
2888 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2889 #[stable(feature = "rust1", since = "1.0.0")]
2890 pub struct Fuse<I> {
2891     iter: I,
2892     done: bool
2893 }
2894
2895 #[stable(feature = "rust1", since = "1.0.0")]
2896 impl<I> Iterator for Fuse<I> where I: Iterator {
2897     type Item = <I as Iterator>::Item;
2898
2899     #[inline]
2900     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2901         if self.done {
2902             None
2903         } else {
2904             let next = self.iter.next();
2905             self.done = next.is_none();
2906             next
2907         }
2908     }
2909
2910     #[inline]
2911     fn nth(&mut self, n: usize) -> Option<I::Item> {
2912         if self.done {
2913             None
2914         } else {
2915             let nth = self.iter.nth(n);
2916             self.done = nth.is_none();
2917             nth
2918         }
2919     }
2920
2921     #[inline]
2922     fn last(self) -> Option<I::Item> {
2923         if self.done {
2924             None
2925         } else {
2926             self.iter.last()
2927         }
2928     }
2929
2930     #[inline]
2931     fn count(self) -> usize {
2932         if self.done {
2933             0
2934         } else {
2935             self.iter.count()
2936         }
2937     }
2938
2939     #[inline]
2940     fn size_hint(&self) -> (usize, Option<usize>) {
2941         if self.done {
2942             (0, Some(0))
2943         } else {
2944             self.iter.size_hint()
2945         }
2946     }
2947 }
2948
2949 #[stable(feature = "rust1", since = "1.0.0")]
2950 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2951     #[inline]
2952     fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2953         if self.done {
2954             None
2955         } else {
2956             let next = self.iter.next_back();
2957             self.done = next.is_none();
2958             next
2959         }
2960     }
2961 }
2962
2963 #[stable(feature = "rust1", since = "1.0.0")]
2964 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
2965
2966 /// An iterator that calls a function with a reference to each element before
2967 /// yielding it.
2968 ///
2969 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
2970 /// documentation for more.
2971 ///
2972 /// [`inspect()`]: trait.Iterator.html#method.inspect
2973 /// [`Iterator`]: trait.Iterator.html
2974 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2975 #[stable(feature = "rust1", since = "1.0.0")]
2976 #[derive(Clone)]
2977 pub struct Inspect<I, F> {
2978     iter: I,
2979     f: F,
2980 }
2981
2982 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2983     #[inline]
2984     fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2985         if let Some(ref a) = elt {
2986             (self.f)(a);
2987         }
2988
2989         elt
2990     }
2991 }
2992
2993 #[stable(feature = "rust1", since = "1.0.0")]
2994 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2995     type Item = I::Item;
2996
2997     #[inline]
2998     fn next(&mut self) -> Option<I::Item> {
2999         let next = self.iter.next();
3000         self.do_inspect(next)
3001     }
3002
3003     #[inline]
3004     fn size_hint(&self) -> (usize, Option<usize>) {
3005         self.iter.size_hint()
3006     }
3007 }
3008
3009 #[stable(feature = "rust1", since = "1.0.0")]
3010 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
3011     where F: FnMut(&I::Item),
3012 {
3013     #[inline]
3014     fn next_back(&mut self) -> Option<I::Item> {
3015         let next = self.iter.next_back();
3016         self.do_inspect(next)
3017     }
3018 }
3019
3020 /// Objects that can be stepped over in both directions.
3021 ///
3022 /// The `steps_between` function provides a way to efficiently compare
3023 /// two `Step` objects.
3024 #[unstable(feature = "step_trait",
3025            reason = "likely to be replaced by finer-grained traits",
3026            issue = "27741")]
3027 pub trait Step: PartialOrd + Sized {
3028     /// Steps `self` if possible.
3029     fn step(&self, by: &Self) -> Option<Self>;
3030
3031     /// Returns the number of steps between two step objects. The count is
3032     /// inclusive of `start` and exclusive of `end`.
3033     ///
3034     /// Returns `None` if it is not possible to calculate `steps_between`
3035     /// without overflow.
3036     fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
3037 }
3038
3039 macro_rules! step_impl_unsigned {
3040     ($($t:ty)*) => ($(
3041         impl Step for $t {
3042             #[inline]
3043             fn step(&self, by: &$t) -> Option<$t> {
3044                 (*self).checked_add(*by)
3045             }
3046             #[inline]
3047             #[allow(trivial_numeric_casts)]
3048             fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
3049                 if *by == 0 { return None; }
3050                 if *start < *end {
3051                     // Note: We assume $t <= usize here
3052                     let diff = (*end - *start) as usize;
3053                     let by = *by as usize;
3054                     if diff % by > 0 {
3055                         Some(diff / by + 1)
3056                     } else {
3057                         Some(diff / by)
3058                     }
3059                 } else {
3060                     Some(0)
3061                 }
3062             }
3063         }
3064     )*)
3065 }
3066 macro_rules! step_impl_signed {
3067     ($($t:ty)*) => ($(
3068         impl Step for $t {
3069             #[inline]
3070             fn step(&self, by: &$t) -> Option<$t> {
3071                 (*self).checked_add(*by)
3072             }
3073             #[inline]
3074             #[allow(trivial_numeric_casts)]
3075             fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
3076                 if *by == 0 { return None; }
3077                 let diff: usize;
3078                 let by_u: usize;
3079                 if *by > 0 {
3080                     if *start >= *end {
3081                         return Some(0);
3082                     }
3083                     // Note: We assume $t <= isize here
3084                     // Use .wrapping_sub and cast to usize to compute the
3085                     // difference that may not fit inside the range of isize.
3086                     diff = (*end as isize).wrapping_sub(*start as isize) as usize;
3087                     by_u = *by as usize;
3088                 } else {
3089                     if *start <= *end {
3090                         return Some(0);
3091                     }
3092                     diff = (*start as isize).wrapping_sub(*end as isize) as usize;
3093                     by_u = (*by as isize).wrapping_mul(-1) as usize;
3094                 }
3095                 if diff % by_u > 0 {
3096                     Some(diff / by_u + 1)
3097                 } else {
3098                     Some(diff / by_u)
3099                 }
3100             }
3101         }
3102     )*)
3103 }
3104
3105 macro_rules! step_impl_no_between {
3106     ($($t:ty)*) => ($(
3107         impl Step for $t {
3108             #[inline]
3109             fn step(&self, by: &$t) -> Option<$t> {
3110                 (*self).checked_add(*by)
3111             }
3112             #[inline]
3113             fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
3114                 None
3115             }
3116         }
3117     )*)
3118 }
3119
3120 step_impl_unsigned!(usize u8 u16 u32);
3121 step_impl_signed!(isize i8 i16 i32);
3122 #[cfg(target_pointer_width = "64")]
3123 step_impl_unsigned!(u64);
3124 #[cfg(target_pointer_width = "64")]
3125 step_impl_signed!(i64);
3126 // If the target pointer width is not 64-bits, we
3127 // assume here that it is less than 64-bits.
3128 #[cfg(not(target_pointer_width = "64"))]
3129 step_impl_no_between!(u64 i64);
3130
3131 /// An adapter for stepping range iterators by a custom amount.
3132 ///
3133 /// The resulting iterator handles overflow by stopping. The `A`
3134 /// parameter is the type being iterated over, while `R` is the range
3135 /// type (usually one of `std::ops::{Range, RangeFrom}`.
3136 #[derive(Clone)]
3137 #[unstable(feature = "step_by", reason = "recent addition",
3138            issue = "27741")]
3139 pub struct StepBy<A, R> {
3140     step_by: A,
3141     range: R,
3142 }
3143
3144 impl<A: Step> RangeFrom<A> {
3145     /// Creates an iterator starting at the same point, but stepping by
3146     /// the given amount at each iteration.
3147     ///
3148     /// # Examples
3149     ///
3150     /// ```ignore
3151     /// for i in (0u8..).step_by(2) {
3152     ///     println!("{}", i);
3153     /// }
3154     /// ```
3155     ///
3156     /// This prints all even `u8` values.
3157     #[unstable(feature = "step_by", reason = "recent addition",
3158                issue = "27741")]
3159     pub fn step_by(self, by: A) -> StepBy<A, Self> {
3160         StepBy {
3161             step_by: by,
3162             range: self
3163         }
3164     }
3165 }
3166
3167 impl<A: Step> ops::Range<A> {
3168     /// Creates an iterator with the same range, but stepping by the
3169     /// given amount at each iteration.
3170     ///
3171     /// The resulting iterator handles overflow by stopping.
3172     ///
3173     /// # Examples
3174     ///
3175     /// ```
3176     /// #![feature(step_by)]
3177     ///
3178     /// for i in (0..10).step_by(2) {
3179     ///     println!("{}", i);
3180     /// }
3181     /// ```
3182     ///
3183     /// This prints:
3184     ///
3185     /// ```text
3186     /// 0
3187     /// 2
3188     /// 4
3189     /// 6
3190     /// 8
3191     /// ```
3192     #[unstable(feature = "step_by", reason = "recent addition",
3193                issue = "27741")]
3194     pub fn step_by(self, by: A) -> StepBy<A, Self> {
3195         StepBy {
3196             step_by: by,
3197             range: self
3198         }
3199     }
3200 }
3201
3202 #[stable(feature = "rust1", since = "1.0.0")]
3203 impl<A> Iterator for StepBy<A, RangeFrom<A>> where
3204     A: Clone,
3205     for<'a> &'a A: Add<&'a A, Output = A>
3206 {
3207     type Item = A;
3208
3209     #[inline]
3210     fn next(&mut self) -> Option<A> {
3211         let mut n = &self.range.start + &self.step_by;
3212         mem::swap(&mut n, &mut self.range.start);
3213         Some(n)
3214     }
3215
3216     #[inline]
3217     fn size_hint(&self) -> (usize, Option<usize>) {
3218         (usize::MAX, None) // Too bad we can't specify an infinite lower bound
3219     }
3220 }
3221
3222 /// An iterator over the range [start, stop]
3223 #[derive(Clone)]
3224 #[unstable(feature = "range_inclusive",
3225            reason = "likely to be replaced by range notation and adapters",
3226            issue = "27777")]
3227 pub struct RangeInclusive<A> {
3228     range: ops::Range<A>,
3229     done: bool,
3230 }
3231
3232 /// Returns an iterator over the range [start, stop].
3233 #[inline]
3234 #[unstable(feature = "range_inclusive",
3235            reason = "likely to be replaced by range notation and adapters",
3236            issue = "27777")]
3237 pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
3238     where A: Step + One + Clone
3239 {
3240     RangeInclusive {
3241         range: start..stop,
3242         done: false,
3243     }
3244 }
3245
3246 #[unstable(feature = "range_inclusive",
3247            reason = "likely to be replaced by range notation and adapters",
3248            issue = "27777")]
3249 impl<A> Iterator for RangeInclusive<A> where
3250     A: PartialEq + Step + One + Clone,
3251     for<'a> &'a A: Add<&'a A, Output = A>
3252 {
3253     type Item = A;
3254
3255     #[inline]
3256     fn next(&mut self) -> Option<A> {
3257         self.range.next().or_else(|| {
3258             if !self.done && self.range.start == self.range.end {
3259                 self.done = true;
3260                 Some(self.range.end.clone())
3261             } else {
3262                 None
3263             }
3264         })
3265     }
3266
3267     #[inline]
3268     fn size_hint(&self) -> (usize, Option<usize>) {
3269         let (lo, hi) = self.range.size_hint();
3270         if self.done {
3271             (lo, hi)
3272         } else {
3273             let lo = lo.saturating_add(1);
3274             let hi = hi.and_then(|x| x.checked_add(1));
3275             (lo, hi)
3276         }
3277     }
3278 }
3279
3280 #[unstable(feature = "range_inclusive",
3281            reason = "likely to be replaced by range notation and adapters",
3282            issue = "27777")]
3283 impl<A> DoubleEndedIterator for RangeInclusive<A> where
3284     A: PartialEq + Step + One + Clone,
3285     for<'a> &'a A: Add<&'a A, Output = A>,
3286     for<'a> &'a A: Sub<Output=A>
3287 {
3288     #[inline]
3289     fn next_back(&mut self) -> Option<A> {
3290         if self.range.end > self.range.start {
3291             let result = self.range.end.clone();
3292             self.range.end = &self.range.end - &A::one();
3293             Some(result)
3294         } else if !self.done && self.range.start == self.range.end {
3295             self.done = true;
3296             Some(self.range.end.clone())
3297         } else {
3298             None
3299         }
3300     }
3301 }
3302
3303 #[stable(feature = "rust1", since = "1.0.0")]
3304 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
3305     type Item = A;
3306
3307     #[inline]
3308     fn next(&mut self) -> Option<A> {
3309         let rev = self.step_by < A::zero();
3310         if (rev && self.range.start > self.range.end) ||
3311            (!rev && self.range.start < self.range.end)
3312         {
3313             match self.range.start.step(&self.step_by) {
3314                 Some(mut n) => {
3315                     mem::swap(&mut self.range.start, &mut n);
3316                     Some(n)
3317                 },
3318                 None => {
3319                     let mut n = self.range.end.clone();
3320                     mem::swap(&mut self.range.start, &mut n);
3321                     Some(n)
3322                 }
3323             }
3324         } else {
3325             None
3326         }
3327     }
3328
3329     #[inline]
3330     fn size_hint(&self) -> (usize, Option<usize>) {
3331         match Step::steps_between(&self.range.start,
3332                                   &self.range.end,
3333                                   &self.step_by) {
3334             Some(hint) => (hint, Some(hint)),
3335             None       => (0, None)
3336         }
3337     }
3338 }
3339
3340 macro_rules! range_exact_iter_impl {
3341     ($($t:ty)*) => ($(
3342         #[stable(feature = "rust1", since = "1.0.0")]
3343         impl ExactSizeIterator for ops::Range<$t> { }
3344     )*)
3345 }
3346
3347 #[stable(feature = "rust1", since = "1.0.0")]
3348 impl<A: Step + One> Iterator for ops::Range<A> where
3349     for<'a> &'a A: Add<&'a A, Output = A>
3350 {
3351     type Item = A;
3352
3353     #[inline]
3354     fn next(&mut self) -> Option<A> {
3355         if self.start < self.end {
3356             let mut n = &self.start + &A::one();
3357             mem::swap(&mut n, &mut self.start);
3358             Some(n)
3359         } else {
3360             None
3361         }
3362     }
3363
3364     #[inline]
3365     fn size_hint(&self) -> (usize, Option<usize>) {
3366         match Step::steps_between(&self.start, &self.end, &A::one()) {
3367             Some(hint) => (hint, Some(hint)),
3368             None => (0, None)
3369         }
3370     }
3371 }
3372
3373 // Ranges of u64 and i64 are excluded because they cannot guarantee having
3374 // a length <= usize::MAX, which is required by ExactSizeIterator.
3375 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
3376
3377 #[stable(feature = "rust1", since = "1.0.0")]
3378 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
3379     for<'a> &'a A: Add<&'a A, Output = A>,
3380     for<'a> &'a A: Sub<&'a A, Output = A>
3381 {
3382     #[inline]
3383     fn next_back(&mut self) -> Option<A> {
3384         if self.start < self.end {
3385             self.end = &self.end - &A::one();
3386             Some(self.end.clone())
3387         } else {
3388             None
3389         }
3390     }
3391 }
3392
3393 #[stable(feature = "rust1", since = "1.0.0")]
3394 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
3395     for<'a> &'a A: Add<&'a A, Output = A>
3396 {
3397     type Item = A;
3398
3399     #[inline]
3400     fn next(&mut self) -> Option<A> {
3401         let mut n = &self.start + &A::one();
3402         mem::swap(&mut n, &mut self.start);
3403         Some(n)
3404     }
3405 }
3406
3407 /// An iterator that repeats an element endlessly.
3408 ///
3409 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
3410 ///
3411 /// [`repeat()`]: fn.repeat.html
3412 #[derive(Clone)]
3413 #[stable(feature = "rust1", since = "1.0.0")]
3414 pub struct Repeat<A> {
3415     element: A
3416 }
3417
3418 #[stable(feature = "rust1", since = "1.0.0")]
3419 impl<A: Clone> Iterator for Repeat<A> {
3420     type Item = A;
3421
3422     #[inline]
3423     fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
3424     #[inline]
3425     fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
3426 }
3427
3428 #[stable(feature = "rust1", since = "1.0.0")]
3429 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
3430     #[inline]
3431     fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
3432 }
3433
3434 /// Creates a new iterator that endlessly repeats a single element.
3435 ///
3436 /// The `repeat()` function repeats a single value over and over and over and
3437 /// over and over and 🔁.
3438 ///
3439 /// Infinite iterators like `repeat()` are often used with adapters like
3440 /// [`take()`], in order to make them finite.
3441 ///
3442 /// [`take()`]: trait.Iterator.html#method.take
3443 ///
3444 /// # Examples
3445 ///
3446 /// Basic usage:
3447 ///
3448 /// ```
3449 /// use std::iter;
3450 ///
3451 /// // the number four 4ever:
3452 /// let mut fours = iter::repeat(4);
3453 ///
3454 /// assert_eq!(Some(4), fours.next());
3455 /// assert_eq!(Some(4), fours.next());
3456 /// assert_eq!(Some(4), fours.next());
3457 /// assert_eq!(Some(4), fours.next());
3458 /// assert_eq!(Some(4), fours.next());
3459 ///
3460 /// // yup, still four
3461 /// assert_eq!(Some(4), fours.next());
3462 /// ```
3463 ///
3464 /// Going finite with [`take()`]:
3465 ///
3466 /// ```
3467 /// use std::iter;
3468 ///
3469 /// // that last example was too many fours. Let's only have four fours.
3470 /// let mut four_fours = iter::repeat(4).take(4);
3471 ///
3472 /// assert_eq!(Some(4), four_fours.next());
3473 /// assert_eq!(Some(4), four_fours.next());
3474 /// assert_eq!(Some(4), four_fours.next());
3475 /// assert_eq!(Some(4), four_fours.next());
3476 ///
3477 /// // ... and now we're done
3478 /// assert_eq!(None, four_fours.next());
3479 /// ```
3480 #[inline]
3481 #[stable(feature = "rust1", since = "1.0.0")]
3482 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
3483     Repeat{element: elt}
3484 }
3485
3486 /// An iterator that yields nothing.
3487 ///
3488 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
3489 ///
3490 /// [`empty()`]: fn.empty.html
3491 #[stable(feature = "iter_empty", since = "1.2.0")]
3492 pub struct Empty<T>(marker::PhantomData<T>);
3493
3494 #[stable(feature = "iter_empty", since = "1.2.0")]
3495 impl<T> Iterator for Empty<T> {
3496     type Item = T;
3497
3498     fn next(&mut self) -> Option<T> {
3499         None
3500     }
3501
3502     fn size_hint(&self) -> (usize, Option<usize>){
3503         (0, Some(0))
3504     }
3505 }
3506
3507 #[stable(feature = "iter_empty", since = "1.2.0")]
3508 impl<T> DoubleEndedIterator for Empty<T> {
3509     fn next_back(&mut self) -> Option<T> {
3510         None
3511     }
3512 }
3513
3514 #[stable(feature = "iter_empty", since = "1.2.0")]
3515 impl<T> ExactSizeIterator for Empty<T> {
3516     fn len(&self) -> usize {
3517         0
3518     }
3519 }
3520
3521 // not #[derive] because that adds a Clone bound on T,
3522 // which isn't necessary.
3523 #[stable(feature = "iter_empty", since = "1.2.0")]
3524 impl<T> Clone for Empty<T> {
3525     fn clone(&self) -> Empty<T> {
3526         Empty(marker::PhantomData)
3527     }
3528 }
3529
3530 // not #[derive] because that adds a Default bound on T,
3531 // which isn't necessary.
3532 #[stable(feature = "iter_empty", since = "1.2.0")]
3533 impl<T> Default for Empty<T> {
3534     fn default() -> Empty<T> {
3535         Empty(marker::PhantomData)
3536     }
3537 }
3538
3539 /// Creates an iterator that yields nothing.
3540 ///
3541 /// # Examples
3542 ///
3543 /// Basic usage:
3544 ///
3545 /// ```
3546 /// use std::iter;
3547 ///
3548 /// // this could have been an iterator over i32, but alas, it's just not.
3549 /// let mut nope = iter::empty::<i32>();
3550 ///
3551 /// assert_eq!(None, nope.next());
3552 /// ```
3553 #[stable(feature = "iter_empty", since = "1.2.0")]
3554 pub fn empty<T>() -> Empty<T> {
3555     Empty(marker::PhantomData)
3556 }
3557
3558 /// An iterator that yields an element exactly once.
3559 ///
3560 /// This `struct` is created by the [`once()`] function. See its documentation for more.
3561 ///
3562 /// [`once()`]: fn.once.html
3563 #[derive(Clone)]
3564 #[stable(feature = "iter_once", since = "1.2.0")]
3565 pub struct Once<T> {
3566     inner: ::option::IntoIter<T>
3567 }
3568
3569 #[stable(feature = "iter_once", since = "1.2.0")]
3570 impl<T> Iterator for Once<T> {
3571     type Item = T;
3572
3573     fn next(&mut self) -> Option<T> {
3574         self.inner.next()
3575     }
3576
3577     fn size_hint(&self) -> (usize, Option<usize>) {
3578         self.inner.size_hint()
3579     }
3580 }
3581
3582 #[stable(feature = "iter_once", since = "1.2.0")]
3583 impl<T> DoubleEndedIterator for Once<T> {
3584     fn next_back(&mut self) -> Option<T> {
3585         self.inner.next_back()
3586     }
3587 }
3588
3589 #[stable(feature = "iter_once", since = "1.2.0")]
3590 impl<T> ExactSizeIterator for Once<T> {
3591     fn len(&self) -> usize {
3592         self.inner.len()
3593     }
3594 }
3595
3596 /// Creates an iterator that yields an element exactly once.
3597 ///
3598 /// This is commonly used to adapt a single value into a [`chain()`] of other
3599 /// kinds of iteration. Maybe you have an iterator that covers almost
3600 /// everything, but you need an extra special case. Maybe you have a function
3601 /// which works on iterators, but you only need to process one value.
3602 ///
3603 /// [`chain()`]: trait.Iterator.html#method.chain
3604 ///
3605 /// # Examples
3606 ///
3607 /// Basic usage:
3608 ///
3609 /// ```
3610 /// use std::iter;
3611 ///
3612 /// // one is the loneliest number
3613 /// let mut one = iter::once(1);
3614 ///
3615 /// assert_eq!(Some(1), one.next());
3616 ///
3617 /// // just one, that's all we get
3618 /// assert_eq!(None, one.next());
3619 /// ```
3620 ///
3621 /// Chaining together with another iterator. Let's say that we want to iterate
3622 /// over each file of the `.foo` directory, but also a configuration file,
3623 /// `.foorc`:
3624 ///
3625 /// ```no_run
3626 /// use std::iter;
3627 /// use std::fs;
3628 /// use std::path::PathBuf;
3629 ///
3630 /// let dirs = fs::read_dir(".foo").unwrap();
3631 ///
3632 /// // we need to convert from an iterator of DirEntry-s to an iterator of
3633 /// // PathBufs, so we use map
3634 /// let dirs = dirs.map(|file| file.unwrap().path());
3635 ///
3636 /// // now, our iterator just for our config file
3637 /// let config = iter::once(PathBuf::from(".foorc"));
3638 ///
3639 /// // chain the two iterators together into one big iterator
3640 /// let files = dirs.chain(config);
3641 ///
3642 /// // this will give us all of the files in .foo as well as .foorc
3643 /// for f in files {
3644 ///     println!("{:?}", f);
3645 /// }
3646 /// ```
3647 #[stable(feature = "iter_once", since = "1.2.0")]
3648 pub fn once<T>(value: T) -> Once<T> {
3649     Once { inner: Some(value).into_iter() }
3650 }
3651
3652 /// Functions for lexicographical ordering of sequences.
3653 ///
3654 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
3655 /// that the elements implement both `PartialEq` and `PartialOrd`.
3656 ///
3657 /// If two sequences are equal up until the point where one ends,
3658 /// the shorter sequence compares less.
3659 #[deprecated(since = "1.4.0", reason = "use the equivalent methods on `Iterator` instead")]
3660 #[unstable(feature = "iter_order", reason = "needs review and revision",
3661            issue = "27737")]
3662 pub mod order {
3663     use cmp;
3664     use cmp::{Eq, Ord, PartialOrd, PartialEq};
3665     use option::Option;
3666     use super::Iterator;
3667
3668     /// Compare `a` and `b` for equality using `Eq`
3669     pub fn equals<A, L, R>(a: L, b: R) -> bool where
3670         A: Eq,
3671         L: Iterator<Item=A>,
3672         R: Iterator<Item=A>,
3673     {
3674         a.eq(b)
3675     }
3676
3677     /// Order `a` and `b` lexicographically using `Ord`
3678     pub fn cmp<A, L, R>(a: L, b: R) -> cmp::Ordering where
3679         A: Ord,
3680         L: Iterator<Item=A>,
3681         R: Iterator<Item=A>,
3682     {
3683         a.cmp(b)
3684     }
3685
3686     /// Order `a` and `b` lexicographically using `PartialOrd`
3687     pub fn partial_cmp<L: Iterator, R: Iterator>(a: L, b: R) -> Option<cmp::Ordering> where
3688         L::Item: PartialOrd<R::Item>
3689     {
3690         a.partial_cmp(b)
3691     }
3692
3693     /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
3694     pub fn eq<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
3695         L::Item: PartialEq<R::Item>,
3696     {
3697         a.eq(b)
3698     }
3699
3700     /// Compares `a` and `b` for nonequality (Using partial equality, `PartialEq`)
3701     pub fn ne<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
3702         L::Item: PartialEq<R::Item>,
3703     {
3704         a.ne(b)
3705     }
3706
3707     /// Returns `a` < `b` lexicographically (Using partial order, `PartialOrd`)
3708     pub fn lt<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
3709         L::Item: PartialOrd<R::Item>,
3710     {
3711         a.lt(b)
3712     }
3713
3714     /// Returns `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
3715     pub fn le<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
3716         L::Item: PartialOrd<R::Item>,
3717     {
3718         a.le(b)
3719     }
3720
3721     /// Returns `a` > `b` lexicographically (Using partial order, `PartialOrd`)
3722     pub fn gt<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
3723         L::Item: PartialOrd<R::Item>,
3724     {
3725         a.gt(b)
3726     }
3727
3728     /// Returns `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
3729     pub fn ge<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
3730         L::Item: PartialOrd<R::Item>,
3731     {
3732         a.ge(b)
3733     }
3734 }