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