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