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