]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter.rs
Auto merge of #29409 - arielb1:recursive-arrays, r=eddyb
[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 iterators.
316 ///
317 /// This is the main iterator trait. For more about the concept of iterators
318 /// generally, please see the [module-level documentation]. In particular, you
319 /// may want to know how to [implement `Iterator`][impl].
320 ///
321 /// [module-level documentation]: index.html
322 /// [impl]: index.html#implementing-iterator
323 #[lang = "iterator"]
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
326                             `.iter()` or a similar method"]
327 pub trait Iterator {
328     /// The type of the elements being iterated over.
329     #[stable(feature = "rust1", since = "1.0.0")]
330     type Item;
331
332     /// Advances the iterator and returns the next value.
333     ///
334     /// Returns `None` when iteration is finished. Individual iterator
335     /// implementations may choose to resume iteration, and so calling `next()`
336     /// again may or may not eventually start returning `Some(Item)` again at some
337     /// point.
338     ///
339     /// # Examples
340     ///
341     /// Basic usage:
342     ///
343     /// ```
344     /// let a = [1, 2, 3];
345     ///
346     /// let mut iter = a.iter();
347     ///
348     /// // A call to next() returns the next value...
349     /// assert_eq!(Some(&1), iter.next());
350     /// assert_eq!(Some(&2), iter.next());
351     /// assert_eq!(Some(&3), iter.next());
352     ///
353     /// // ... and then None once it's over.
354     /// assert_eq!(None, iter.next());
355     ///
356     /// // More calls may or may not return None. Here, they always will.
357     /// assert_eq!(None, iter.next());
358     /// assert_eq!(None, iter.next());
359     /// ```
360     #[stable(feature = "rust1", since = "1.0.0")]
361     fn next(&mut self) -> Option<Self::Item>;
362
363     /// Returns the bounds on the remaining length of the iterator.
364     ///
365     /// Specifically, `size_hint()` returns a tuple where the first element
366     /// is the lower bound, and the second element is the upper bound.
367     ///
368     /// The second half of the tuple that is returned is an `Option<usize>`. A
369     /// `None` here means that either there is no known upper bound, or the
370     /// upper bound is larger than `usize`.
371     ///
372     /// # Examples
373     ///
374     /// Basic usage:
375     ///
376     /// ```
377     /// let a = [1, 2, 3];
378     /// let iter = a.iter();
379     ///
380     /// assert_eq!((3, Some(3)), iter.size_hint());
381     /// ```
382     ///
383     /// A more complex example:
384     ///
385     /// ```
386     /// // The even numbers from zero to ten.
387     /// let iter = (0..10).filter(|x| x % 2 == 0);
388     ///
389     /// // We might iterate from zero to ten times. Knowing that it's five
390     /// // exactly wouldn't be possible without executing filter().
391     /// assert_eq!((0, Some(10)), iter.size_hint());
392     ///
393     /// // Let's add one five more numbers with chain()
394     /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
395     ///
396     /// // now both bounds are increased by five
397     /// assert_eq!((5, Some(15)), iter.size_hint());
398     /// ```
399     ///
400     /// Returning `None` for an upper bound:
401     ///
402     /// ```
403     /// // an infinite iterator has no upper bound
404     /// let iter = (0..);
405     ///
406     /// assert_eq!((0, None), iter.size_hint());
407     /// ```
408     #[inline]
409     #[stable(feature = "rust1", since = "1.0.0")]
410     fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
411
412     /// Consumes the iterator, counting the number of iterations and returning it.
413     ///
414     /// This method will evaluate the iterator until its [`next()`] returns
415     /// `None`. Once `None` is encountered, `count()` returns the number of
416     /// times it called [`next()`].
417     ///
418     /// [`next()`]: #method.next
419     ///
420     /// # Overflow Behavior
421     ///
422     /// The method does no guarding against overflows, so counting elements of
423     /// an iterator with more than `usize::MAX` elements either produces the
424     /// wrong result or panics. If debug assertions are enabled, a panic is
425     /// guaranteed.
426     ///
427     /// # Panics
428     ///
429     /// This function might panic if the iterator has more than `usize::MAX`
430     /// elements.
431     ///
432     /// # Examples
433     ///
434     /// Basic usage:
435     ///
436     /// ```
437     /// let a = [1, 2, 3];
438     /// assert_eq!(a.iter().count(), 3);
439     ///
440     /// let a = [1, 2, 3, 4, 5];
441     /// assert_eq!(a.iter().count(), 5);
442     /// ```
443     #[inline]
444     #[stable(feature = "rust1", since = "1.0.0")]
445     fn count(self) -> usize where Self: Sized {
446         // Might overflow.
447         self.fold(0, |cnt, _| cnt + 1)
448     }
449
450     /// Consumes the iterator, returning the last element.
451     ///
452     /// This method will evaluate the iterator until it returns `None`. While
453     /// doing so, it keeps track of the current element. After `None` is
454     /// returned, `last()` will then return the last element it saw.
455     ///
456     /// # Examples
457     ///
458     /// Basic usage:
459     ///
460     /// ```
461     /// let a = [1, 2, 3];
462     /// assert_eq!(a.iter().last(), Some(&3));
463     ///
464     /// let a = [1, 2, 3, 4, 5];
465     /// assert_eq!(a.iter().last(), Some(&5));
466     /// ```
467     #[inline]
468     #[stable(feature = "rust1", since = "1.0.0")]
469     fn last(self) -> Option<Self::Item> where Self: Sized {
470         let mut last = None;
471         for x in self { last = Some(x); }
472         last
473     }
474
475     /// Consumes the `n` first elements of the iterator, then returns the
476     /// `next()` one.
477     ///
478     /// This method will evaluate the iterator `n` times, discarding those elements.
479     /// After it does so, it will call [`next()`] and return its value.
480     ///
481     /// [`next()`]: #method.next
482     ///
483     /// Like most indexing operations, the count starts from zero, so `nth(0)`
484     /// returns the first value, `nth(1)` the second, and so on.
485     ///
486     /// `nth()` will return `None` if `n` is larger than the length of the
487     /// iterator.
488     ///
489     /// # Examples
490     ///
491     /// Basic usage:
492     ///
493     /// ```
494     /// let a = [1, 2, 3];
495     /// assert_eq!(a.iter().nth(1), Some(&2));
496     /// ```
497     ///
498     /// Calling `nth()` multiple times doesn't rewind the iterator:
499     ///
500     /// ```
501     /// let a = [1, 2, 3];
502     ///
503     /// let mut iter = a.iter();
504     ///
505     /// assert_eq!(iter.nth(1), Some(&2));
506     /// assert_eq!(iter.nth(1), None);
507     /// ```
508     ///
509     /// Returning `None` if there are less than `n` elements:
510     ///
511     /// ```
512     /// let a = [1, 2, 3];
513     /// assert_eq!(a.iter().nth(10), None);
514     /// ```
515     #[inline]
516     #[stable(feature = "rust1", since = "1.0.0")]
517     fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
518         for x in self {
519             if n == 0 { return Some(x) }
520             n -= 1;
521         }
522         None
523     }
524
525     /// Takes two iterators and creates a new iterator over both in sequence.
526     ///
527     /// `chain()` will return a new iterator which will first iterate over
528     /// values from the first iterator and then over values from the second
529     /// iterator.
530     ///
531     /// In other words, it links two iterators together, in a chain. 🔗
532     ///
533     /// # Examples
534     ///
535     /// Basic usage:
536     ///
537     /// ```
538     /// let a1 = [1, 2, 3];
539     /// let a2 = [4, 5, 6];
540     ///
541     /// let mut iter = a1.iter().chain(a2.iter());
542     ///
543     /// assert_eq!(iter.next(), Some(&1));
544     /// assert_eq!(iter.next(), Some(&2));
545     /// assert_eq!(iter.next(), Some(&3));
546     /// assert_eq!(iter.next(), Some(&4));
547     /// assert_eq!(iter.next(), Some(&5));
548     /// assert_eq!(iter.next(), Some(&6));
549     /// assert_eq!(iter.next(), None);
550     /// ```
551     ///
552     /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
553     /// anything that can be converted into an [`Iterator`], not just an
554     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
555     /// [`IntoIterator`], and so can be passed to `chain()` directly:
556     ///
557     /// [`IntoIterator`]: trait.IntoIterator.html
558     /// [`Iterator`]: trait.Iterator.html
559     ///
560     /// ```
561     /// let s1 = &[1, 2, 3];
562     /// let s2 = &[4, 5, 6];
563     ///
564     /// let mut iter = s1.iter().chain(s2);
565     ///
566     /// assert_eq!(iter.next(), Some(&1));
567     /// assert_eq!(iter.next(), Some(&2));
568     /// assert_eq!(iter.next(), Some(&3));
569     /// assert_eq!(iter.next(), Some(&4));
570     /// assert_eq!(iter.next(), Some(&5));
571     /// assert_eq!(iter.next(), Some(&6));
572     /// assert_eq!(iter.next(), None);
573     /// ```
574     #[inline]
575     #[stable(feature = "rust1", since = "1.0.0")]
576     fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
577         Self: Sized, U: IntoIterator<Item=Self::Item>,
578     {
579         Chain{a: self, b: other.into_iter(), state: ChainState::Both}
580     }
581
582     /// 'Zips up' two iterators into a single iterator of pairs.
583     ///
584     /// `zip()` returns a new iterator that will iterate over two other
585     /// iterators, returning a tuple where the first element comes from the
586     /// first iterator, and the second element comes from the second iterator.
587     ///
588     /// In other words, it zips two iterators together, into a single one. 🤐
589     ///
590     /// When either iterator returns `None`, all further calls to `next()`
591     /// will return `None`.
592     ///
593     /// # Examples
594     ///
595     /// Basic usage:
596     ///
597     /// ```
598     /// let a1 = [1, 2, 3];
599     /// let a2 = [4, 5, 6];
600     ///
601     /// let mut iter = a1.iter().zip(a2.iter());
602     ///
603     /// assert_eq!(iter.next(), Some((&1, &4)));
604     /// assert_eq!(iter.next(), Some((&2, &5)));
605     /// assert_eq!(iter.next(), Some((&3, &6)));
606     /// assert_eq!(iter.next(), None);
607     /// ```
608     ///
609     /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
610     /// anything that can be converted into an [`Iterator`], not just an
611     /// [`Iterator`] itself. For example, slices (`&[T]`) implement
612     /// [`IntoIterator`], and so can be passed to `zip()` directly:
613     ///
614     /// [`IntoIterator`]: trait.IntoIterator.html
615     /// [`Iterator`]: trait.Iterator.html
616     ///
617     /// ```
618     /// let s1 = &[1, 2, 3];
619     /// let s2 = &[4, 5, 6];
620     ///
621     /// let mut iter = s1.iter().zip(s2);
622     ///
623     /// assert_eq!(iter.next(), Some((&1, &4)));
624     /// assert_eq!(iter.next(), Some((&2, &5)));
625     /// assert_eq!(iter.next(), Some((&3, &6)));
626     /// assert_eq!(iter.next(), None);
627     /// ```
628     ///
629     /// `zip()` is often used to zip an infinite iterator to a finite one.
630     /// This works because the finite iterator will eventually return `None`,
631     /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
632     ///
633     /// ```
634     /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
635     ///
636     /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
637     ///
638     /// assert_eq!((0, 'f'), enumerate[0]);
639     /// assert_eq!((0, 'f'), zipper[0]);
640     ///
641     /// assert_eq!((1, 'o'), enumerate[1]);
642     /// assert_eq!((1, 'o'), zipper[1]);
643     ///
644     /// assert_eq!((2, 'o'), enumerate[2]);
645     /// assert_eq!((2, 'o'), zipper[2]);
646     /// ```
647     ///
648     /// [`enumerate()`]: trait.Iterator.html#method.enumerate
649     #[inline]
650     #[stable(feature = "rust1", since = "1.0.0")]
651     fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
652         Self: Sized, U: IntoIterator
653     {
654         Zip{a: self, b: other.into_iter()}
655     }
656
657     /// Takes a closure and creates an iterator which calls that closure on each
658     /// element.
659     ///
660     /// `map()` transforms one iterator into another, by means of its argument:
661     /// something that implements `FnMut`. It produces a new iterator which
662     /// calls this closure on each element of the original iterator.
663     ///
664     /// If you are good at thinking in types, you can think of `map()` like this:
665     /// If you have an iterator that gives you elements of some type `A`, and
666     /// you want an iterator of some other type `B`, you can use `map()`,
667     /// passing a closure that takes an `A` and returns a `B`.
668     ///
669     /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
670     /// lazy, it is best used when you're already working with other iterators.
671     /// If you're doing some sort of looping for a side effect, it's considered
672     /// more idiomatic to use [`for`] than `map()`.
673     ///
674     /// [`for`]: ../../book/loops.html#for
675     ///
676     /// # Examples
677     ///
678     /// Basic usage:
679     ///
680     /// ```
681     /// let a = [1, 2, 3];
682     ///
683     /// let mut iter = a.into_iter().map(|x| 2 * x);
684     ///
685     /// assert_eq!(iter.next(), Some(2));
686     /// assert_eq!(iter.next(), Some(4));
687     /// assert_eq!(iter.next(), Some(6));
688     /// assert_eq!(iter.next(), None);
689     /// ```
690     ///
691     /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
692     ///
693     /// ```
694     /// // don't do this:
695     /// (0..5).map(|x| println!("{}", x));
696     ///
697     /// // it won't even execute, as it is lazy. Rust will warn you about this.
698     ///
699     /// // Instead, use for:
700     /// for x in 0..5 {
701     ///     println!("{}", x);
702     /// }
703     /// ```
704     #[inline]
705     #[stable(feature = "rust1", since = "1.0.0")]
706     fn map<B, F>(self, f: F) -> Map<Self, F> where
707         Self: Sized, F: FnMut(Self::Item) -> B,
708     {
709         Map{iter: self, f: f}
710     }
711
712     /// Creates an iterator which uses a closure to determine if an element
713     /// should be yielded.
714     ///
715     /// The closure must return `true` or `false`. `filter()` creates an
716     /// iterator which calls this closure on each element. If the closure
717     /// returns `true`, then the element is returned. If the closure returns
718     /// `false`, it will try again, and call the closure on the next element,
719     /// seeing if it passes the test.
720     ///
721     /// # Examples
722     ///
723     /// Basic usage:
724     ///
725     /// ```
726     /// let a = [0i32, 1, 2];
727     ///
728     /// let mut iter = a.into_iter().filter(|x| x.is_positive());
729     ///
730     /// assert_eq!(iter.next(), Some(&1));
731     /// assert_eq!(iter.next(), Some(&2));
732     /// assert_eq!(iter.next(), None);
733     /// ```
734     ///
735     /// Because the closure passed to `filter()` takes a reference, and many
736     /// iterators iterate over references, this leads to a possibly confusing
737     /// situation, where the type of the closure is a double reference:
738     ///
739     /// ```
740     /// let a = [0, 1, 2];
741     ///
742     /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
743     ///
744     /// assert_eq!(iter.next(), Some(&2));
745     /// assert_eq!(iter.next(), None);
746     /// ```
747     ///
748     /// It's common to instead use destructuring on the argument to strip away
749     /// one:
750     ///
751     /// ```
752     /// let a = [0, 1, 2];
753     ///
754     /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
755     ///
756     /// assert_eq!(iter.next(), Some(&2));
757     /// assert_eq!(iter.next(), None);
758     /// ```
759     ///
760     /// or both:
761     ///
762     /// ```
763     /// let a = [0, 1, 2];
764     ///
765     /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
766     ///
767     /// assert_eq!(iter.next(), Some(&2));
768     /// assert_eq!(iter.next(), None);
769     /// ```
770     ///
771     /// of these layers.
772     #[inline]
773     #[stable(feature = "rust1", since = "1.0.0")]
774     fn filter<P>(self, predicate: P) -> Filter<Self, P> where
775         Self: Sized, P: FnMut(&Self::Item) -> bool,
776     {
777         Filter{iter: self, predicate: predicate}
778     }
779
780     /// Creates an iterator that both filters and maps.
781     ///
782     /// The closure must return an [`Option<T>`]. `filter_map()` creates an
783     /// iterator which calls this closure on each element. If the closure
784     /// returns `Some(element)`, then that element is returned. If the
785     /// closure returns `None`, it will try again, and call the closure on the
786     /// next element, seeing if it will return `Some`.
787     ///
788     /// [`Option<T>`]: ../option/enum.Option.html
789     ///
790     /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
791     /// part:
792     ///
793     /// [`filter()`]: #method.filter
794     /// [`map()`]: #method.map
795     ///
796     /// > If the closure returns `Some(element)`, then that element is returned.
797     ///
798     /// In other words, it removes the [`Option<T>`] layer automatically. If your
799     /// mapping is already returning an [`Option<T>`] and you want to skip over
800     /// `None`s, then `filter_map()` is much, much nicer to use.
801     ///
802     /// # Examples
803     ///
804     /// Basic usage:
805     ///
806     /// ```
807     /// let a = ["1", "2", "lol"];
808     ///
809     /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
810     ///
811     /// assert_eq!(iter.next(), Some(1));
812     /// assert_eq!(iter.next(), Some(2));
813     /// assert_eq!(iter.next(), None);
814     /// ```
815     ///
816     /// Here's the same example, but with [`filter()`] and [`map()`]:
817     ///
818     /// ```
819     /// let a = ["1", "2", "lol"];
820     ///
821     /// let mut iter = a.iter()
822     ///                 .map(|s| s.parse().ok())
823     ///                 .filter(|s| s.is_some());
824     ///
825     /// assert_eq!(iter.next(), Some(Some(1)));
826     /// assert_eq!(iter.next(), Some(Some(2)));
827     /// assert_eq!(iter.next(), None);
828     /// ```
829     ///
830     /// There's an extra layer of `Some` in there.
831     #[inline]
832     #[stable(feature = "rust1", since = "1.0.0")]
833     fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
834         Self: Sized, F: FnMut(Self::Item) -> Option<B>,
835     {
836         FilterMap { iter: self, f: f }
837     }
838
839     /// Creates an iterator which gives the current iteration count as well as
840     /// the next value.
841     ///
842     /// The iterator returned yields pairs `(i, val)`, where `i` is the
843     /// current index of iteration and `val` is the value returned by the
844     /// iterator.
845     ///
846     /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
847     /// different sized integer, the [`zip()`] function provides similar
848     /// functionality.
849     ///
850     /// [`usize`]: ../primitive.usize.html
851     /// [`zip()`]: #method.zip
852     ///
853     /// # Overflow Behavior
854     ///
855     /// The method does no guarding against overflows, so enumerating more than
856     /// [`usize::MAX`] elements either produces the wrong result or panics. If
857     /// debug assertions are enabled, a panic is guaranteed.
858     ///
859     /// [`usize::MAX`]: ../usize/constant.MAX.html
860     ///
861     /// # Panics
862     ///
863     /// The returned iterator might panic if the to-be-returned index would
864     /// overflow a `usize`.
865     ///
866     /// # Examples
867     ///
868     /// ```
869     /// let a = [1, 2, 3];
870     ///
871     /// let mut iter = a.iter().enumerate();
872     ///
873     /// assert_eq!(iter.next(), Some((0, &1)));
874     /// assert_eq!(iter.next(), Some((1, &2)));
875     /// assert_eq!(iter.next(), Some((2, &3)));
876     /// assert_eq!(iter.next(), None);
877     /// ```
878     #[inline]
879     #[stable(feature = "rust1", since = "1.0.0")]
880     fn enumerate(self) -> Enumerate<Self> where Self: Sized {
881         Enumerate { iter: self, count: 0 }
882     }
883
884     /// Creates an iterator which can look at the `next()` element without
885     /// consuming it.
886     ///
887     /// Adds a [`peek()`] method to an iterator. See its documentation for
888     /// more information.
889     ///
890     /// [`peek()`]: struct.Peekable.html#method.peek
891     ///
892     /// # Examples
893     ///
894     /// Basic usage:
895     ///
896     /// ```
897     /// let xs = [1, 2, 3];
898     ///
899     /// let mut iter = xs.iter().peekable();
900     ///
901     /// // peek() lets us see into the future
902     /// assert_eq!(iter.peek(), Some(&&1));
903     /// assert_eq!(iter.next(), Some(&1));
904     ///
905     /// assert_eq!(iter.next(), Some(&2));
906     ///
907     /// // we can peek() multiple times, the itererator won't advance
908     /// assert_eq!(iter.peek(), Some(&&3));
909     /// assert_eq!(iter.peek(), Some(&&3));
910     ///
911     /// assert_eq!(iter.next(), Some(&3));
912     ///
913     /// // after the itererator is finished, so is peek()
914     /// assert_eq!(iter.peek(), None);
915     /// assert_eq!(iter.next(), None);
916     /// ```
917     #[inline]
918     #[stable(feature = "rust1", since = "1.0.0")]
919     fn peekable(self) -> Peekable<Self> where Self: Sized {
920         Peekable{iter: self, peeked: None}
921     }
922
923     /// Creates an iterator that [`skip()`]s elements based on a predicate.
924     ///
925     /// [`skip()`]: #method.skip
926     ///
927     /// `skip_while()` takes a closure as an argument. It will call this
928     /// closure on each element of the iterator, and ignore elements
929     /// until it returns `false`.
930     ///
931     /// After `false` is returned, `skip_while()`'s job is over, and the
932     /// rest of the elements are yielded.
933     ///
934     /// # Examples
935     ///
936     /// Basic usage:
937     ///
938     /// ```
939     /// let a = [-1i32, 0, 1];
940     ///
941     /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
942     ///
943     /// assert_eq!(iter.next(), Some(&0));
944     /// assert_eq!(iter.next(), Some(&1));
945     /// assert_eq!(iter.next(), None);
946     /// ```
947     ///
948     /// Because the closure passed to `skip_while()` takes a reference, and many
949     /// iterators iterate over references, this leads to a possibly confusing
950     /// situation, where the type of the closure is a double reference:
951     ///
952     /// ```
953     /// let a = [-1, 0, 1];
954     ///
955     /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
956     ///
957     /// assert_eq!(iter.next(), Some(&0));
958     /// assert_eq!(iter.next(), Some(&1));
959     /// assert_eq!(iter.next(), None);
960     /// ```
961     ///
962     /// Stopping after an initial `false`:
963     ///
964     /// ```
965     /// let a = [-1, 0, 1, -2];
966     ///
967     /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
968     ///
969     /// assert_eq!(iter.next(), Some(&0));
970     /// assert_eq!(iter.next(), Some(&1));
971     ///
972     /// // while this would have been false, since we already got a false,
973     /// // skip_while() isn't used any more
974     /// assert_eq!(iter.next(), Some(&-2));
975     ///
976     /// assert_eq!(iter.next(), None);
977     /// ```
978     #[inline]
979     #[stable(feature = "rust1", since = "1.0.0")]
980     fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
981         Self: Sized, P: FnMut(&Self::Item) -> bool,
982     {
983         SkipWhile{iter: self, flag: false, predicate: predicate}
984     }
985
986     /// Creates an iterator that yields elements based on a predicate.
987     ///
988     /// `take_while()` takes a closure as an argument. It will call this
989     /// closure on each element of the iterator, and yield elements
990     /// while it returns `true`.
991     ///
992     /// After `false` is returned, `take_while()`'s job is over, and the
993     /// rest of the elements are ignored.
994     ///
995     /// # Examples
996     ///
997     /// Basic usage:
998     ///
999     /// ```
1000     /// let a = [-1i32, 0, 1];
1001     ///
1002     /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1003     ///
1004     /// assert_eq!(iter.next(), Some(&-1));
1005     /// assert_eq!(iter.next(), None);
1006     /// ```
1007     ///
1008     /// Because the closure passed to `take_while()` takes a reference, and many
1009     /// iterators iterate over references, this leads to a possibly confusing
1010     /// situation, where the type of the closure is a double reference:
1011     ///
1012     /// ```
1013     /// let a = [-1, 0, 1];
1014     ///
1015     /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1016     ///
1017     /// assert_eq!(iter.next(), Some(&-1));
1018     /// assert_eq!(iter.next(), None);
1019     /// ```
1020     ///
1021     /// Stopping after an initial `false`:
1022     ///
1023     /// ```
1024     /// let a = [-1, 0, 1, -2];
1025     ///
1026     /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1027     ///
1028     /// assert_eq!(iter.next(), Some(&-1));
1029     ///
1030     /// // We have more elements that are less than zero, but since we already
1031     /// // got a false, take_while() isn't used any more
1032     /// assert_eq!(iter.next(), None);
1033     /// ```
1034     #[inline]
1035     #[stable(feature = "rust1", since = "1.0.0")]
1036     fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1037         Self: Sized, P: FnMut(&Self::Item) -> bool,
1038     {
1039         TakeWhile{iter: self, flag: false, predicate: predicate}
1040     }
1041
1042     /// Creates an iterator that skips the first `n` elements.
1043     ///
1044     /// After they have been consumed, the rest of the elements are yielded.
1045     ///
1046     /// # Examples
1047     ///
1048     /// Basic usage:
1049     ///
1050     /// ```
1051     /// let a = [1, 2, 3];
1052     ///
1053     /// let mut iter = a.iter().skip(2);
1054     ///
1055     /// assert_eq!(iter.next(), Some(&3));
1056     /// assert_eq!(iter.next(), None);
1057     /// ```
1058     #[inline]
1059     #[stable(feature = "rust1", since = "1.0.0")]
1060     fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1061         Skip{iter: self, n: n}
1062     }
1063
1064     /// Creates an iterator that yields its first `n` elements.
1065     ///
1066     /// # Examples
1067     ///
1068     /// Basic usage:
1069     ///
1070     /// ```
1071     /// let a = [1, 2, 3];
1072     ///
1073     /// let mut iter = a.iter().take(2);
1074     ///
1075     /// assert_eq!(iter.next(), Some(&1));
1076     /// assert_eq!(iter.next(), Some(&2));
1077     /// assert_eq!(iter.next(), None);
1078     /// ```
1079     ///
1080     /// `take()` is often used with an infinite iterator, to make it finite:
1081     ///
1082     /// ```
1083     /// let mut iter = (0..).take(3);
1084     ///
1085     /// assert_eq!(iter.next(), Some(0));
1086     /// assert_eq!(iter.next(), Some(1));
1087     /// assert_eq!(iter.next(), Some(2));
1088     /// assert_eq!(iter.next(), None);
1089     /// ```
1090     #[inline]
1091     #[stable(feature = "rust1", since = "1.0.0")]
1092     fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1093         Take{iter: self, n: n}
1094     }
1095
1096     /// An iterator similar to `fold()`, with internal state.
1097     ///
1098     /// `scan()` accumulates a final value, similar to [`fold()`], but instead
1099     /// of passing along an accumulator, it maintains the accumulator internally.
1100     ///
1101     /// [`fold()`]: #method.fold
1102     ///
1103     /// On each iteraton of `scan()`, you can assign to the internal state, and
1104     /// a mutable reference to the state is passed as the first argument to the
1105     /// closure, allowing you to modify it on each iteration.
1106     ///
1107     /// # Examples
1108     ///
1109     /// Basic usage:
1110     ///
1111     /// ```
1112     /// let a = [1, 2, 3];
1113     ///
1114     /// let mut iter = a.iter().scan(1, |state, &x| {
1115     ///     // each iteration, we'll multiply the state by the element
1116     ///     *state = *state * x;
1117     ///
1118     ///     // the value passed on to the next iteration
1119     ///     Some(*state)
1120     /// });
1121     ///
1122     /// assert_eq!(iter.next(), Some(1));
1123     /// assert_eq!(iter.next(), Some(2));
1124     /// assert_eq!(iter.next(), Some(6));
1125     /// assert_eq!(iter.next(), None);
1126     /// ```
1127     #[inline]
1128     #[stable(feature = "rust1", since = "1.0.0")]
1129     fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1130         where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1131     {
1132         Scan{iter: self, f: f, state: initial_state}
1133     }
1134
1135     /// Creates an iterator that works like map, but flattens nested structure.
1136     ///
1137     /// The [`map()`] adapter is very useful, but only when the closure
1138     /// argument produces values. If it produces an iterator instead, there's
1139     /// an extra layer of indirection. `flat_map()` will remove this extra layer
1140     /// on its own.
1141     ///
1142     /// [`map()`]: #method.map
1143     ///
1144     /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1145     /// one item for each element, and `flat_map()`'s closure returns an
1146     /// iterator for each element.
1147     ///
1148     /// # Examples
1149     ///
1150     /// Basic usage:
1151     ///
1152     /// ```
1153     /// let words = ["alpha", "beta", "gamma"];
1154     ///
1155     /// // chars() returns an iterator
1156     /// let merged: String = words.iter()
1157     ///                           .flat_map(|s| s.chars())
1158     ///                           .collect();
1159     /// assert_eq!(merged, "alphabetagamma");
1160     /// ```
1161     #[inline]
1162     #[stable(feature = "rust1", since = "1.0.0")]
1163     fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1164         where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1165     {
1166         FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1167     }
1168
1169     /// Creates an iterator which ends after the first `None`.
1170     ///
1171     /// After an iterator returns `None`, future calls may or may not yield
1172     /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1173     /// `None` is given, it will always return `None` forever.
1174     ///
1175     /// # Examples
1176     ///
1177     /// Basic usage:
1178     ///
1179     /// ```
1180     /// // an iterator which alternates between Some and None
1181     /// struct Alternate {
1182     ///     state: i32,
1183     /// }
1184     ///
1185     /// impl Iterator for Alternate {
1186     ///     type Item = i32;
1187     ///
1188     ///     fn next(&mut self) -> Option<i32> {
1189     ///         let val = self.state;
1190     ///         self.state = self.state + 1;
1191     ///
1192     ///         // if it's even, Some(i32), else None
1193     ///         if val % 2 == 0 {
1194     ///             Some(val)
1195     ///         } else {
1196     ///             None
1197     ///         }
1198     ///     }
1199     /// }
1200     ///
1201     /// let mut iter = Alternate { state: 0 };
1202     ///
1203     /// // we can see our iterator going back and forth
1204     /// assert_eq!(iter.next(), Some(0));
1205     /// assert_eq!(iter.next(), None);
1206     /// assert_eq!(iter.next(), Some(2));
1207     /// assert_eq!(iter.next(), None);
1208     ///
1209     /// // however, once we fuse it...
1210     /// let mut iter = iter.fuse();
1211     ///
1212     /// assert_eq!(iter.next(), Some(4));
1213     /// assert_eq!(iter.next(), None);
1214     ///
1215     /// // it will always return None after the first time.
1216     /// assert_eq!(iter.next(), None);
1217     /// assert_eq!(iter.next(), None);
1218     /// assert_eq!(iter.next(), None);
1219     /// ```
1220     #[inline]
1221     #[stable(feature = "rust1", since = "1.0.0")]
1222     fn fuse(self) -> Fuse<Self> where Self: Sized {
1223         Fuse{iter: self, done: false}
1224     }
1225
1226     /// Do something with each element of an iterator, passing the value on.
1227     ///
1228     /// When using iterators, you'll often chain several of them together.
1229     /// While working on such code, you might want to check out what's
1230     /// happening at various parts in the pipeline. To do that, insert
1231     /// a call to `inspect()`.
1232     ///
1233     /// It's much more common for `inspect()` to be used as a debugging tool
1234     /// than to exist in your final code, but never say never.
1235     ///
1236     /// # Examples
1237     ///
1238     /// Basic usage:
1239     ///
1240     /// ```
1241     /// let a = [1, 4, 2, 3];
1242     ///
1243     /// // this iterator sequence is complex.
1244     /// let sum = a.iter()
1245     ///             .cloned()
1246     ///             .filter(|&x| x % 2 == 0)
1247     ///             .fold(0, |sum, i| sum + i);
1248     ///
1249     /// println!("{}", sum);
1250     ///
1251     /// // let's add some inspect() calls to investigate what's happening
1252     /// let sum = a.iter()
1253     ///             .cloned()
1254     ///             .inspect(|x| println!("about to filter: {}", x))
1255     ///             .filter(|&x| x % 2 == 0)
1256     ///             .inspect(|x| println!("made it through filter: {}", x))
1257     ///             .fold(0, |sum, i| sum + i);
1258     ///
1259     /// println!("{}", sum);
1260     /// ```
1261     ///
1262     /// This will print:
1263     ///
1264     /// ```text
1265     /// about to filter: 1
1266     /// about to filter: 4
1267     /// made it through filter: 4
1268     /// about to filter: 2
1269     /// made it through filter: 2
1270     /// about to filter: 3
1271     /// 6
1272     /// ```
1273     #[inline]
1274     #[stable(feature = "rust1", since = "1.0.0")]
1275     fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1276         Self: Sized, F: FnMut(&Self::Item),
1277     {
1278         Inspect{iter: self, f: f}
1279     }
1280
1281     /// Borrows an iterator, rather than consuming it.
1282     ///
1283     /// This is useful to allow applying iterator adaptors while still
1284     /// retaining ownership of the original iterator.
1285     ///
1286     /// # Examples
1287     ///
1288     /// Basic usage:
1289     ///
1290     /// ```
1291     /// let a = [1, 2, 3];
1292     ///
1293     /// let iter = a.into_iter();
1294     ///
1295     /// let sum: i32 = iter.take(5)
1296     ///                    .fold(0, |acc, &i| acc + i );
1297     ///
1298     /// assert_eq!(sum, 6);
1299     ///
1300     /// // if we try to use iter again, it won't work. The following line
1301     /// // gives "error: use of moved value: `iter`
1302     /// // assert_eq!(iter.next(), None);
1303     ///
1304     /// // let's try that again
1305     /// let a = [1, 2, 3];
1306     ///
1307     /// let mut iter = a.into_iter();
1308     ///
1309     /// // instead, we add in a .by_ref()
1310     /// let sum: i32 = iter.by_ref()
1311     ///                    .take(2)
1312     ///                    .fold(0, |acc, &i| acc + i );
1313     ///
1314     /// assert_eq!(sum, 3);
1315     ///
1316     /// // now this is just fine:
1317     /// assert_eq!(iter.next(), Some(&3));
1318     /// assert_eq!(iter.next(), None);
1319     /// ```
1320     #[stable(feature = "rust1", since = "1.0.0")]
1321     fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1322
1323     /// Transforms an iterator into a collection.
1324     ///
1325     /// `collect()` can take anything iterable, and turn it into a relevant
1326     /// collection. This is one of the more powerful methods in the standard
1327     /// library, used in a variety of contexts.
1328     ///
1329     /// The most basic pattern in which `collect()` is used is to turn one
1330     /// collection into another. You take a collection, call `iter()` on it,
1331     /// do a bunch of transformations, and then `collect()` at the end.
1332     ///
1333     /// One of the keys to `collect()`'s power is that many things you might
1334     /// not think of as 'collections' actually are. For example, a [`String`]
1335     /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1336     /// be thought of as single [`Result<Collection<T>, E>`]. See the examples
1337     /// below for more.
1338     ///
1339     /// [`String`]: ../string/struct.String.html
1340     /// [`Result<T, E>`]: ../result/enum.Result.html
1341     /// [`char`]: ../primitive.char.html
1342     ///
1343     /// Because `collect()` is so general, it can cause problems with type
1344     /// inference. As such, `collect()` is one of the few times you'll see
1345     /// the syntax affectionately known as the 'turbofish': `::<>`. This
1346     /// helps the inference algorithm understand specifically which collection
1347     /// you're trying to collect into.
1348     ///
1349     /// # Examples
1350     ///
1351     /// Basic usage:
1352     ///
1353     /// ```
1354     /// let a = [1, 2, 3];
1355     ///
1356     /// let doubled: Vec<i32> = a.iter()
1357     ///                          .map(|&x| x * 2)
1358     ///                          .collect();
1359     ///
1360     /// assert_eq!(vec![2, 4, 6], doubled);
1361     /// ```
1362     ///
1363     /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1364     /// we could collect into, for example, a [`VecDeque<T>`] instead:
1365     ///
1366     /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1367     ///
1368     /// ```
1369     /// use std::collections::VecDeque;
1370     ///
1371     /// let a = [1, 2, 3];
1372     ///
1373     /// let doubled: VecDeque<i32> = a.iter()
1374     ///                               .map(|&x| x * 2)
1375     ///                               .collect();
1376     ///
1377     /// assert_eq!(2, doubled[0]);
1378     /// assert_eq!(4, doubled[1]);
1379     /// assert_eq!(6, doubled[2]);
1380     /// ```
1381     ///
1382     /// Using the 'turbofish' instead of annotationg `doubled`:
1383     ///
1384     /// ```
1385     /// let a = [1, 2, 3];
1386     ///
1387     /// let doubled = a.iter()
1388     ///                .map(|&x| x * 2)
1389     ///                .collect::<Vec<i32>>();
1390     ///
1391     /// assert_eq!(vec![2, 4, 6], doubled);
1392     /// ```
1393     ///
1394     /// Because `collect()` cares about what you're collecting into, you can
1395     /// still use a partial type hint, `_`, with the turbofish:
1396     ///
1397     /// ```
1398     /// let a = [1, 2, 3];
1399     ///
1400     /// let doubled = a.iter()
1401     ///                .map(|&x| x * 2)
1402     ///                .collect::<Vec<_>>();
1403     ///
1404     /// assert_eq!(vec![2, 4, 6], doubled);
1405     /// ```
1406     ///
1407     /// Using `collect()` to make a [`String`]:
1408     ///
1409     /// ```
1410     /// let chars = ['g', 'd', 'k', 'k', 'n'];
1411     ///
1412     /// let hello: String = chars.iter()
1413     ///                          .map(|&x| x as u8)
1414     ///                          .map(|x| (x + 1) as char)
1415     ///                          .collect();
1416     ///
1417     /// assert_eq!("hello", hello);
1418     /// ```
1419     ///
1420     /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1421     /// see if any of them failed:
1422     ///
1423     /// ```
1424     /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1425     ///
1426     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1427     ///
1428     /// // gives us the first error
1429     /// assert_eq!(Err("nope"), result);
1430     ///
1431     /// let results = [Ok(1), Ok(3)];
1432     ///
1433     /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1434     ///
1435     /// // gives us the list of answers
1436     /// assert_eq!(Ok(vec![1, 3]), result);
1437     /// ```
1438     #[inline]
1439     #[stable(feature = "rust1", since = "1.0.0")]
1440     fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1441         FromIterator::from_iter(self)
1442     }
1443
1444     /// Consumes an iterator, creating two collections from it.
1445     ///
1446     /// The predicate passed to `partition()` can return `true`, or `false`.
1447     /// `partition()` returns a pair, all of the elements for which it returned
1448     /// `true`, and all of the elements for which it returned `false`.
1449     ///
1450     /// # Examples
1451     ///
1452     /// Basic usage:
1453     ///
1454     /// ```
1455     /// let a = [1, 2, 3];
1456     ///
1457     /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1458     ///                                          .partition(|&n| n % 2 == 0);
1459     ///
1460     /// assert_eq!(even, vec![2]);
1461     /// assert_eq!(odd, vec![1, 3]);
1462     /// ```
1463     #[stable(feature = "rust1", since = "1.0.0")]
1464     fn partition<B, F>(self, mut f: F) -> (B, B) where
1465         Self: Sized,
1466         B: Default + Extend<Self::Item>,
1467         F: FnMut(&Self::Item) -> bool
1468     {
1469         let mut left: B = Default::default();
1470         let mut right: B = Default::default();
1471
1472         for x in self {
1473             if f(&x) {
1474                 left.extend(Some(x))
1475             } else {
1476                 right.extend(Some(x))
1477             }
1478         }
1479
1480         (left, right)
1481     }
1482
1483     /// An iterator adaptor that applies a function, producing a single, final value.
1484     ///
1485     /// `fold()` takes two arguments: an initial value, and a closure with two
1486     /// arguments: an 'accumulator', and an element. It returns the value that
1487     /// the accumulator should have for the next iteration.
1488     ///
1489     /// The initial value is the value the accumulator will have on the first
1490     /// call.
1491     ///
1492     /// After applying this closure to every element of the iterator, `fold()`
1493     /// returns the accumulator.
1494     ///
1495     /// This operation is sometimes called 'reduce' or 'inject'.
1496     ///
1497     /// Folding is useful whenever you have a collection of something, and want
1498     /// to produce a single value from it.
1499     ///
1500     /// # Examples
1501     ///
1502     /// Basic usage:
1503     ///
1504     /// ```
1505     /// let a = [1, 2, 3];
1506     ///
1507     /// // the sum of all of the elements of a
1508     /// let sum = a.iter()
1509     ///            .fold(0, |acc, &x| acc + x);
1510     ///
1511     /// assert_eq!(sum, 6);
1512     /// ```
1513     ///
1514     /// Let's walk through each step of the iteration here:
1515     ///
1516     /// | element | acc | x | result |
1517     /// |---------|-----|---|--------|
1518     /// |         | 0   |   |        |
1519     /// | 1       | 0   | 1 | 1      |
1520     /// | 2       | 1   | 2 | 3      |
1521     /// | 3       | 3   | 3 | 6      |
1522     ///
1523     /// And so, our final result, `6`.
1524     ///
1525     /// It's common for people who haven't used iterators a lot to
1526     /// use a `for` loop with a list of things to build up a result. Those
1527     /// can be turned into `fold()`s:
1528     ///
1529     /// ```
1530     /// let numbers = [1, 2, 3, 4, 5];
1531     ///
1532     /// let mut result = 0;
1533     ///
1534     /// // for loop:
1535     /// for i in &numbers {
1536     ///     result = result + i;
1537     /// }
1538     ///
1539     /// // fold:
1540     /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1541     ///
1542     /// // they're the same
1543     /// assert_eq!(result, result2);
1544     /// ```
1545     #[inline]
1546     #[stable(feature = "rust1", since = "1.0.0")]
1547     fn fold<B, F>(self, init: B, mut f: F) -> B where
1548         Self: Sized, F: FnMut(B, Self::Item) -> B,
1549     {
1550         let mut accum = init;
1551         for x in self {
1552             accum = f(accum, x);
1553         }
1554         accum
1555     }
1556
1557     /// Tests if every element of the iterator matches a predicate.
1558     ///
1559     /// `all()` takes a closure that returns `true` or `false`. It applies
1560     /// this closure to each element of the iterator, and if they all return
1561     /// `true`, then so does `all()`. If any of them return `false`, it
1562     /// returns `false`.
1563     ///
1564     /// `all()` is short-circuting; in other words, it will stop processing
1565     /// as soon as it finds a `false`, given that no matter what else happens,
1566     /// the result will also be `false`.
1567     ///
1568     /// # Examples
1569     ///
1570     /// Basic usage:
1571     ///
1572     /// ```
1573     /// let a = [1, 2, 3];
1574     ///
1575     /// assert!(a.iter().all(|&x| x > 0));
1576     ///
1577     /// assert!(!a.iter().all(|&x| x > 2));
1578     /// ```
1579     ///
1580     /// Stopping at the first `false`:
1581     ///
1582     /// ```
1583     /// let a = [1, 2, 3];
1584     ///
1585     /// let mut iter = a.iter();
1586     ///
1587     /// assert!(!iter.all(|&x| x != 2));
1588     ///
1589     /// // we can still use `iter`, as there are more elements.
1590     /// assert_eq!(iter.next(), Some(&3));
1591     /// ```
1592     #[inline]
1593     #[stable(feature = "rust1", since = "1.0.0")]
1594     fn all<F>(&mut self, mut f: F) -> bool where
1595         Self: Sized, F: FnMut(Self::Item) -> bool
1596     {
1597         for x in self {
1598             if !f(x) {
1599                 return false;
1600             }
1601         }
1602         true
1603     }
1604
1605     /// Tests if any element of the iterator matches a predicate.
1606     ///
1607     /// `any()` takes a closure that returns `true` or `false`. It applies
1608     /// this closure to each element of the iterator, and if any of them return
1609     /// `true`, then so does `any()`. If they all return `false`, it
1610     /// returns `false`.
1611     ///
1612     /// `any()` is short-circuting; in other words, it will stop processing
1613     /// as soon as it finds a `true`, given that no matter what else happens,
1614     /// the result will also be `true`.
1615     ///
1616     /// # Examples
1617     ///
1618     /// Basic usage:
1619     ///
1620     /// ```
1621     /// let a = [1, 2, 3];
1622     ///
1623     /// assert!(a.iter().any(|&x| x > 0));
1624     ///
1625     /// assert!(!a.iter().any(|&x| x > 5));
1626     /// ```
1627     ///
1628     /// Stopping at the first `true`:
1629     ///
1630     /// ```
1631     /// let a = [1, 2, 3];
1632     ///
1633     /// let mut iter = a.iter();
1634     ///
1635     /// assert!(iter.any(|&x| x != 2));
1636     ///
1637     /// // we can still use `iter`, as there are more elements.
1638     /// assert_eq!(iter.next(), Some(&2));
1639     /// ```
1640     #[inline]
1641     #[stable(feature = "rust1", since = "1.0.0")]
1642     fn any<F>(&mut self, mut f: F) -> bool where
1643         Self: Sized,
1644         F: FnMut(Self::Item) -> bool
1645     {
1646         for x in self {
1647             if f(x) {
1648                 return true;
1649             }
1650         }
1651         false
1652     }
1653
1654     /// Searches for an element of an iterator that satisfies a predicate.
1655     ///
1656     /// `find()` takes a closure that returns `true` or `false`. It applies
1657     /// this closure to each element of the iterator, and if any of them return
1658     /// `true`, then `find()` returns `Some(element)`. If they all return
1659     /// `false`, it returns `None`.
1660     ///
1661     /// `find()` is short-circuting; in other words, it will stop processing
1662     /// as soon as the closure returns `true`.
1663     ///
1664     /// Because `find()` takes a reference, and many iterators iterate over
1665     /// references, this leads to a possibly confusing situation where the
1666     /// argument is a double reference. You can see this effect in the
1667     /// examples below, with `&&x`.
1668     ///
1669     /// # Examples
1670     ///
1671     /// Basic usage:
1672     ///
1673     /// ```
1674     /// let a = [1, 2, 3];
1675     ///
1676     /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1677     ///
1678     /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1679     /// ```
1680     ///
1681     /// Stopping at the first `true`:
1682     ///
1683     /// ```
1684     /// let a = [1, 2, 3];
1685     ///
1686     /// let mut iter = a.iter();
1687     ///
1688     /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1689     ///
1690     /// // we can still use `iter`, as there are more elements.
1691     /// assert_eq!(iter.next(), Some(&3));
1692     /// ```
1693     #[inline]
1694     #[stable(feature = "rust1", since = "1.0.0")]
1695     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1696         Self: Sized,
1697         P: FnMut(&Self::Item) -> bool,
1698     {
1699         for x in self {
1700             if predicate(&x) { return Some(x) }
1701         }
1702         None
1703     }
1704
1705     /// Searches for an element in an iterator, returning its index.
1706     ///
1707     /// `position()` takes a closure that returns `true` or `false`. It applies
1708     /// this closure to each element of the iterator, and if if one of them
1709     /// returns `true`, then `position()` returns `Some(index)`. If all of
1710     /// them return `false`, it returns `None`.
1711     ///
1712     /// `position()` is short-circuting; in other words, it will stop
1713     /// processing as soon as it finds a `true`.
1714     ///
1715     /// # Overflow Behavior
1716     ///
1717     /// The method does no guarding against overflows, so if there are more
1718     /// than `usize::MAX` non-matching elements, it either produces the wrong
1719     /// result or panics. If debug assertions are enabled, a panic is
1720     /// guaranteed.
1721     ///
1722     /// # Panics
1723     ///
1724     /// This function might panic if the iterator has more than `usize::MAX`
1725     /// non-matching elements.
1726     ///
1727     /// # Examples
1728     ///
1729     /// Basic usage:
1730     ///
1731     /// ```
1732     /// let a = [1, 2, 3];
1733     ///
1734     /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1735     ///
1736     /// assert_eq!(a.iter().position(|&x| x == 5), None);
1737     /// ```
1738     ///
1739     /// Stopping at the first `true`:
1740     ///
1741     /// ```
1742     /// let a = [1, 2, 3];
1743     ///
1744     /// let mut iter = a.iter();
1745     ///
1746     /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1747     ///
1748     /// // we can still use `iter`, as there are more elements.
1749     /// assert_eq!(iter.next(), Some(&3));
1750     /// ```
1751     #[inline]
1752     #[stable(feature = "rust1", since = "1.0.0")]
1753     fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1754         Self: Sized,
1755         P: FnMut(Self::Item) -> bool,
1756     {
1757         // `enumerate` might overflow.
1758         for (i, x) in self.enumerate() {
1759             if predicate(x) {
1760                 return Some(i);
1761             }
1762         }
1763         None
1764     }
1765
1766     /// Searches for an element in an iterator from the right, returning its
1767     /// index.
1768     ///
1769     /// `rposition()` takes a closure that returns `true` or `false`. It applies
1770     /// this closure to each element of the iterator, starting from the end,
1771     /// and if if one of them returns `true`, then `rposition()` returns
1772     /// `Some(index)`. If all of them return `false`, it returns `None`.
1773     ///
1774     /// `rposition()` is short-circuting; in other words, it will stop
1775     /// processing as soon as it finds a `true`.
1776     ///
1777     /// # Examples
1778     ///
1779     /// Basic usage:
1780     ///
1781     /// ```
1782     /// let a = [1, 2, 3];
1783     ///
1784     /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1785     ///
1786     /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1787     /// ```
1788     ///
1789     /// Stopping at the first `true`:
1790     ///
1791     /// ```
1792     /// let a = [1, 2, 3];
1793     ///
1794     /// let mut iter = a.iter();
1795     ///
1796     /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1797     ///
1798     /// // we can still use `iter`, as there are more elements.
1799     /// assert_eq!(iter.next(), Some(&1));
1800     /// ```
1801     #[inline]
1802     #[stable(feature = "rust1", since = "1.0.0")]
1803     fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1804         P: FnMut(Self::Item) -> bool,
1805         Self: Sized + ExactSizeIterator + DoubleEndedIterator
1806     {
1807         let mut i = self.len();
1808
1809         while let Some(v) = self.next_back() {
1810             if predicate(v) {
1811                 return Some(i - 1);
1812             }
1813             // No need for an overflow check here, because `ExactSizeIterator`
1814             // implies that the number of elements fits into a `usize`.
1815             i -= 1;
1816         }
1817         None
1818     }
1819
1820     /// Returns the maximum element of an iterator.
1821     ///
1822     /// If the two elements are equally maximum, the latest element is
1823     /// returned.
1824     ///
1825     /// # Examples
1826     ///
1827     /// Basic usage:
1828     ///
1829     /// ```
1830     /// let a = [1, 2, 3];
1831     ///
1832     /// assert_eq!(a.iter().max(), Some(&3));
1833     /// ```
1834     #[inline]
1835     #[stable(feature = "rust1", since = "1.0.0")]
1836     fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1837     {
1838         select_fold1(self,
1839                      |_| (),
1840                      // switch to y even if it is only equal, to preserve
1841                      // stability.
1842                      |_, x, _, y| *x <= *y)
1843             .map(|(_, x)| x)
1844     }
1845
1846     /// Returns the minimum element of an iterator.
1847     ///
1848     /// If the two elements are equally minimum, the first element is
1849     /// returned.
1850     ///
1851     /// # Examples
1852     ///
1853     /// Basic usage:
1854     ///
1855     /// ```
1856     /// let a = [1, 2, 3];
1857     ///
1858     /// assert_eq!(a.iter().min(), Some(&1));
1859     /// ```
1860     #[inline]
1861     #[stable(feature = "rust1", since = "1.0.0")]
1862     fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1863     {
1864         select_fold1(self,
1865                      |_| (),
1866                      // only switch to y if it is strictly smaller, to
1867                      // preserve stability.
1868                      |_, x, _, y| *x > *y)
1869             .map(|(_, x)| x)
1870     }
1871
1872     /// Returns the element that gives the maximum value from the
1873     /// specified function.
1874     ///
1875     /// Returns the rightmost element if the comparison determines two elements
1876     /// to be equally maximum.
1877     ///
1878     /// # Examples
1879     ///
1880     /// ```
1881     /// #![feature(iter_cmp)]
1882     ///
1883     /// let a = [-3_i32, 0, 1, 5, -10];
1884     /// assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10);
1885     /// ```
1886     #[inline]
1887     #[unstable(feature = "iter_cmp",
1888                reason = "may want to produce an Ordering directly; see #15311",
1889                issue = "27724")]
1890     fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1891         Self: Sized,
1892         F: FnMut(&Self::Item) -> B,
1893     {
1894         select_fold1(self,
1895                      f,
1896                      // switch to y even if it is only equal, to preserve
1897                      // stability.
1898                      |x_p, _, y_p, _| x_p <= y_p)
1899             .map(|(_, x)| x)
1900     }
1901
1902     /// Returns the element that gives the minimum value from the
1903     /// specified function.
1904     ///
1905     /// Returns the latest element if the comparison determines two elements
1906     /// to be equally minimum.
1907     ///
1908     /// # Examples
1909     ///
1910     /// ```
1911     /// #![feature(iter_cmp)]
1912     ///
1913     /// let a = [-3_i32, 0, 1, 5, -10];
1914     /// assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0);
1915     /// ```
1916     #[inline]
1917     #[unstable(feature = "iter_cmp",
1918                reason = "may want to produce an Ordering directly; see #15311",
1919                issue = "27724")]
1920     fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1921         Self: Sized,
1922         F: FnMut(&Self::Item) -> B,
1923     {
1924         select_fold1(self,
1925                      f,
1926                      // only switch to y if it is strictly smaller, to
1927                      // preserve stability.
1928                      |x_p, _, y_p, _| x_p > y_p)
1929             .map(|(_, x)| x)
1930     }
1931
1932     /// Reverses an iterator's direction.
1933     ///
1934     /// Usually, iterators iterate from left to right. After using `rev()`,
1935     /// an iterator will instead iterate from right to left.
1936     ///
1937     /// This is only possible if the iterator has an end, so `rev()` only
1938     /// works on [`DoubleEndedIterator`]s.
1939     ///
1940     /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1941     ///
1942     /// # Examples
1943     ///
1944     /// ```
1945     /// let a = [1, 2, 3];
1946     ///
1947     /// let mut iter = a.iter().rev();
1948     ///
1949     /// assert_eq!(iter.next(), Some(&3));
1950     /// assert_eq!(iter.next(), Some(&2));
1951     /// assert_eq!(iter.next(), Some(&1));
1952     ///
1953     /// assert_eq!(iter.next(), None);
1954     /// ```
1955     #[inline]
1956     #[stable(feature = "rust1", since = "1.0.0")]
1957     fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1958         Rev{iter: self}
1959     }
1960
1961     /// Converts an iterator of pairs into a pair of containers.
1962     ///
1963     /// `unzip()` consumes an entire iterator of pairs, producing two
1964     /// collections: one from the left elements of the pairs, and one
1965     /// from the right elements.
1966     ///
1967     /// This function is, in some sense, the opposite of [`zip()`].
1968     ///
1969     /// [`zip()`]: #method.zip
1970     ///
1971     /// # Examples
1972     ///
1973     /// Basic usage:
1974     ///
1975     /// ```
1976     /// let a = [(1, 2), (3, 4)];
1977     ///
1978     /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1979     ///
1980     /// assert_eq!(left, [1, 3]);
1981     /// assert_eq!(right, [2, 4]);
1982     /// ```
1983     #[stable(feature = "rust1", since = "1.0.0")]
1984     fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1985         FromA: Default + Extend<A>,
1986         FromB: Default + Extend<B>,
1987         Self: Sized + Iterator<Item=(A, B)>,
1988     {
1989         struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
1990         impl<A> Iterator for SizeHint<A> {
1991             type Item = A;
1992
1993             fn next(&mut self) -> Option<A> { None }
1994             fn size_hint(&self) -> (usize, Option<usize>) {
1995                 (self.0, self.1)
1996             }
1997         }
1998
1999         let (lo, hi) = self.size_hint();
2000         let mut ts: FromA = Default::default();
2001         let mut us: FromB = Default::default();
2002
2003         ts.extend(SizeHint(lo, hi, marker::PhantomData));
2004         us.extend(SizeHint(lo, hi, marker::PhantomData));
2005
2006         for (t, u) in self {
2007             ts.extend(Some(t));
2008             us.extend(Some(u));
2009         }
2010
2011         (ts, us)
2012     }
2013
2014     /// Creates an iterator which clone()s all of its elements.
2015     ///
2016     /// This is useful when you have an iterator over `&T`, but you need an
2017     /// iterator over `T`.
2018     ///
2019     /// # Examples
2020     ///
2021     /// Basic usage:
2022     ///
2023     /// ```
2024     /// let a = [1, 2, 3];
2025     ///
2026     /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2027     ///
2028     /// // cloned is the same as .map(|&x| x), for integers
2029     /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2030     ///
2031     /// assert_eq!(v_cloned, vec![1, 2, 3]);
2032     /// assert_eq!(v_map, vec![1, 2, 3]);
2033     /// ```
2034     #[stable(feature = "rust1", since = "1.0.0")]
2035     fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2036         where Self: Sized + Iterator<Item=&'a T>, T: Clone
2037     {
2038         Cloned { it: self }
2039     }
2040
2041     /// Repeats an iterator endlessly.
2042     ///
2043     /// Instead of stopping at `None`, the iterator will instead start again,
2044     /// from the beginning. After iterating again, it will start at the
2045     /// beginning again. And again. And again. Forever.
2046     ///
2047     /// # Examples
2048     ///
2049     /// Basic usage:
2050     ///
2051     /// ```
2052     /// let a = [1, 2, 3];
2053     ///
2054     /// let mut it = a.iter().cycle();
2055     ///
2056     /// assert_eq!(it.next(), Some(&1));
2057     /// assert_eq!(it.next(), Some(&2));
2058     /// assert_eq!(it.next(), Some(&3));
2059     /// assert_eq!(it.next(), Some(&1));
2060     /// assert_eq!(it.next(), Some(&2));
2061     /// assert_eq!(it.next(), Some(&3));
2062     /// assert_eq!(it.next(), Some(&1));
2063     /// ```
2064     #[stable(feature = "rust1", since = "1.0.0")]
2065     #[inline]
2066     fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2067         Cycle{orig: self.clone(), iter: self}
2068     }
2069
2070     /// Sums the elements of an iterator.
2071     ///
2072     /// Takes each element, adds them together, and returns the result.
2073     ///
2074     /// # Examples
2075     ///
2076     /// Basic usage:
2077     ///
2078     /// ```
2079     /// #![feature(iter_arith)]
2080     ///
2081     /// let a = [1, 2, 3];
2082     /// let sum: i32 = a.iter().sum();
2083     ///
2084     /// assert_eq!(sum, 6);
2085     /// ```
2086     #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2087                issue = "27739")]
2088     fn sum<S=<Self as Iterator>::Item>(self) -> S where
2089         S: Add<Self::Item, Output=S> + Zero,
2090         Self: Sized,
2091     {
2092         self.fold(Zero::zero(), |s, e| s + e)
2093     }
2094
2095     /// Iterates over the entire iterator, multiplying all the elements
2096     ///
2097     /// # Examples
2098     ///
2099     /// ```
2100     /// #![feature(iter_arith)]
2101     ///
2102     /// fn factorial(n: u32) -> u32 {
2103     ///     (1..).take_while(|&i| i <= n).product()
2104     /// }
2105     /// assert_eq!(factorial(0), 1);
2106     /// assert_eq!(factorial(1), 1);
2107     /// assert_eq!(factorial(5), 120);
2108     /// ```
2109     #[unstable(feature="iter_arith", reason = "bounds recently changed",
2110                issue = "27739")]
2111     fn product<P=<Self as Iterator>::Item>(self) -> P where
2112         P: Mul<Self::Item, Output=P> + One,
2113         Self: Sized,
2114     {
2115         self.fold(One::one(), |p, e| p * e)
2116     }
2117
2118     /// Lexicographically compares the elements of this `Iterator` with those
2119     /// of another.
2120     #[stable(feature = "iter_order", since = "1.5.0")]
2121     fn cmp<I>(mut self, other: I) -> Ordering where
2122         I: IntoIterator<Item = Self::Item>,
2123         Self::Item: Ord,
2124         Self: Sized,
2125     {
2126         let mut other = other.into_iter();
2127
2128         loop {
2129             match (self.next(), other.next()) {
2130                 (None, None) => return Ordering::Equal,
2131                 (None, _   ) => return Ordering::Less,
2132                 (_   , None) => return Ordering::Greater,
2133                 (Some(x), Some(y)) => match x.cmp(&y) {
2134                     Ordering::Equal => (),
2135                     non_eq => return non_eq,
2136                 },
2137             }
2138         }
2139     }
2140
2141     /// Lexicographically compares the elements of this `Iterator` with those
2142     /// of another.
2143     #[stable(feature = "iter_order", since = "1.5.0")]
2144     fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2145         I: IntoIterator,
2146         Self::Item: PartialOrd<I::Item>,
2147         Self: Sized,
2148     {
2149         let mut other = other.into_iter();
2150
2151         loop {
2152             match (self.next(), other.next()) {
2153                 (None, None) => return Some(Ordering::Equal),
2154                 (None, _   ) => return Some(Ordering::Less),
2155                 (_   , None) => return Some(Ordering::Greater),
2156                 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2157                     Some(Ordering::Equal) => (),
2158                     non_eq => return non_eq,
2159                 },
2160             }
2161         }
2162     }
2163
2164     /// Determines if the elements of this `Iterator` are equal to those of
2165     /// another.
2166     #[stable(feature = "iter_order", since = "1.5.0")]
2167     fn eq<I>(mut self, other: I) -> bool where
2168         I: IntoIterator,
2169         Self::Item: PartialEq<I::Item>,
2170         Self: Sized,
2171     {
2172         let mut other = other.into_iter();
2173
2174         loop {
2175             match (self.next(), other.next()) {
2176                 (None, None) => return true,
2177                 (None, _) | (_, None) => return false,
2178                 (Some(x), Some(y)) => if x != y { return false },
2179             }
2180         }
2181     }
2182
2183     /// Determines if the elements of this `Iterator` are unequal to those of
2184     /// another.
2185     #[stable(feature = "iter_order", since = "1.5.0")]
2186     fn ne<I>(mut self, other: I) -> bool where
2187         I: IntoIterator,
2188         Self::Item: PartialEq<I::Item>,
2189         Self: Sized,
2190     {
2191         let mut other = other.into_iter();
2192
2193         loop {
2194             match (self.next(), other.next()) {
2195                 (None, None) => return false,
2196                 (None, _) | (_, None) => return true,
2197                 (Some(x), Some(y)) => if x.ne(&y) { return true },
2198             }
2199         }
2200     }
2201
2202     /// Determines if the elements of this `Iterator` are lexicographically
2203     /// less than those of another.
2204     #[stable(feature = "iter_order", since = "1.5.0")]
2205     fn lt<I>(mut self, other: I) -> bool where
2206         I: IntoIterator,
2207         Self::Item: PartialOrd<I::Item>,
2208         Self: Sized,
2209     {
2210         let mut other = other.into_iter();
2211
2212         loop {
2213             match (self.next(), other.next()) {
2214                 (None, None) => return false,
2215                 (None, _   ) => return true,
2216                 (_   , None) => return false,
2217                 (Some(x), Some(y)) => {
2218                     match x.partial_cmp(&y) {
2219                         Some(Ordering::Less) => return true,
2220                         Some(Ordering::Equal) => {}
2221                         Some(Ordering::Greater) => return false,
2222                         None => return false,
2223                     }
2224                 },
2225             }
2226         }
2227     }
2228
2229     /// Determines if the elements of this `Iterator` are lexicographically
2230     /// less or equal to those of another.
2231     #[stable(feature = "iter_order", since = "1.5.0")]
2232     fn le<I>(mut self, other: I) -> bool where
2233         I: IntoIterator,
2234         Self::Item: PartialOrd<I::Item>,
2235         Self: Sized,
2236     {
2237         let mut other = other.into_iter();
2238
2239         loop {
2240             match (self.next(), other.next()) {
2241                 (None, None) => return true,
2242                 (None, _   ) => return true,
2243                 (_   , None) => return false,
2244                 (Some(x), Some(y)) => {
2245                     match x.partial_cmp(&y) {
2246                         Some(Ordering::Less) => return true,
2247                         Some(Ordering::Equal) => {}
2248                         Some(Ordering::Greater) => return false,
2249                         None => return false,
2250                     }
2251                 },
2252             }
2253         }
2254     }
2255
2256     /// Determines if the elements of this `Iterator` are lexicographically
2257     /// greater than those of another.
2258     #[stable(feature = "iter_order", since = "1.5.0")]
2259     fn gt<I>(mut self, other: I) -> bool where
2260         I: IntoIterator,
2261         Self::Item: PartialOrd<I::Item>,
2262         Self: Sized,
2263     {
2264         let mut other = other.into_iter();
2265
2266         loop {
2267             match (self.next(), other.next()) {
2268                 (None, None) => return false,
2269                 (None, _   ) => return false,
2270                 (_   , None) => return true,
2271                 (Some(x), Some(y)) => {
2272                     match x.partial_cmp(&y) {
2273                         Some(Ordering::Less) => return false,
2274                         Some(Ordering::Equal) => {}
2275                         Some(Ordering::Greater) => return true,
2276                         None => return false,
2277                     }
2278                 }
2279             }
2280         }
2281     }
2282
2283     /// Determines if the elements of this `Iterator` are lexicographically
2284     /// greater than or equal to those of another.
2285     #[stable(feature = "iter_order", since = "1.5.0")]
2286     fn ge<I>(mut self, other: I) -> bool where
2287         I: IntoIterator,
2288         Self::Item: PartialOrd<I::Item>,
2289         Self: Sized,
2290     {
2291         let mut other = other.into_iter();
2292
2293         loop {
2294             match (self.next(), other.next()) {
2295                 (None, None) => return true,
2296                 (None, _   ) => return false,
2297                 (_   , None) => return true,
2298                 (Some(x), Some(y)) => {
2299                     match x.partial_cmp(&y) {
2300                         Some(Ordering::Less) => return false,
2301                         Some(Ordering::Equal) => {}
2302                         Some(Ordering::Greater) => return true,
2303                         None => return false,
2304                     }
2305                 },
2306             }
2307         }
2308     }
2309 }
2310
2311 /// Select an element from an iterator based on the given projection
2312 /// and "comparison" function.
2313 ///
2314 /// This is an idiosyncratic helper to try to factor out the
2315 /// commonalities of {max,min}{,_by}. In particular, this avoids
2316 /// having to implement optimizations several times.
2317 #[inline]
2318 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2319                                   mut f_proj: FProj,
2320                                   mut f_cmp: FCmp) -> Option<(B, I::Item)>
2321     where I: Iterator,
2322           FProj: FnMut(&I::Item) -> B,
2323           FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2324 {
2325     // start with the first element as our selection. This avoids
2326     // having to use `Option`s inside the loop, translating to a
2327     // sizeable performance gain (6x in one case).
2328     it.next().map(|mut sel| {
2329         let mut sel_p = f_proj(&sel);
2330
2331         for x in it {
2332             let x_p = f_proj(&x);
2333             if f_cmp(&sel_p,  &sel, &x_p, &x) {
2334                 sel = x;
2335                 sel_p = x_p;
2336             }
2337         }
2338         (sel_p, sel)
2339     })
2340 }
2341
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2344     type Item = I::Item;
2345     fn next(&mut self) -> Option<I::Item> { (**self).next() }
2346     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2347 }
2348
2349 /// Conversion from an `Iterator`.
2350 #[stable(feature = "rust1", since = "1.0.0")]
2351 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2352                           built from an iterator over elements of type `{A}`"]
2353 pub trait FromIterator<A>: Sized {
2354     /// Builds a container with elements from something iterable.
2355     ///
2356     /// # Examples
2357     ///
2358     /// ```
2359     /// use std::collections::HashSet;
2360     /// use std::iter::FromIterator;
2361     ///
2362     /// let colors_vec = vec!["red", "red", "yellow", "blue"];
2363     /// let colors_set = HashSet::<&str>::from_iter(colors_vec);
2364     /// assert_eq!(colors_set.len(), 3);
2365     /// ```
2366     ///
2367     /// `FromIterator` is more commonly used implicitly via the
2368     /// `Iterator::collect` method:
2369     ///
2370     /// ```
2371     /// use std::collections::HashSet;
2372     ///
2373     /// let colors_vec = vec!["red", "red", "yellow", "blue"];
2374     /// let colors_set = colors_vec.into_iter().collect::<HashSet<&str>>();
2375     /// assert_eq!(colors_set.len(), 3);
2376     /// ```
2377     #[stable(feature = "rust1", since = "1.0.0")]
2378     fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
2379 }
2380
2381 /// Conversion into an `Iterator`.
2382 ///
2383 /// By implementing `IntoIterator` for a type, you define how it will be
2384 /// converted to an iterator. This is common for types which describe a
2385 /// collection of some kind.
2386 ///
2387 /// One benefit of implementing `IntoIterator` is that your type will [work
2388 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2389 ///
2390 /// # Examples
2391 ///
2392 /// Vectors implement `IntoIterator`:
2393 ///
2394 /// ```
2395 /// let v = vec![1, 2, 3];
2396 ///
2397 /// let mut iter = v.into_iter();
2398 ///
2399 /// let n = iter.next();
2400 /// assert_eq!(Some(1), n);
2401 ///
2402 /// let n = iter.next();
2403 /// assert_eq!(Some(2), n);
2404 ///
2405 /// let n = iter.next();
2406 /// assert_eq!(Some(3), n);
2407 ///
2408 /// let n = iter.next();
2409 /// assert_eq!(None, n);
2410 /// ```
2411 ///
2412 /// Implementing `IntoIterator` for your type:
2413 ///
2414 /// ```
2415 /// // A sample collection, that's just a wrapper over Vec<T>
2416 /// #[derive(Debug)]
2417 /// struct MyCollection(Vec<i32>);
2418 ///
2419 /// // Let's give it some methods so we can create one and add things
2420 /// // to it.
2421 /// impl MyCollection {
2422 ///     fn new() -> MyCollection {
2423 ///         MyCollection(Vec::new())
2424 ///     }
2425 ///
2426 ///     fn add(&mut self, elem: i32) {
2427 ///         self.0.push(elem);
2428 ///     }
2429 /// }
2430 ///
2431 /// // and we'll implement IntoIterator
2432 /// impl IntoIterator for MyCollection {
2433 ///     type Item = i32;
2434 ///     type IntoIter = ::std::vec::IntoIter<i32>;
2435 ///
2436 ///     fn into_iter(self) -> Self::IntoIter {
2437 ///         self.0.into_iter()
2438 ///     }
2439 /// }
2440 ///
2441 /// // Now we can make a new collection...
2442 /// let mut c = MyCollection::new();
2443 ///
2444 /// // ... add some stuff to it ...
2445 /// c.add(0);
2446 /// c.add(1);
2447 /// c.add(2);
2448 ///
2449 /// // ... and then turn it into an Iterator:
2450 /// for (i, n) in c.into_iter().enumerate() {
2451 ///     assert_eq!(i as i32, n);
2452 /// }
2453 /// ```
2454 #[stable(feature = "rust1", since = "1.0.0")]
2455 pub trait IntoIterator {
2456     /// The type of the elements being iterated over.
2457     #[stable(feature = "rust1", since = "1.0.0")]
2458     type Item;
2459
2460     /// Which kind of iterator are we turning this into?
2461     #[stable(feature = "rust1", since = "1.0.0")]
2462     type IntoIter: Iterator<Item=Self::Item>;
2463
2464     /// Consumes `Self` and returns an iterator over it.
2465     #[stable(feature = "rust1", since = "1.0.0")]
2466     fn into_iter(self) -> Self::IntoIter;
2467 }
2468
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 impl<I: Iterator> IntoIterator for I {
2471     type Item = I::Item;
2472     type IntoIter = I;
2473
2474     fn into_iter(self) -> I {
2475         self
2476     }
2477 }
2478
2479 /// Extend a collection with the contents of an iterator.
2480 ///
2481 /// Iterators produce a series of values, and collections can also be thought
2482 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2483 /// to extend a collection by including the contents of that iterator.
2484 ///
2485 /// # Examples
2486 ///
2487 /// Basic usage:
2488 ///
2489 /// ```
2490 /// // You can extend a String with some chars:
2491 /// let mut message = String::from("The first three letters are: ");
2492 ///
2493 /// message.extend(&['a', 'b', 'c']);
2494 ///
2495 /// assert_eq!("abc", &message[29..32]);
2496 /// ```
2497 ///
2498 /// Implementing `Extend`:
2499 ///
2500 /// ```
2501 /// // A sample collection, that's just a wrapper over Vec<T>
2502 /// #[derive(Debug)]
2503 /// struct MyCollection(Vec<i32>);
2504 ///
2505 /// // Let's give it some methods so we can create one and add things
2506 /// // to it.
2507 /// impl MyCollection {
2508 ///     fn new() -> MyCollection {
2509 ///         MyCollection(Vec::new())
2510 ///     }
2511 ///
2512 ///     fn add(&mut self, elem: i32) {
2513 ///         self.0.push(elem);
2514 ///     }
2515 /// }
2516 ///
2517 /// // since MyCollection has a list of i32s, we implement Extend for i32
2518 /// impl Extend<i32> for MyCollection {
2519 ///
2520 ///     // This is a bit simpler with the concrete type signature: we can call
2521 ///     // extend on anything which can be turned into an Iterator which gives
2522 ///     // us i32s. Because we need i32s to put into MyCollection.
2523 ///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2524 ///
2525 ///         // The implementation is very straightforward: loop through the
2526 ///         // iterator, and add() each element to ourselves.
2527 ///         for elem in iterable {
2528 ///             self.add(elem);
2529 ///         }
2530 ///     }
2531 /// }
2532 ///
2533 /// let mut c = MyCollection::new();
2534 ///
2535 /// c.add(5);
2536 /// c.add(6);
2537 /// c.add(7);
2538 ///
2539 /// // let's extend our collection with three more numbers
2540 /// c.extend(vec![1, 2, 3]);
2541 ///
2542 /// // we've added these elements onto the end
2543 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2544 /// ```
2545 #[stable(feature = "rust1", since = "1.0.0")]
2546 pub trait Extend<A> {
2547     /// Extends a collection with the contents of an iterator.
2548     ///
2549     /// As this is the only method for this trait, the [trait-level] docs
2550     /// contain more details.
2551     ///
2552     /// [trait-level]: trait.Extend.html
2553     ///
2554     /// # Examples
2555     ///
2556     /// Basic usage:
2557     ///
2558     /// ```
2559     /// // You can extend a String with some chars:
2560     /// let mut message = String::from("The first three letters are: ");
2561     ///
2562     /// message.extend(['a', 'b', 'c'].iter());
2563     ///
2564     /// assert_eq!("abc", &message[29..32]);
2565     /// ```
2566     #[stable(feature = "rust1", since = "1.0.0")]
2567     fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
2568 }
2569
2570 /// An iterator able to yield elements from both ends.
2571 ///
2572 /// Something that implements `DoubleEndedIterator` has one extra capability
2573 /// over something that implements [`Iterator`]: the ability to also take
2574 /// `Item`s from the back, as well as the front.
2575 ///
2576 /// It is important to note that both back and forth work on the same range,
2577 /// and do not cross: iteration is over when they meet in the middle.
2578 ///
2579 /// [`Iterator`]: trait.Iterator.html
2580 /// # Examples
2581 ///
2582 /// Basic usage:
2583 ///
2584 /// ```
2585 /// let numbers = vec![1, 2, 3];
2586 ///
2587 /// let mut iter = numbers.iter();
2588 ///
2589 /// let n = iter.next();
2590 /// assert_eq!(Some(&1), n);
2591 ///
2592 /// let n = iter.next_back();
2593 /// assert_eq!(Some(&3), n);
2594 ///
2595 /// let n = iter.next_back();
2596 /// assert_eq!(Some(&2), n);
2597 ///
2598 /// let n = iter.next();
2599 /// assert_eq!(None, n);
2600 ///
2601 /// let n = iter.next_back();
2602 /// assert_eq!(None, n);
2603 /// ```
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 pub trait DoubleEndedIterator: Iterator {
2606     /// An iterator able to yield elements from both ends.
2607     ///
2608     /// As this is the only method for this trait, the [trait-level] docs
2609     /// contain more details.
2610     ///
2611     /// [trait-level]: trait.DoubleEndedIterator.html
2612     ///
2613     /// # Examples
2614     ///
2615     /// Basic usage:
2616     ///
2617     /// ```
2618     /// let numbers = vec![1, 2, 3];
2619     ///
2620     /// let mut iter = numbers.iter();
2621     ///
2622     /// let n = iter.next();
2623     /// assert_eq!(Some(&1), n);
2624     ///
2625     /// let n = iter.next_back();
2626     /// assert_eq!(Some(&3), n);
2627     ///
2628     /// let n = iter.next_back();
2629     /// assert_eq!(Some(&2), n);
2630     ///
2631     /// let n = iter.next();
2632     /// assert_eq!(None, n);
2633     ///
2634     /// let n = iter.next_back();
2635     /// assert_eq!(None, n);
2636     /// ```
2637     #[stable(feature = "rust1", since = "1.0.0")]
2638     fn next_back(&mut self) -> Option<Self::Item>;
2639 }
2640
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2643     fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2644 }
2645
2646 /// An iterator that knows its exact length.
2647 ///
2648 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2649 /// If an iterator knows how many times it can iterate, providing access to
2650 /// that information can be useful. For example, if you want to iterate
2651 /// backwards, a good start is to know where the end is.
2652 ///
2653 /// When implementing an `ExactSizeIterator`, You must also implement
2654 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2655 /// return the exact size of the iterator.
2656 ///
2657 /// [`Iterator`]: trait.Iterator.html
2658 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2659 ///
2660 /// The [`len()`] method has a default implementation, so you usually shouldn't
2661 /// implement it. However, you may be able to provide a more performant
2662 /// implementation than the default, so overriding it in this case makes sense.
2663 ///
2664 /// [`len()`]: #method.len
2665 ///
2666 /// # Examples
2667 ///
2668 /// Basic usage:
2669 ///
2670 /// ```
2671 /// // a finite range knows exactly how many times it will iterate
2672 /// let five = (0..5);
2673 ///
2674 /// assert_eq!(5, five.len());
2675 /// ```
2676 ///
2677 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2678 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2679 ///
2680 /// [moddocs]: index.html
2681 ///
2682 /// ```
2683 /// # struct Counter {
2684 /// #     count: usize,
2685 /// # }
2686 /// # impl Counter {
2687 /// #     fn new() -> Counter {
2688 /// #         Counter { count: 0 }
2689 /// #     }
2690 /// # }
2691 /// # impl Iterator for Counter {
2692 /// #     type Item = usize;
2693 /// #     fn next(&mut self) -> Option<usize> {
2694 /// #         self.count += 1;
2695 /// #         if self.count < 6 {
2696 /// #             Some(self.count)
2697 /// #         } else {
2698 /// #             None
2699 /// #         }
2700 /// #     }
2701 /// # }
2702 /// impl ExactSizeIterator for Counter {
2703 ///     // We already have the number of iterations, so we can use it directly.
2704 ///     fn len(&self) -> usize {
2705 ///         self.count
2706 ///     }
2707 /// }
2708 ///
2709 /// // And now we can use it!
2710 ///
2711 /// let counter = Counter::new();
2712 ///
2713 /// assert_eq!(0, counter.len());
2714 /// ```
2715 #[stable(feature = "rust1", since = "1.0.0")]
2716 pub trait ExactSizeIterator: Iterator {
2717     #[inline]
2718     #[stable(feature = "rust1", since = "1.0.0")]
2719     /// Returns the exact number of times the iterator will iterate.
2720     ///
2721     /// This method has a default implementation, so you usually should not
2722     /// implement it directly. However, if you can provide a more efficient
2723     /// implementation, you can do so. See the [trait-level] docs for an
2724     /// example.
2725     ///
2726     /// [trait-level]: trait.ExactSizeIterator.html
2727     ///
2728     /// # Examples
2729     ///
2730     /// Basic usage:
2731     ///
2732     /// ```
2733     /// // a finite range knows exactly how many times it will iterate
2734     /// let five = (0..5);
2735     ///
2736     /// assert_eq!(5, five.len());
2737     /// ```
2738     fn len(&self) -> usize {
2739         let (lower, upper) = self.size_hint();
2740         // Note: This assertion is overly defensive, but it checks the invariant
2741         // guaranteed by the trait. If this trait were rust-internal,
2742         // we could use debug_assert!; assert_eq! will check all Rust user
2743         // implementations too.
2744         assert_eq!(upper, Some(lower));
2745         lower
2746     }
2747 }
2748
2749 #[stable(feature = "rust1", since = "1.0.0")]
2750 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2751
2752 // All adaptors that preserve the size of the wrapped iterator are fine
2753 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2754 #[stable(feature = "rust1", since = "1.0.0")]
2755 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2756 #[stable(feature = "rust1", since = "1.0.0")]
2757 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2758     F: FnMut(&I::Item),
2759 {}
2760 #[stable(feature = "rust1", since = "1.0.0")]
2761 impl<I> ExactSizeIterator for Rev<I>
2762     where I: ExactSizeIterator + DoubleEndedIterator {}
2763 #[stable(feature = "rust1", since = "1.0.0")]
2764 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2765     F: FnMut(I::Item) -> B,
2766 {}
2767 #[stable(feature = "rust1", since = "1.0.0")]
2768 impl<A, B> ExactSizeIterator for Zip<A, B>
2769     where A: ExactSizeIterator, B: ExactSizeIterator {}
2770
2771 /// An double-ended iterator with the direction inverted.
2772 ///
2773 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2774 /// documentation for more.
2775 ///
2776 /// [`rev()`]: trait.Iterator.html#method.rev
2777 /// [`Iterator`]: trait.Iterator.html
2778 #[derive(Clone)]
2779 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2780 #[stable(feature = "rust1", since = "1.0.0")]
2781 pub struct Rev<T> {
2782     iter: T
2783 }
2784
2785 #[stable(feature = "rust1", since = "1.0.0")]
2786 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2787     type Item = <I as Iterator>::Item;
2788
2789     #[inline]
2790     fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2791     #[inline]
2792     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2793 }
2794
2795 #[stable(feature = "rust1", since = "1.0.0")]
2796 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2797     #[inline]
2798     fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2799 }
2800
2801 /// An iterator that clones the elements of an underlying iterator.
2802 ///
2803 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2804 /// documentation for more.
2805 ///
2806 /// [`cloned()`]: trait.Iterator.html#method.cloned
2807 /// [`Iterator`]: trait.Iterator.html
2808 #[stable(feature = "iter_cloned", since = "1.1.0")]
2809 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2810 #[derive(Clone)]
2811 pub struct Cloned<I> {
2812     it: I,
2813 }
2814
2815 #[stable(feature = "rust1", since = "1.0.0")]
2816 impl<'a, I, T: 'a> Iterator for Cloned<I>
2817     where I: Iterator<Item=&'a T>, T: Clone
2818 {
2819     type Item = T;
2820
2821     fn next(&mut self) -> Option<T> {
2822         self.it.next().cloned()
2823     }
2824
2825     fn size_hint(&self) -> (usize, Option<usize>) {
2826         self.it.size_hint()
2827     }
2828 }
2829
2830 #[stable(feature = "rust1", since = "1.0.0")]
2831 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
2832     where I: DoubleEndedIterator<Item=&'a T>, T: Clone
2833 {
2834     fn next_back(&mut self) -> Option<T> {
2835         self.it.next_back().cloned()
2836     }
2837 }
2838
2839 #[stable(feature = "rust1", since = "1.0.0")]
2840 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
2841     where I: ExactSizeIterator<Item=&'a T>, T: Clone
2842 {}
2843
2844 /// An iterator that repeats endlessly.
2845 ///
2846 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
2847 /// documentation for more.
2848 ///
2849 /// [`cycle()`]: trait.Iterator.html#method.cycle
2850 /// [`Iterator`]: trait.Iterator.html
2851 #[derive(Clone)]
2852 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 pub struct Cycle<I> {
2855     orig: I,
2856     iter: I,
2857 }
2858
2859 #[stable(feature = "rust1", since = "1.0.0")]
2860 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
2861     type Item = <I as Iterator>::Item;
2862
2863     #[inline]
2864     fn next(&mut self) -> Option<<I as Iterator>::Item> {
2865         match self.iter.next() {
2866             None => { self.iter = self.orig.clone(); self.iter.next() }
2867             y => y
2868         }
2869     }
2870
2871     #[inline]
2872     fn size_hint(&self) -> (usize, Option<usize>) {
2873         // the cycle iterator is either empty or infinite
2874         match self.orig.size_hint() {
2875             sz @ (0, Some(0)) => sz,
2876             (0, _) => (0, None),
2877             _ => (usize::MAX, None)
2878         }
2879     }
2880 }
2881
2882 /// An iterator that strings two iterators together.
2883 ///
2884 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
2885 /// documentation for more.
2886 ///
2887 /// [`chain()`]: trait.Iterator.html#method.chain
2888 /// [`Iterator`]: trait.Iterator.html
2889 #[derive(Clone)]
2890 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2891 #[stable(feature = "rust1", since = "1.0.0")]
2892 pub struct Chain<A, B> {
2893     a: A,
2894     b: B,
2895     state: ChainState,
2896 }
2897
2898 // The iterator protocol specifies that iteration ends with the return value
2899 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
2900 // further calls return. The chain adaptor must account for this since it uses
2901 // two subiterators.
2902 //
2903 //  It uses three states:
2904 //
2905 //  - Both: `a` and `b` are remaining
2906 //  - Front: `a` remaining
2907 //  - Back: `b` remaining
2908 //
2909 //  The fourth state (neither iterator is remaining) only occurs after Chain has
2910 //  returned None once, so we don't need to store this state.
2911 #[derive(Clone)]
2912 enum ChainState {
2913     // both front and back iterator are remaining
2914     Both,
2915     // only front is remaining
2916     Front,
2917     // only back is remaining
2918     Back,
2919 }
2920
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 impl<A, B> Iterator for Chain<A, B> where
2923     A: Iterator,
2924     B: Iterator<Item = A::Item>
2925 {
2926     type Item = A::Item;
2927
2928     #[inline]
2929     fn next(&mut self) -> Option<A::Item> {
2930         match self.state {
2931             ChainState::Both => match self.a.next() {
2932                 elt @ Some(..) => elt,
2933                 None => {
2934                     self.state = ChainState::Back;
2935                     self.b.next()
2936                 }
2937             },
2938             ChainState::Front => self.a.next(),
2939             ChainState::Back => self.b.next(),
2940         }
2941     }
2942
2943     #[inline]
2944     fn count(self) -> usize {
2945         match self.state {
2946             ChainState::Both => self.a.count() + self.b.count(),
2947             ChainState::Front => self.a.count(),
2948             ChainState::Back => self.b.count(),
2949         }
2950     }
2951
2952     #[inline]
2953     fn nth(&mut self, mut n: usize) -> Option<A::Item> {
2954         match self.state {
2955             ChainState::Both | ChainState::Front => {
2956                 for x in self.a.by_ref() {
2957                     if n == 0 {
2958                         return Some(x)
2959                     }
2960                     n -= 1;
2961                 }
2962                 if let ChainState::Both = self.state {
2963                     self.state = ChainState::Back;
2964                 }
2965             }
2966             ChainState::Back => {}
2967         }
2968         if let ChainState::Back = self.state {
2969             self.b.nth(n)
2970         } else {
2971             None
2972         }
2973     }
2974
2975     #[inline]
2976     fn last(self) -> Option<A::Item> {
2977         match self.state {
2978             ChainState::Both => {
2979                 // Must exhaust a before b.
2980                 let a_last = self.a.last();
2981                 let b_last = self.b.last();
2982                 b_last.or(a_last)
2983             },
2984             ChainState::Front => self.a.last(),
2985             ChainState::Back => self.b.last()
2986         }
2987     }
2988
2989     #[inline]
2990     fn size_hint(&self) -> (usize, Option<usize>) {
2991         let (a_lower, a_upper) = self.a.size_hint();
2992         let (b_lower, b_upper) = self.b.size_hint();
2993
2994         let lower = a_lower.saturating_add(b_lower);
2995
2996         let upper = match (a_upper, b_upper) {
2997             (Some(x), Some(y)) => x.checked_add(y),
2998             _ => None
2999         };
3000
3001         (lower, upper)
3002     }
3003 }
3004
3005 #[stable(feature = "rust1", since = "1.0.0")]
3006 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3007     A: DoubleEndedIterator,
3008     B: DoubleEndedIterator<Item=A::Item>,
3009 {
3010     #[inline]
3011     fn next_back(&mut self) -> Option<A::Item> {
3012         match self.state {
3013             ChainState::Both => match self.b.next_back() {
3014                 elt @ Some(..) => elt,
3015                 None => {
3016                     self.state = ChainState::Front;
3017                     self.a.next_back()
3018                 }
3019             },
3020             ChainState::Front => self.a.next_back(),
3021             ChainState::Back => self.b.next_back(),
3022         }
3023     }
3024 }
3025
3026 /// An iterator that iterates two other iterators simultaneously.
3027 ///
3028 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3029 /// documentation for more.
3030 ///
3031 /// [`zip()`]: trait.Iterator.html#method.zip
3032 /// [`Iterator`]: trait.Iterator.html
3033 #[derive(Clone)]
3034 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3035 #[stable(feature = "rust1", since = "1.0.0")]
3036 pub struct Zip<A, B> {
3037     a: A,
3038     b: B
3039 }
3040
3041 #[stable(feature = "rust1", since = "1.0.0")]
3042 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3043 {
3044     type Item = (A::Item, B::Item);
3045
3046     #[inline]
3047     fn next(&mut self) -> Option<(A::Item, B::Item)> {
3048         self.a.next().and_then(|x| {
3049             self.b.next().and_then(|y| {
3050                 Some((x, y))
3051             })
3052         })
3053     }
3054
3055     #[inline]
3056     fn size_hint(&self) -> (usize, Option<usize>) {
3057         let (a_lower, a_upper) = self.a.size_hint();
3058         let (b_lower, b_upper) = self.b.size_hint();
3059
3060         let lower = cmp::min(a_lower, b_lower);
3061
3062         let upper = match (a_upper, b_upper) {
3063             (Some(x), Some(y)) => Some(cmp::min(x,y)),
3064             (Some(x), None) => Some(x),
3065             (None, Some(y)) => Some(y),
3066             (None, None) => None
3067         };
3068
3069         (lower, upper)
3070     }
3071 }
3072
3073 #[stable(feature = "rust1", since = "1.0.0")]
3074 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3075     A: DoubleEndedIterator + ExactSizeIterator,
3076     B: DoubleEndedIterator + ExactSizeIterator,
3077 {
3078     #[inline]
3079     fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3080         let a_sz = self.a.len();
3081         let b_sz = self.b.len();
3082         if a_sz != b_sz {
3083             // Adjust a, b to equal length
3084             if a_sz > b_sz {
3085                 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3086             } else {
3087                 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3088             }
3089         }
3090         match (self.a.next_back(), self.b.next_back()) {
3091             (Some(x), Some(y)) => Some((x, y)),
3092             (None, None) => None,
3093             _ => unreachable!(),
3094         }
3095     }
3096 }
3097
3098 /// An iterator that maps the values of `iter` with `f`.
3099 ///
3100 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3101 /// documentation for more.
3102 ///
3103 /// [`map()`]: trait.Iterator.html#method.map
3104 /// [`Iterator`]: trait.Iterator.html
3105 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3106 #[stable(feature = "rust1", since = "1.0.0")]
3107 #[derive(Clone)]
3108 pub struct Map<I, F> {
3109     iter: I,
3110     f: F,
3111 }
3112
3113 #[stable(feature = "rust1", since = "1.0.0")]
3114 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3115     type Item = B;
3116
3117     #[inline]
3118     fn next(&mut self) -> Option<B> {
3119         self.iter.next().map(&mut self.f)
3120     }
3121
3122     #[inline]
3123     fn size_hint(&self) -> (usize, Option<usize>) {
3124         self.iter.size_hint()
3125     }
3126 }
3127
3128 #[stable(feature = "rust1", since = "1.0.0")]
3129 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3130     F: FnMut(I::Item) -> B,
3131 {
3132     #[inline]
3133     fn next_back(&mut self) -> Option<B> {
3134         self.iter.next_back().map(&mut self.f)
3135     }
3136 }
3137
3138 /// An iterator that filters the elements of `iter` with `predicate`.
3139 ///
3140 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3141 /// documentation for more.
3142 ///
3143 /// [`filter()`]: trait.Iterator.html#method.filter
3144 /// [`Iterator`]: trait.Iterator.html
3145 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3146 #[stable(feature = "rust1", since = "1.0.0")]
3147 #[derive(Clone)]
3148 pub struct Filter<I, P> {
3149     iter: I,
3150     predicate: P,
3151 }
3152
3153 #[stable(feature = "rust1", since = "1.0.0")]
3154 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3155     type Item = I::Item;
3156
3157     #[inline]
3158     fn next(&mut self) -> Option<I::Item> {
3159         for x in self.iter.by_ref() {
3160             if (self.predicate)(&x) {
3161                 return Some(x);
3162             }
3163         }
3164         None
3165     }
3166
3167     #[inline]
3168     fn size_hint(&self) -> (usize, Option<usize>) {
3169         let (_, upper) = self.iter.size_hint();
3170         (0, upper) // can't know a lower bound, due to the predicate
3171     }
3172 }
3173
3174 #[stable(feature = "rust1", since = "1.0.0")]
3175 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3176     where P: FnMut(&I::Item) -> bool,
3177 {
3178     #[inline]
3179     fn next_back(&mut self) -> Option<I::Item> {
3180         for x in self.iter.by_ref().rev() {
3181             if (self.predicate)(&x) {
3182                 return Some(x);
3183             }
3184         }
3185         None
3186     }
3187 }
3188
3189 /// An iterator that uses `f` to both filter and map elements from `iter`.
3190 ///
3191 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3192 /// documentation for more.
3193 ///
3194 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3195 /// [`Iterator`]: trait.Iterator.html
3196 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3197 #[stable(feature = "rust1", since = "1.0.0")]
3198 #[derive(Clone)]
3199 pub struct FilterMap<I, F> {
3200     iter: I,
3201     f: F,
3202 }
3203
3204 #[stable(feature = "rust1", since = "1.0.0")]
3205 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3206     where F: FnMut(I::Item) -> Option<B>,
3207 {
3208     type Item = B;
3209
3210     #[inline]
3211     fn next(&mut self) -> Option<B> {
3212         for x in self.iter.by_ref() {
3213             if let Some(y) = (self.f)(x) {
3214                 return Some(y);
3215             }
3216         }
3217         None
3218     }
3219
3220     #[inline]
3221     fn size_hint(&self) -> (usize, Option<usize>) {
3222         let (_, upper) = self.iter.size_hint();
3223         (0, upper) // can't know a lower bound, due to the predicate
3224     }
3225 }
3226
3227 #[stable(feature = "rust1", since = "1.0.0")]
3228 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3229     where F: FnMut(I::Item) -> Option<B>,
3230 {
3231     #[inline]
3232     fn next_back(&mut self) -> Option<B> {
3233         for x in self.iter.by_ref().rev() {
3234             if let Some(y) = (self.f)(x) {
3235                 return Some(y);
3236             }
3237         }
3238         None
3239     }
3240 }
3241
3242 /// An iterator that yields the current count and the element during iteration.
3243 ///
3244 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3245 /// documentation for more.
3246 ///
3247 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3248 /// [`Iterator`]: trait.Iterator.html
3249 #[derive(Clone)]
3250 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3251 #[stable(feature = "rust1", since = "1.0.0")]
3252 pub struct Enumerate<I> {
3253     iter: I,
3254     count: usize,
3255 }
3256
3257 #[stable(feature = "rust1", since = "1.0.0")]
3258 impl<I> Iterator for Enumerate<I> where I: Iterator {
3259     type Item = (usize, <I as Iterator>::Item);
3260
3261     /// # Overflow Behavior
3262     ///
3263     /// The method does no guarding against overflows, so enumerating more than
3264     /// `usize::MAX` elements either produces the wrong result or panics. If
3265     /// debug assertions are enabled, a panic is guaranteed.
3266     ///
3267     /// # Panics
3268     ///
3269     /// Might panic if the index of the element overflows a `usize`.
3270     #[inline]
3271     fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3272         self.iter.next().map(|a| {
3273             let ret = (self.count, a);
3274             // Possible undefined overflow.
3275             self.count += 1;
3276             ret
3277         })
3278     }
3279
3280     #[inline]
3281     fn size_hint(&self) -> (usize, Option<usize>) {
3282         self.iter.size_hint()
3283     }
3284
3285     #[inline]
3286     fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3287         self.iter.nth(n).map(|a| {
3288             let i = self.count + n;
3289             self.count = i + 1;
3290             (i, a)
3291         })
3292     }
3293
3294     #[inline]
3295     fn count(self) -> usize {
3296         self.iter.count()
3297     }
3298 }
3299
3300 #[stable(feature = "rust1", since = "1.0.0")]
3301 impl<I> DoubleEndedIterator for Enumerate<I> where
3302     I: ExactSizeIterator + DoubleEndedIterator
3303 {
3304     #[inline]
3305     fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3306         self.iter.next_back().map(|a| {
3307             let len = self.iter.len();
3308             // Can safely add, `ExactSizeIterator` promises that the number of
3309             // elements fits into a `usize`.
3310             (self.count + len, a)
3311         })
3312     }
3313 }
3314
3315 /// An iterator with a `peek()` that returns an optional reference to the next
3316 /// element.
3317 ///
3318 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3319 /// documentation for more.
3320 ///
3321 /// [`peekable()`]: trait.Iterator.html#method.peekable
3322 /// [`Iterator`]: trait.Iterator.html
3323 #[derive(Clone)]
3324 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3325 #[stable(feature = "rust1", since = "1.0.0")]
3326 pub struct Peekable<I: Iterator> {
3327     iter: I,
3328     peeked: Option<I::Item>,
3329 }
3330
3331 #[stable(feature = "rust1", since = "1.0.0")]
3332 impl<I: Iterator> Iterator for Peekable<I> {
3333     type Item = I::Item;
3334
3335     #[inline]
3336     fn next(&mut self) -> Option<I::Item> {
3337         match self.peeked {
3338             Some(_) => self.peeked.take(),
3339             None => self.iter.next(),
3340         }
3341     }
3342
3343     #[inline]
3344     fn count(self) -> usize {
3345         (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3346     }
3347
3348     #[inline]
3349     fn nth(&mut self, n: usize) -> Option<I::Item> {
3350         match self.peeked {
3351             Some(_) if n == 0 => self.peeked.take(),
3352             Some(_) => {
3353                 self.peeked = None;
3354                 self.iter.nth(n-1)
3355             },
3356             None => self.iter.nth(n)
3357         }
3358     }
3359
3360     #[inline]
3361     fn last(self) -> Option<I::Item> {
3362         self.iter.last().or(self.peeked)
3363     }
3364
3365     #[inline]
3366     fn size_hint(&self) -> (usize, Option<usize>) {
3367         let (lo, hi) = self.iter.size_hint();
3368         if self.peeked.is_some() {
3369             let lo = lo.saturating_add(1);
3370             let hi = hi.and_then(|x| x.checked_add(1));
3371             (lo, hi)
3372         } else {
3373             (lo, hi)
3374         }
3375     }
3376 }
3377
3378 #[stable(feature = "rust1", since = "1.0.0")]
3379 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3380
3381 #[stable(feature = "rust1", since = "1.0.0")]
3382 impl<I: Iterator> Peekable<I> {
3383     /// Returns a reference to the next() value without advancing the iterator.
3384     ///
3385     /// The `peek()` method will return the value that a call to [`next()`] would
3386     /// return, but does not advance the iterator. Like [`next()`], if there is
3387     /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3388     /// will return `None`.
3389     ///
3390     /// [`next()`]: trait.Iterator.html#tymethod.next
3391     ///
3392     /// Because `peek()` returns reference, and many iterators iterate over
3393     /// references, this leads to a possibly confusing situation where the
3394     /// return value is a double reference. You can see this effect in the
3395     /// examples below, with `&&i32`.
3396     ///
3397     /// # Examples
3398     ///
3399     /// Basic usage:
3400     ///
3401     /// ```
3402     /// let xs = [1, 2, 3];
3403     ///
3404     /// let mut iter = xs.iter().peekable();
3405     ///
3406     /// // peek() lets us see into the future
3407     /// assert_eq!(iter.peek(), Some(&&1));
3408     /// assert_eq!(iter.next(), Some(&1));
3409     ///
3410     /// assert_eq!(iter.next(), Some(&2));
3411     ///
3412     /// // we can peek() multiple times, the itererator won't advance
3413     /// assert_eq!(iter.peek(), Some(&&3));
3414     /// assert_eq!(iter.peek(), Some(&&3));
3415     ///
3416     /// assert_eq!(iter.next(), Some(&3));
3417     ///
3418     /// // after the itererator is finished, so is peek()
3419     /// assert_eq!(iter.peek(), None);
3420     /// assert_eq!(iter.next(), None);
3421     /// ```
3422     #[inline]
3423     #[stable(feature = "rust1", since = "1.0.0")]
3424     pub fn peek(&mut self) -> Option<&I::Item> {
3425         if self.peeked.is_none() {
3426             self.peeked = self.iter.next();
3427         }
3428         match self.peeked {
3429             Some(ref value) => Some(value),
3430             None => None,
3431         }
3432     }
3433
3434     /// Checks if the iterator has finished iterating.
3435     ///
3436     /// Returns `true` if there are no more elements in the iterator, and
3437     /// `false` if there are.
3438     ///
3439     /// # Examples
3440     ///
3441     /// Basic usage:
3442     ///
3443     /// ```
3444     /// #![feature(core)]
3445     ///
3446     /// let xs = [1, 2, 3];
3447     ///
3448     /// let mut iter = xs.iter().peekable();
3449     ///
3450     /// // there are still elements to iterate over
3451     /// assert_eq!(iter.is_empty(), false);
3452     ///
3453     /// // let's consume the iterator
3454     /// iter.next();
3455     /// iter.next();
3456     /// iter.next();
3457     ///
3458     /// assert_eq!(iter.is_empty(), true);
3459     /// ```
3460     #[inline]
3461     pub fn is_empty(&mut self) -> bool {
3462         self.peek().is_none()
3463     }
3464 }
3465
3466 /// An iterator that rejects elements while `predicate` is true.
3467 ///
3468 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3469 /// documentation for more.
3470 ///
3471 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3472 /// [`Iterator`]: trait.Iterator.html
3473 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3474 #[stable(feature = "rust1", since = "1.0.0")]
3475 #[derive(Clone)]
3476 pub struct SkipWhile<I, P> {
3477     iter: I,
3478     flag: bool,
3479     predicate: P,
3480 }
3481
3482 #[stable(feature = "rust1", since = "1.0.0")]
3483 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3484     where P: FnMut(&I::Item) -> bool
3485 {
3486     type Item = I::Item;
3487
3488     #[inline]
3489     fn next(&mut self) -> Option<I::Item> {
3490         for x in self.iter.by_ref() {
3491             if self.flag || !(self.predicate)(&x) {
3492                 self.flag = true;
3493                 return Some(x);
3494             }
3495         }
3496         None
3497     }
3498
3499     #[inline]
3500     fn size_hint(&self) -> (usize, Option<usize>) {
3501         let (_, upper) = self.iter.size_hint();
3502         (0, upper) // can't know a lower bound, due to the predicate
3503     }
3504 }
3505
3506 /// An iterator that only accepts elements while `predicate` is true.
3507 ///
3508 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3509 /// documentation for more.
3510 ///
3511 /// [`take_while()`]: trait.Iterator.html#method.take_while
3512 /// [`Iterator`]: trait.Iterator.html
3513 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3514 #[stable(feature = "rust1", since = "1.0.0")]
3515 #[derive(Clone)]
3516 pub struct TakeWhile<I, P> {
3517     iter: I,
3518     flag: bool,
3519     predicate: P,
3520 }
3521
3522 #[stable(feature = "rust1", since = "1.0.0")]
3523 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3524     where P: FnMut(&I::Item) -> bool
3525 {
3526     type Item = I::Item;
3527
3528     #[inline]
3529     fn next(&mut self) -> Option<I::Item> {
3530         if self.flag {
3531             None
3532         } else {
3533             self.iter.next().and_then(|x| {
3534                 if (self.predicate)(&x) {
3535                     Some(x)
3536                 } else {
3537                     self.flag = true;
3538                     None
3539                 }
3540             })
3541         }
3542     }
3543
3544     #[inline]
3545     fn size_hint(&self) -> (usize, Option<usize>) {
3546         let (_, upper) = self.iter.size_hint();
3547         (0, upper) // can't know a lower bound, due to the predicate
3548     }
3549 }
3550
3551 /// An iterator that skips over `n` elements of `iter`.
3552 ///
3553 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3554 /// documentation for more.
3555 ///
3556 /// [`skip()`]: trait.Iterator.html#method.skip
3557 /// [`Iterator`]: trait.Iterator.html
3558 #[derive(Clone)]
3559 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3560 #[stable(feature = "rust1", since = "1.0.0")]
3561 pub struct Skip<I> {
3562     iter: I,
3563     n: usize
3564 }
3565
3566 #[stable(feature = "rust1", since = "1.0.0")]
3567 impl<I> Iterator for Skip<I> where I: Iterator {
3568     type Item = <I as Iterator>::Item;
3569
3570     #[inline]
3571     fn next(&mut self) -> Option<I::Item> {
3572         if self.n == 0 {
3573             self.iter.next()
3574         } else {
3575             let old_n = self.n;
3576             self.n = 0;
3577             self.iter.nth(old_n)
3578         }
3579     }
3580
3581     #[inline]
3582     fn nth(&mut self, n: usize) -> Option<I::Item> {
3583         // Can't just add n + self.n due to overflow.
3584         if self.n == 0 {
3585             self.iter.nth(n)
3586         } else {
3587             let to_skip = self.n;
3588             self.n = 0;
3589             // nth(n) skips n+1
3590             if self.iter.nth(to_skip-1).is_none() {
3591                 return None;
3592             }
3593             self.iter.nth(n)
3594         }
3595     }
3596
3597     #[inline]
3598     fn count(self) -> usize {
3599         self.iter.count().saturating_sub(self.n)
3600     }
3601
3602     #[inline]
3603     fn last(mut self) -> Option<I::Item> {
3604         if self.n == 0 {
3605             self.iter.last()
3606         } else {
3607             let next = self.next();
3608             if next.is_some() {
3609                 // recurse. n should be 0.
3610                 self.last().or(next)
3611             } else {
3612                 None
3613             }
3614         }
3615     }
3616
3617     #[inline]
3618     fn size_hint(&self) -> (usize, Option<usize>) {
3619         let (lower, upper) = self.iter.size_hint();
3620
3621         let lower = lower.saturating_sub(self.n);
3622         let upper = upper.map(|x| x.saturating_sub(self.n));
3623
3624         (lower, upper)
3625     }
3626 }
3627
3628 #[stable(feature = "rust1", since = "1.0.0")]
3629 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3630
3631 /// An iterator that only iterates over the first `n` iterations of `iter`.
3632 ///
3633 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3634 /// documentation for more.
3635 ///
3636 /// [`take()`]: trait.Iterator.html#method.take
3637 /// [`Iterator`]: trait.Iterator.html
3638 #[derive(Clone)]
3639 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3640 #[stable(feature = "rust1", since = "1.0.0")]
3641 pub struct Take<I> {
3642     iter: I,
3643     n: usize
3644 }
3645
3646 #[stable(feature = "rust1", since = "1.0.0")]
3647 impl<I> Iterator for Take<I> where I: Iterator{
3648     type Item = <I as Iterator>::Item;
3649
3650     #[inline]
3651     fn next(&mut self) -> Option<<I as Iterator>::Item> {
3652         if self.n != 0 {
3653             self.n -= 1;
3654             self.iter.next()
3655         } else {
3656             None
3657         }
3658     }
3659
3660     #[inline]
3661     fn nth(&mut self, n: usize) -> Option<I::Item> {
3662         if self.n > n {
3663             self.n -= n + 1;
3664             self.iter.nth(n)
3665         } else {
3666             if self.n > 0 {
3667                 self.iter.nth(self.n - 1);
3668                 self.n = 0;
3669             }
3670             None
3671         }
3672     }
3673
3674     #[inline]
3675     fn size_hint(&self) -> (usize, Option<usize>) {
3676         let (lower, upper) = self.iter.size_hint();
3677
3678         let lower = cmp::min(lower, self.n);
3679
3680         let upper = match upper {
3681             Some(x) if x < self.n => Some(x),
3682             _ => Some(self.n)
3683         };
3684
3685         (lower, upper)
3686     }
3687 }
3688
3689 #[stable(feature = "rust1", since = "1.0.0")]
3690 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3691
3692
3693 /// An iterator to maintain state while iterating another iterator.
3694 ///
3695 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3696 /// documentation for more.
3697 ///
3698 /// [`scan()`]: trait.Iterator.html#method.scan
3699 /// [`Iterator`]: trait.Iterator.html
3700 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3701 #[stable(feature = "rust1", since = "1.0.0")]
3702 #[derive(Clone)]
3703 pub struct Scan<I, St, F> {
3704     iter: I,
3705     f: F,
3706     state: St,
3707 }
3708
3709 #[stable(feature = "rust1", since = "1.0.0")]
3710 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3711     I: Iterator,
3712     F: FnMut(&mut St, I::Item) -> Option<B>,
3713 {
3714     type Item = B;
3715
3716     #[inline]
3717     fn next(&mut self) -> Option<B> {
3718         self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3719     }
3720
3721     #[inline]
3722     fn size_hint(&self) -> (usize, Option<usize>) {
3723         let (_, upper) = self.iter.size_hint();
3724         (0, upper) // can't know a lower bound, due to the scan function
3725     }
3726 }
3727
3728 /// An iterator that maps each element to an iterator, and yields the elements
3729 /// of the produced iterators.
3730 ///
3731 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3732 /// documentation for more.
3733 ///
3734 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
3735 /// [`Iterator`]: trait.Iterator.html
3736 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3737 #[stable(feature = "rust1", since = "1.0.0")]
3738 #[derive(Clone)]
3739 pub struct FlatMap<I, U: IntoIterator, F> {
3740     iter: I,
3741     f: F,
3742     frontiter: Option<U::IntoIter>,
3743     backiter: Option<U::IntoIter>,
3744 }
3745
3746 #[stable(feature = "rust1", since = "1.0.0")]
3747 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
3748     where F: FnMut(I::Item) -> U,
3749 {
3750     type Item = U::Item;
3751
3752     #[inline]
3753     fn next(&mut self) -> Option<U::Item> {
3754         loop {
3755             if let Some(ref mut inner) = self.frontiter {
3756                 if let Some(x) = inner.by_ref().next() {
3757                     return Some(x)
3758                 }
3759             }
3760             match self.iter.next().map(&mut self.f) {
3761                 None => return self.backiter.as_mut().and_then(|it| it.next()),
3762                 next => self.frontiter = next.map(IntoIterator::into_iter),
3763             }
3764         }
3765     }
3766
3767     #[inline]
3768     fn size_hint(&self) -> (usize, Option<usize>) {
3769         let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3770         let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3771         let lo = flo.saturating_add(blo);
3772         match (self.iter.size_hint(), fhi, bhi) {
3773             ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
3774             _ => (lo, None)
3775         }
3776     }
3777 }
3778
3779 #[stable(feature = "rust1", since = "1.0.0")]
3780 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
3781     F: FnMut(I::Item) -> U,
3782     U: IntoIterator,
3783     U::IntoIter: DoubleEndedIterator
3784 {
3785     #[inline]
3786     fn next_back(&mut self) -> Option<U::Item> {
3787         loop {
3788             if let Some(ref mut inner) = self.backiter {
3789                 if let Some(y) = inner.next_back() {
3790                     return Some(y)
3791                 }
3792             }
3793             match self.iter.next_back().map(&mut self.f) {
3794                 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
3795                 next => self.backiter = next.map(IntoIterator::into_iter),
3796             }
3797         }
3798     }
3799 }
3800
3801 /// An iterator that yields `None` forever after the underlying iterator
3802 /// yields `None` once.
3803 ///
3804 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
3805 /// documentation for more.
3806 ///
3807 /// [`fuse()`]: trait.Iterator.html#method.fuse
3808 /// [`Iterator`]: trait.Iterator.html
3809 #[derive(Clone)]
3810 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3811 #[stable(feature = "rust1", since = "1.0.0")]
3812 pub struct Fuse<I> {
3813     iter: I,
3814     done: bool
3815 }
3816
3817 #[stable(feature = "rust1", since = "1.0.0")]
3818 impl<I> Iterator for Fuse<I> where I: Iterator {
3819     type Item = <I as Iterator>::Item;
3820
3821     #[inline]
3822     fn next(&mut self) -> Option<<I as Iterator>::Item> {
3823         if self.done {
3824             None
3825         } else {
3826             let next = self.iter.next();
3827             self.done = next.is_none();
3828             next
3829         }
3830     }
3831
3832     #[inline]
3833     fn nth(&mut self, n: usize) -> Option<I::Item> {
3834         if self.done {
3835             None
3836         } else {
3837             let nth = self.iter.nth(n);
3838             self.done = nth.is_none();
3839             nth
3840         }
3841     }
3842
3843     #[inline]
3844     fn last(self) -> Option<I::Item> {
3845         if self.done {
3846             None
3847         } else {
3848             self.iter.last()
3849         }
3850     }
3851
3852     #[inline]
3853     fn count(self) -> usize {
3854         if self.done {
3855             0
3856         } else {
3857             self.iter.count()
3858         }
3859     }
3860
3861     #[inline]
3862     fn size_hint(&self) -> (usize, Option<usize>) {
3863         if self.done {
3864             (0, Some(0))
3865         } else {
3866             self.iter.size_hint()
3867         }
3868     }
3869 }
3870
3871 #[stable(feature = "rust1", since = "1.0.0")]
3872 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
3873     #[inline]
3874     fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
3875         if self.done {
3876             None
3877         } else {
3878             let next = self.iter.next_back();
3879             self.done = next.is_none();
3880             next
3881         }
3882     }
3883 }
3884
3885 #[stable(feature = "rust1", since = "1.0.0")]
3886 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
3887
3888 /// An iterator that calls a function with a reference to each element before
3889 /// yielding it.
3890 ///
3891 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
3892 /// documentation for more.
3893 ///
3894 /// [`inspect()`]: trait.Iterator.html#method.inspect
3895 /// [`Iterator`]: trait.Iterator.html
3896 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3897 #[stable(feature = "rust1", since = "1.0.0")]
3898 #[derive(Clone)]
3899 pub struct Inspect<I, F> {
3900     iter: I,
3901     f: F,
3902 }
3903
3904 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
3905     #[inline]
3906     fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
3907         if let Some(ref a) = elt {
3908             (self.f)(a);
3909         }
3910
3911         elt
3912     }
3913 }
3914
3915 #[stable(feature = "rust1", since = "1.0.0")]
3916 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
3917     type Item = I::Item;
3918
3919     #[inline]
3920     fn next(&mut self) -> Option<I::Item> {
3921         let next = self.iter.next();
3922         self.do_inspect(next)
3923     }
3924
3925     #[inline]
3926     fn size_hint(&self) -> (usize, Option<usize>) {
3927         self.iter.size_hint()
3928     }
3929 }
3930
3931 #[stable(feature = "rust1", since = "1.0.0")]
3932 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
3933     where F: FnMut(&I::Item),
3934 {
3935     #[inline]
3936     fn next_back(&mut self) -> Option<I::Item> {
3937         let next = self.iter.next_back();
3938         self.do_inspect(next)
3939     }
3940 }
3941
3942 /// Objects that can be stepped over in both directions.
3943 ///
3944 /// The `steps_between` function provides a way to efficiently compare
3945 /// two `Step` objects.
3946 #[unstable(feature = "step_trait",
3947            reason = "likely to be replaced by finer-grained traits",
3948            issue = "27741")]
3949 pub trait Step: PartialOrd + Sized {
3950     /// Steps `self` if possible.
3951     fn step(&self, by: &Self) -> Option<Self>;
3952
3953     /// Returns the number of steps between two step objects. The count is
3954     /// inclusive of `start` and exclusive of `end`.
3955     ///
3956     /// Returns `None` if it is not possible to calculate `steps_between`
3957     /// without overflow.
3958     fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
3959 }
3960
3961 macro_rules! step_impl_unsigned {
3962     ($($t:ty)*) => ($(
3963         impl Step for $t {
3964             #[inline]
3965             fn step(&self, by: &$t) -> Option<$t> {
3966                 (*self).checked_add(*by)
3967             }
3968             #[inline]
3969             #[allow(trivial_numeric_casts)]
3970             fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
3971                 if *by == 0 { return None; }
3972                 if *start < *end {
3973                     // Note: We assume $t <= usize here
3974                     let diff = (*end - *start) as usize;
3975                     let by = *by as usize;
3976                     if diff % by > 0 {
3977                         Some(diff / by + 1)
3978                     } else {
3979                         Some(diff / by)
3980                     }
3981                 } else {
3982                     Some(0)
3983                 }
3984             }
3985         }
3986     )*)
3987 }
3988 macro_rules! step_impl_signed {
3989     ($($t:ty)*) => ($(
3990         impl Step for $t {
3991             #[inline]
3992             fn step(&self, by: &$t) -> Option<$t> {
3993                 (*self).checked_add(*by)
3994             }
3995             #[inline]
3996             #[allow(trivial_numeric_casts)]
3997             fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
3998                 if *by == 0 { return None; }
3999                 let diff: usize;
4000                 let by_u: usize;
4001                 if *by > 0 {
4002                     if *start >= *end {
4003                         return Some(0);
4004                     }
4005                     // Note: We assume $t <= isize here
4006                     // Use .wrapping_sub and cast to usize to compute the
4007                     // difference that may not fit inside the range of isize.
4008                     diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4009                     by_u = *by as usize;
4010                 } else {
4011                     if *start <= *end {
4012                         return Some(0);
4013                     }
4014                     diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4015                     by_u = (*by as isize).wrapping_mul(-1) as usize;
4016                 }
4017                 if diff % by_u > 0 {
4018                     Some(diff / by_u + 1)
4019                 } else {
4020                     Some(diff / by_u)
4021                 }
4022             }
4023         }
4024     )*)
4025 }
4026
4027 macro_rules! step_impl_no_between {
4028     ($($t:ty)*) => ($(
4029         impl Step for $t {
4030             #[inline]
4031             fn step(&self, by: &$t) -> Option<$t> {
4032                 (*self).checked_add(*by)
4033             }
4034             #[inline]
4035             fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4036                 None
4037             }
4038         }
4039     )*)
4040 }
4041
4042 step_impl_unsigned!(usize u8 u16 u32);
4043 step_impl_signed!(isize i8 i16 i32);
4044 #[cfg(target_pointer_width = "64")]
4045 step_impl_unsigned!(u64);
4046 #[cfg(target_pointer_width = "64")]
4047 step_impl_signed!(i64);
4048 // If the target pointer width is not 64-bits, we
4049 // assume here that it is less than 64-bits.
4050 #[cfg(not(target_pointer_width = "64"))]
4051 step_impl_no_between!(u64 i64);
4052
4053 /// An adapter for stepping range iterators by a custom amount.
4054 ///
4055 /// The resulting iterator handles overflow by stopping. The `A`
4056 /// parameter is the type being iterated over, while `R` is the range
4057 /// type (usually one of `std::ops::{Range, RangeFrom}`.
4058 #[derive(Clone)]
4059 #[unstable(feature = "step_by", reason = "recent addition",
4060            issue = "27741")]
4061 pub struct StepBy<A, R> {
4062     step_by: A,
4063     range: R,
4064 }
4065
4066 impl<A: Step> RangeFrom<A> {
4067     /// Creates an iterator starting at the same point, but stepping by
4068     /// the given amount at each iteration.
4069     ///
4070     /// # Examples
4071     ///
4072     /// ```ignore
4073     /// for i in (0u8..).step_by(2) {
4074     ///     println!("{}", i);
4075     /// }
4076     /// ```
4077     ///
4078     /// This prints all even `u8` values.
4079     #[unstable(feature = "step_by", reason = "recent addition",
4080                issue = "27741")]
4081     pub fn step_by(self, by: A) -> StepBy<A, Self> {
4082         StepBy {
4083             step_by: by,
4084             range: self
4085         }
4086     }
4087 }
4088
4089 impl<A: Step> ops::Range<A> {
4090     /// Creates an iterator with the same range, but stepping by the
4091     /// given amount at each iteration.
4092     ///
4093     /// The resulting iterator handles overflow by stopping.
4094     ///
4095     /// # Examples
4096     ///
4097     /// ```
4098     /// #![feature(step_by)]
4099     ///
4100     /// for i in (0..10).step_by(2) {
4101     ///     println!("{}", i);
4102     /// }
4103     /// ```
4104     ///
4105     /// This prints:
4106     ///
4107     /// ```text
4108     /// 0
4109     /// 2
4110     /// 4
4111     /// 6
4112     /// 8
4113     /// ```
4114     #[unstable(feature = "step_by", reason = "recent addition",
4115                issue = "27741")]
4116     pub fn step_by(self, by: A) -> StepBy<A, Self> {
4117         StepBy {
4118             step_by: by,
4119             range: self
4120         }
4121     }
4122 }
4123
4124 #[stable(feature = "rust1", since = "1.0.0")]
4125 impl<A> Iterator for StepBy<A, RangeFrom<A>> where
4126     A: Clone,
4127     for<'a> &'a A: Add<&'a A, Output = A>
4128 {
4129     type Item = A;
4130
4131     #[inline]
4132     fn next(&mut self) -> Option<A> {
4133         let mut n = &self.range.start + &self.step_by;
4134         mem::swap(&mut n, &mut self.range.start);
4135         Some(n)
4136     }
4137
4138     #[inline]
4139     fn size_hint(&self) -> (usize, Option<usize>) {
4140         (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4141     }
4142 }
4143
4144 /// An iterator over the range [start, stop]
4145 #[derive(Clone)]
4146 #[unstable(feature = "range_inclusive",
4147            reason = "likely to be replaced by range notation and adapters",
4148            issue = "27777")]
4149 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4150 #[allow(deprecated)]
4151 pub struct RangeInclusive<A> {
4152     range: ops::Range<A>,
4153     done: bool,
4154 }
4155
4156 /// Returns an iterator over the range [start, stop].
4157 #[inline]
4158 #[unstable(feature = "range_inclusive",
4159            reason = "likely to be replaced by range notation and adapters",
4160            issue = "27777")]
4161 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4162 #[allow(deprecated)]
4163 pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
4164     where A: Step + One + Clone
4165 {
4166     RangeInclusive {
4167         range: start..stop,
4168         done: false,
4169     }
4170 }
4171
4172 #[unstable(feature = "range_inclusive",
4173            reason = "likely to be replaced by range notation and adapters",
4174            issue = "27777")]
4175 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4176 #[allow(deprecated)]
4177 impl<A> Iterator for RangeInclusive<A> where
4178     A: PartialEq + Step + One + Clone,
4179     for<'a> &'a A: Add<&'a A, Output = A>
4180 {
4181     type Item = A;
4182
4183     #[inline]
4184     fn next(&mut self) -> Option<A> {
4185         self.range.next().or_else(|| {
4186             if !self.done && self.range.start == self.range.end {
4187                 self.done = true;
4188                 Some(self.range.end.clone())
4189             } else {
4190                 None
4191             }
4192         })
4193     }
4194
4195     #[inline]
4196     fn size_hint(&self) -> (usize, Option<usize>) {
4197         let (lo, hi) = self.range.size_hint();
4198         if self.done {
4199             (lo, hi)
4200         } else {
4201             let lo = lo.saturating_add(1);
4202             let hi = hi.and_then(|x| x.checked_add(1));
4203             (lo, hi)
4204         }
4205     }
4206 }
4207
4208 #[unstable(feature = "range_inclusive",
4209            reason = "likely to be replaced by range notation and adapters",
4210            issue = "27777")]
4211 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4212 #[allow(deprecated)]
4213 impl<A> DoubleEndedIterator for RangeInclusive<A> where
4214     A: PartialEq + Step + One + Clone,
4215     for<'a> &'a A: Add<&'a A, Output = A>,
4216     for<'a> &'a A: Sub<Output=A>
4217 {
4218     #[inline]
4219     fn next_back(&mut self) -> Option<A> {
4220         if self.range.end > self.range.start {
4221             let result = self.range.end.clone();
4222             self.range.end = &self.range.end - &A::one();
4223             Some(result)
4224         } else if !self.done && self.range.start == self.range.end {
4225             self.done = true;
4226             Some(self.range.end.clone())
4227         } else {
4228             None
4229         }
4230     }
4231 }
4232
4233 #[stable(feature = "rust1", since = "1.0.0")]
4234 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4235     type Item = A;
4236
4237     #[inline]
4238     fn next(&mut self) -> Option<A> {
4239         let rev = self.step_by < A::zero();
4240         if (rev && self.range.start > self.range.end) ||
4241            (!rev && self.range.start < self.range.end)
4242         {
4243             match self.range.start.step(&self.step_by) {
4244                 Some(mut n) => {
4245                     mem::swap(&mut self.range.start, &mut n);
4246                     Some(n)
4247                 },
4248                 None => {
4249                     let mut n = self.range.end.clone();
4250                     mem::swap(&mut self.range.start, &mut n);
4251                     Some(n)
4252                 }
4253             }
4254         } else {
4255             None
4256         }
4257     }
4258
4259     #[inline]
4260     fn size_hint(&self) -> (usize, Option<usize>) {
4261         match Step::steps_between(&self.range.start,
4262                                   &self.range.end,
4263                                   &self.step_by) {
4264             Some(hint) => (hint, Some(hint)),
4265             None       => (0, None)
4266         }
4267     }
4268 }
4269
4270 macro_rules! range_exact_iter_impl {
4271     ($($t:ty)*) => ($(
4272         #[stable(feature = "rust1", since = "1.0.0")]
4273         impl ExactSizeIterator for ops::Range<$t> { }
4274     )*)
4275 }
4276
4277 #[stable(feature = "rust1", since = "1.0.0")]
4278 impl<A: Step + One> Iterator for ops::Range<A> where
4279     for<'a> &'a A: Add<&'a A, Output = A>
4280 {
4281     type Item = A;
4282
4283     #[inline]
4284     fn next(&mut self) -> Option<A> {
4285         if self.start < self.end {
4286             let mut n = &self.start + &A::one();
4287             mem::swap(&mut n, &mut self.start);
4288             Some(n)
4289         } else {
4290             None
4291         }
4292     }
4293
4294     #[inline]
4295     fn size_hint(&self) -> (usize, Option<usize>) {
4296         match Step::steps_between(&self.start, &self.end, &A::one()) {
4297             Some(hint) => (hint, Some(hint)),
4298             None => (0, None)
4299         }
4300     }
4301 }
4302
4303 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4304 // a length <= usize::MAX, which is required by ExactSizeIterator.
4305 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4306
4307 #[stable(feature = "rust1", since = "1.0.0")]
4308 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4309     for<'a> &'a A: Add<&'a A, Output = A>,
4310     for<'a> &'a A: Sub<&'a A, Output = A>
4311 {
4312     #[inline]
4313     fn next_back(&mut self) -> Option<A> {
4314         if self.start < self.end {
4315             self.end = &self.end - &A::one();
4316             Some(self.end.clone())
4317         } else {
4318             None
4319         }
4320     }
4321 }
4322
4323 #[stable(feature = "rust1", since = "1.0.0")]
4324 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4325     for<'a> &'a A: Add<&'a A, Output = A>
4326 {
4327     type Item = A;
4328
4329     #[inline]
4330     fn next(&mut self) -> Option<A> {
4331         let mut n = &self.start + &A::one();
4332         mem::swap(&mut n, &mut self.start);
4333         Some(n)
4334     }
4335 }
4336
4337 /// An iterator that repeats an element endlessly.
4338 ///
4339 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4340 ///
4341 /// [`repeat()`]: fn.repeat.html
4342 #[derive(Clone)]
4343 #[stable(feature = "rust1", since = "1.0.0")]
4344 pub struct Repeat<A> {
4345     element: A
4346 }
4347
4348 #[stable(feature = "rust1", since = "1.0.0")]
4349 impl<A: Clone> Iterator for Repeat<A> {
4350     type Item = A;
4351
4352     #[inline]
4353     fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4354     #[inline]
4355     fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4356 }
4357
4358 #[stable(feature = "rust1", since = "1.0.0")]
4359 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4360     #[inline]
4361     fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4362 }
4363
4364 /// Creates a new iterator that endlessly repeats a single element.
4365 ///
4366 /// The `repeat()` function repeats a single value over and over and over and
4367 /// over and over and 🔁.
4368 ///
4369 /// Infinite iterators like `repeat()` are often used with adapters like
4370 /// [`take()`], in order to make them finite.
4371 ///
4372 /// [`take()`]: trait.Iterator.html#method.take
4373 ///
4374 /// # Examples
4375 ///
4376 /// Basic usage:
4377 ///
4378 /// ```
4379 /// use std::iter;
4380 ///
4381 /// // the number four 4ever:
4382 /// let mut fours = iter::repeat(4);
4383 ///
4384 /// assert_eq!(Some(4), fours.next());
4385 /// assert_eq!(Some(4), fours.next());
4386 /// assert_eq!(Some(4), fours.next());
4387 /// assert_eq!(Some(4), fours.next());
4388 /// assert_eq!(Some(4), fours.next());
4389 ///
4390 /// // yup, still four
4391 /// assert_eq!(Some(4), fours.next());
4392 /// ```
4393 ///
4394 /// Going finite with [`take()`]:
4395 ///
4396 /// ```
4397 /// use std::iter;
4398 ///
4399 /// // that last example was too many fours. Let's only have four fours.
4400 /// let mut four_fours = iter::repeat(4).take(4);
4401 ///
4402 /// assert_eq!(Some(4), four_fours.next());
4403 /// assert_eq!(Some(4), four_fours.next());
4404 /// assert_eq!(Some(4), four_fours.next());
4405 /// assert_eq!(Some(4), four_fours.next());
4406 ///
4407 /// // ... and now we're done
4408 /// assert_eq!(None, four_fours.next());
4409 /// ```
4410 #[inline]
4411 #[stable(feature = "rust1", since = "1.0.0")]
4412 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4413     Repeat{element: elt}
4414 }
4415
4416 /// An iterator that yields nothing.
4417 ///
4418 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4419 ///
4420 /// [`empty()`]: fn.empty.html
4421 #[stable(feature = "iter_empty", since = "1.2.0")]
4422 pub struct Empty<T>(marker::PhantomData<T>);
4423
4424 #[stable(feature = "iter_empty", since = "1.2.0")]
4425 impl<T> Iterator for Empty<T> {
4426     type Item = T;
4427
4428     fn next(&mut self) -> Option<T> {
4429         None
4430     }
4431
4432     fn size_hint(&self) -> (usize, Option<usize>){
4433         (0, Some(0))
4434     }
4435 }
4436
4437 #[stable(feature = "iter_empty", since = "1.2.0")]
4438 impl<T> DoubleEndedIterator for Empty<T> {
4439     fn next_back(&mut self) -> Option<T> {
4440         None
4441     }
4442 }
4443
4444 #[stable(feature = "iter_empty", since = "1.2.0")]
4445 impl<T> ExactSizeIterator for Empty<T> {
4446     fn len(&self) -> usize {
4447         0
4448     }
4449 }
4450
4451 // not #[derive] because that adds a Clone bound on T,
4452 // which isn't necessary.
4453 #[stable(feature = "iter_empty", since = "1.2.0")]
4454 impl<T> Clone for Empty<T> {
4455     fn clone(&self) -> Empty<T> {
4456         Empty(marker::PhantomData)
4457     }
4458 }
4459
4460 // not #[derive] because that adds a Default bound on T,
4461 // which isn't necessary.
4462 #[stable(feature = "iter_empty", since = "1.2.0")]
4463 impl<T> Default for Empty<T> {
4464     fn default() -> Empty<T> {
4465         Empty(marker::PhantomData)
4466     }
4467 }
4468
4469 /// Creates an iterator that yields nothing.
4470 ///
4471 /// # Examples
4472 ///
4473 /// Basic usage:
4474 ///
4475 /// ```
4476 /// use std::iter;
4477 ///
4478 /// // this could have been an iterator over i32, but alas, it's just not.
4479 /// let mut nope = iter::empty::<i32>();
4480 ///
4481 /// assert_eq!(None, nope.next());
4482 /// ```
4483 #[stable(feature = "iter_empty", since = "1.2.0")]
4484 pub fn empty<T>() -> Empty<T> {
4485     Empty(marker::PhantomData)
4486 }
4487
4488 /// An iterator that yields an element exactly once.
4489 ///
4490 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4491 ///
4492 /// [`once()`]: fn.once.html
4493 #[derive(Clone)]
4494 #[stable(feature = "iter_once", since = "1.2.0")]
4495 pub struct Once<T> {
4496     inner: ::option::IntoIter<T>
4497 }
4498
4499 #[stable(feature = "iter_once", since = "1.2.0")]
4500 impl<T> Iterator for Once<T> {
4501     type Item = T;
4502
4503     fn next(&mut self) -> Option<T> {
4504         self.inner.next()
4505     }
4506
4507     fn size_hint(&self) -> (usize, Option<usize>) {
4508         self.inner.size_hint()
4509     }
4510 }
4511
4512 #[stable(feature = "iter_once", since = "1.2.0")]
4513 impl<T> DoubleEndedIterator for Once<T> {
4514     fn next_back(&mut self) -> Option<T> {
4515         self.inner.next_back()
4516     }
4517 }
4518
4519 #[stable(feature = "iter_once", since = "1.2.0")]
4520 impl<T> ExactSizeIterator for Once<T> {
4521     fn len(&self) -> usize {
4522         self.inner.len()
4523     }
4524 }
4525
4526 /// Creates an iterator that yields an element exactly once.
4527 ///
4528 /// This is commonly used to adapt a single value into a [`chain()`] of other
4529 /// kinds of iteration. Maybe you have an iterator that covers almost
4530 /// everything, but you need an extra special case. Maybe you have a function
4531 /// which works on iterators, but you only need to process one value.
4532 ///
4533 /// [`chain()`]: trait.Iterator.html#method.chain
4534 ///
4535 /// # Examples
4536 ///
4537 /// Basic usage:
4538 ///
4539 /// ```
4540 /// use std::iter;
4541 ///
4542 /// // one is the loneliest number
4543 /// let mut one = iter::once(1);
4544 ///
4545 /// assert_eq!(Some(1), one.next());
4546 ///
4547 /// // just one, that's all we get
4548 /// assert_eq!(None, one.next());
4549 /// ```
4550 ///
4551 /// Chaining together with another iterator. Let's say that we want to iterate
4552 /// over each file of the `.foo` directory, but also a configuration file,
4553 /// `.foorc`:
4554 ///
4555 /// ```no_run
4556 /// use std::iter;
4557 /// use std::fs;
4558 /// use std::path::PathBuf;
4559 ///
4560 /// let dirs = fs::read_dir(".foo").unwrap();
4561 ///
4562 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4563 /// // PathBufs, so we use map
4564 /// let dirs = dirs.map(|file| file.unwrap().path());
4565 ///
4566 /// // now, our iterator just for our config file
4567 /// let config = iter::once(PathBuf::from(".foorc"));
4568 ///
4569 /// // chain the two iterators together into one big iterator
4570 /// let files = dirs.chain(config);
4571 ///
4572 /// // this will give us all of the files in .foo as well as .foorc
4573 /// for f in files {
4574 ///     println!("{:?}", f);
4575 /// }
4576 /// ```
4577 #[stable(feature = "iter_once", since = "1.2.0")]
4578 pub fn once<T>(value: T) -> Once<T> {
4579     Once { inner: Some(value).into_iter() }
4580 }
4581
4582 /// Functions for lexicographical ordering of sequences.
4583 ///
4584 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
4585 /// that the elements implement both `PartialEq` and `PartialOrd`.
4586 ///
4587 /// If two sequences are equal up until the point where one ends,
4588 /// the shorter sequence compares less.
4589 #[deprecated(since = "1.4.0", reason = "use the equivalent methods on `Iterator` instead")]
4590 #[unstable(feature = "iter_order_deprecated", reason = "needs review and revision",
4591            issue = "27737")]
4592 pub mod order {
4593     use cmp;
4594     use cmp::{Eq, Ord, PartialOrd, PartialEq};
4595     use option::Option;
4596     use super::Iterator;
4597
4598     /// Compare `a` and `b` for equality using `Eq`
4599     pub fn equals<A, L, R>(a: L, b: R) -> bool where
4600         A: Eq,
4601         L: Iterator<Item=A>,
4602         R: Iterator<Item=A>,
4603     {
4604         a.eq(b)
4605     }
4606
4607     /// Order `a` and `b` lexicographically using `Ord`
4608     pub fn cmp<A, L, R>(a: L, b: R) -> cmp::Ordering where
4609         A: Ord,
4610         L: Iterator<Item=A>,
4611         R: Iterator<Item=A>,
4612     {
4613         a.cmp(b)
4614     }
4615
4616     /// Order `a` and `b` lexicographically using `PartialOrd`
4617     pub fn partial_cmp<L: Iterator, R: Iterator>(a: L, b: R) -> Option<cmp::Ordering> where
4618         L::Item: PartialOrd<R::Item>
4619     {
4620         a.partial_cmp(b)
4621     }
4622
4623     /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
4624     pub fn eq<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4625         L::Item: PartialEq<R::Item>,
4626     {
4627         a.eq(b)
4628     }
4629
4630     /// Compares `a` and `b` for nonequality (Using partial equality, `PartialEq`)
4631     pub fn ne<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4632         L::Item: PartialEq<R::Item>,
4633     {
4634         a.ne(b)
4635     }
4636
4637     /// Returns `a` < `b` lexicographically (Using partial order, `PartialOrd`)
4638     pub fn lt<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4639         L::Item: PartialOrd<R::Item>,
4640     {
4641         a.lt(b)
4642     }
4643
4644     /// Returns `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
4645     pub fn le<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4646         L::Item: PartialOrd<R::Item>,
4647     {
4648         a.le(b)
4649     }
4650
4651     /// Returns `a` > `b` lexicographically (Using partial order, `PartialOrd`)
4652     pub fn gt<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4653         L::Item: PartialOrd<R::Item>,
4654     {
4655         a.gt(b)
4656     }
4657
4658     /// Returns `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
4659     pub fn ge<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4660         L::Item: PartialOrd<R::Item>,
4661     {
4662         a.ge(b)
4663     }
4664 }