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