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