]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/mod.rs
Auto merge of #37944 - bluss:adaptors-are-empty, r=alexcrichton
[rust.git] / src / libcore / iter / mod.rs
1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Composable external iteration.
12 //!
13 //! If you've found yourself with a collection of some kind, and needed to
14 //! perform an operation on the elements of said collection, you'll quickly run
15 //! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
16 //! it's worth becoming familiar with them.
17 //!
18 //! Before explaining more, let's talk about how this module is structured:
19 //!
20 //! # Organization
21 //!
22 //! This module is largely organized by type:
23 //!
24 //! * [Traits] are the core portion: these traits define what kind of iterators
25 //!   exist and what you can do with them. The methods of these traits are worth
26 //!   putting some extra study time into.
27 //! * [Functions] provide some helpful ways to create some basic iterators.
28 //! * [Structs] are often the return types of the various methods on this
29 //!   module's traits. You'll usually want to look at the method that creates
30 //!   the `struct`, rather than the `struct` itself. For more detail about why,
31 //!   see '[Implementing Iterator](#implementing-iterator)'.
32 //!
33 //! [Traits]: #traits
34 //! [Functions]: #functions
35 //! [Structs]: #structs
36 //!
37 //! That's it! Let's dig into iterators.
38 //!
39 //! # Iterator
40 //!
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
43 //!
44 //! ```
45 //! trait Iterator {
46 //!     type Item;
47 //!     fn next(&mut self) -> Option<Self::Item>;
48 //! }
49 //! ```
50 //!
51 //! An iterator has a method, [`next()`], which when called, returns an
52 //! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
53 //! are elements, and once they've all been exhausted, will return `None` to
54 //! indicate that iteration is finished. Individual iterators may choose to
55 //! resume iteration, and so calling [`next()`] again may or may not eventually
56 //! start returning `Some(Item)` again at some point.
57 //!
58 //! [`Iterator`]'s full definition includes a number of other methods as well,
59 //! but they are default methods, built on top of [`next()`], and so you get
60 //! them for free.
61 //!
62 //! Iterators are also composable, and it's common to chain them together to do
63 //! more complex forms of processing. See the [Adapters](#adapters) section
64 //! below for more details.
65 //!
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../../std/option/enum.Option.html
69 //!
70 //! # The three forms of iteration
71 //!
72 //! There are three common methods which can create iterators from a collection:
73 //!
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
77 //!
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
80 //!
81 //! # Implementing Iterator
82 //!
83 //! Creating an iterator of your own involves two steps: creating a `struct` to
84 //! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
85 //! `struct`. This is why there are so many `struct`s in this module: there is
86 //! one for each iterator and iterator adapter.
87 //!
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
89 //!
90 //! ```
91 //! // First, the struct:
92 //!
93 //! /// An iterator which counts from one to five
94 //! struct Counter {
95 //!     count: usize,
96 //! }
97 //!
98 //! // we want our count to start at one, so let's add a new() method to help.
99 //! // This isn't strictly necessary, but is convenient. Note that we start
100 //! // `count` at zero, we'll see why in `next()`'s implementation below.
101 //! impl Counter {
102 //!     fn new() -> Counter {
103 //!         Counter { count: 0 }
104 //!     }
105 //! }
106 //!
107 //! // Then, we implement `Iterator` for our `Counter`:
108 //!
109 //! impl Iterator for Counter {
110 //!     // we will be counting with usize
111 //!     type Item = usize;
112 //!
113 //!     // next() is the only required method
114 //!     fn next(&mut self) -> Option<usize> {
115 //!         // increment our count. This is why we started at zero.
116 //!         self.count += 1;
117 //!
118 //!         // check to see if we've finished counting or not.
119 //!         if self.count < 6 {
120 //!             Some(self.count)
121 //!         } else {
122 //!             None
123 //!         }
124 //!     }
125 //! }
126 //!
127 //! // And now we can use it!
128 //!
129 //! let mut counter = Counter::new();
130 //!
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
133 //!
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
136 //!
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
139 //!
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
142 //!
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
145 //! ```
146 //!
147 //! This will print `1` through `5`, each on their own line.
148 //!
149 //! Calling `next()` this way gets repetitive. Rust has a construct which can
150 //! call `next()` on your iterator, until it reaches `None`. Let's go over that
151 //! next.
152 //!
153 //! # for Loops and IntoIterator
154 //!
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
157 //!
158 //! ```
159 //! let values = vec![1, 2, 3, 4, 5];
160 //!
161 //! for x in values {
162 //!     println!("{}", x);
163 //! }
164 //! ```
165 //!
166 //! This will print the numbers one through five, each on their own line. But
167 //! you'll notice something here: we never called anything on our vector to
168 //! produce an iterator. What gives?
169 //!
170 //! There's a trait in the standard library for converting something into an
171 //! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
172 //! which converts the thing implementing [`IntoIterator`] into an iterator.
173 //! Let's take a look at that `for` loop again, and what the compiler converts
174 //! it into:
175 //!
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
178 //!
179 //! ```
180 //! let values = vec![1, 2, 3, 4, 5];
181 //!
182 //! for x in values {
183 //!     println!("{}", x);
184 //! }
185 //! ```
186 //!
187 //! Rust de-sugars this into:
188 //!
189 //! ```
190 //! let values = vec![1, 2, 3, 4, 5];
191 //! {
192 //!     let result = match IntoIterator::into_iter(values) {
193 //!         mut iter => loop {
194 //!             match iter.next() {
195 //!                 Some(x) => { println!("{}", x); },
196 //!                 None => break,
197 //!             }
198 //!         },
199 //!     };
200 //!     result
201 //! }
202 //! ```
203 //!
204 //! First, we call `into_iter()` on the value. Then, we match on the iterator
205 //! that returns, calling [`next()`] over and over until we see a `None`. At
206 //! that point, we `break` out of the loop, and we're done iterating.
207 //!
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
210 //!
211 //! ```ignore
212 //! impl<I: Iterator> IntoIterator for I
213 //! ```
214 //!
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
217 //!
218 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
219 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
220 //!    will allow your collection to be used with the `for` loop.
221 //!
222 //! # Adapters
223 //!
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
226 //! pattern'.
227 //!
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
230 //!
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
234 //!
235 //! # Laziness
236 //!
237 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
238 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
239 //! until you call [`next()`]. This is sometimes a source of confusion when
240 //! creating an iterator solely for its side effects. For example, the [`map()`]
241 //! method calls a closure on each element it iterates over:
242 //!
243 //! ```
244 //! # #![allow(unused_must_use)]
245 //! let v = vec![1, 2, 3, 4, 5];
246 //! v.iter().map(|x| println!("{}", x));
247 //! ```
248 //!
249 //! This will not print any values, as we only created an iterator, rather than
250 //! using it. The compiler will warn us about this kind of behavior:
251 //!
252 //! ```text
253 //! warning: unused result which must be used: iterator adaptors are lazy and
254 //! do nothing unless consumed
255 //! ```
256 //!
257 //! The idiomatic way to write a [`map()`] for its side effects is to use a
258 //! `for` loop instead:
259 //!
260 //! ```
261 //! let v = vec![1, 2, 3, 4, 5];
262 //!
263 //! for x in &v {
264 //!     println!("{}", x);
265 //! }
266 //! ```
267 //!
268 //! [`map()`]: trait.Iterator.html#method.map
269 //!
270 //! The two most common ways to evaluate an iterator are to use a `for` loop
271 //! like this, or using the [`collect()`] adapter to produce a new collection.
272 //!
273 //! [`collect()`]: trait.Iterator.html#method.collect
274 //!
275 //! # Infinity
276 //!
277 //! Iterators do not have to be finite. As an example, an open-ended range is
278 //! an infinite iterator:
279 //!
280 //! ```
281 //! let numbers = 0..;
282 //! ```
283 //!
284 //! It is common to use the [`take()`] iterator adapter to turn an infinite
285 //! iterator into a finite one:
286 //!
287 //! ```
288 //! let numbers = 0..;
289 //! let five_numbers = numbers.take(5);
290 //!
291 //! for number in five_numbers {
292 //!     println!("{}", number);
293 //! }
294 //! ```
295 //!
296 //! This will print the numbers `0` through `4`, each on their own line.
297 //!
298 //! [`take()`]: trait.Iterator.html#method.take
299
300 #![stable(feature = "rust1", since = "1.0.0")]
301
302 use cmp;
303 use fmt;
304 use iter_private::TrustedRandomAccess;
305 use usize;
306
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub use self::iterator::Iterator;
309
310 #[unstable(feature = "step_trait",
311            reason = "likely to be replaced by finer-grained traits",
312            issue = "27741")]
313 pub use self::range::Step;
314 #[unstable(feature = "step_by", reason = "recent addition",
315            issue = "27741")]
316 pub use self::range::StepBy;
317
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub use self::sources::{Repeat, repeat};
320 #[stable(feature = "iter_empty", since = "1.2.0")]
321 pub use self::sources::{Empty, empty};
322 #[stable(feature = "iter_once", since = "1.2.0")]
323 pub use self::sources::{Once, once};
324
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend};
327 #[stable(feature = "rust1", since = "1.0.0")]
328 pub use self::traits::{ExactSizeIterator, Sum, Product};
329 #[unstable(feature = "fused", issue = "35602")]
330 pub use self::traits::FusedIterator;
331 #[unstable(feature = "trusted_len", issue = "37572")]
332 pub use self::traits::TrustedLen;
333
334 mod iterator;
335 mod range;
336 mod sources;
337 mod traits;
338
339 /// An double-ended iterator with the direction inverted.
340 ///
341 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
342 /// documentation for more.
343 ///
344 /// [`rev()`]: trait.Iterator.html#method.rev
345 /// [`Iterator`]: trait.Iterator.html
346 #[derive(Clone, Debug)]
347 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub struct Rev<T> {
350     iter: T
351 }
352
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
355     type Item = <I as Iterator>::Item;
356
357     #[inline]
358     fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
359     #[inline]
360     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
361 }
362
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
365     #[inline]
366     fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
367 }
368
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<I> ExactSizeIterator for Rev<I>
371     where I: ExactSizeIterator + DoubleEndedIterator
372 {
373     fn len(&self) -> usize {
374         self.iter.len()
375     }
376
377     fn is_empty(&self) -> bool {
378         self.iter.is_empty()
379     }
380 }
381
382 #[unstable(feature = "fused", issue = "35602")]
383 impl<I> FusedIterator for Rev<I>
384     where I: FusedIterator + DoubleEndedIterator {}
385
386 #[unstable(feature = "trusted_len", issue = "37572")]
387 unsafe impl<I> TrustedLen for Rev<I>
388     where I: TrustedLen + DoubleEndedIterator {}
389
390 /// An iterator that clones the elements of an underlying iterator.
391 ///
392 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
393 /// documentation for more.
394 ///
395 /// [`cloned()`]: trait.Iterator.html#method.cloned
396 /// [`Iterator`]: trait.Iterator.html
397 #[stable(feature = "iter_cloned", since = "1.1.0")]
398 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
399 #[derive(Clone, Debug)]
400 pub struct Cloned<I> {
401     it: I,
402 }
403
404 #[stable(feature = "iter_cloned", since = "1.1.0")]
405 impl<'a, I, T: 'a> Iterator for Cloned<I>
406     where I: Iterator<Item=&'a T>, T: Clone
407 {
408     type Item = T;
409
410     fn next(&mut self) -> Option<T> {
411         self.it.next().cloned()
412     }
413
414     fn size_hint(&self) -> (usize, Option<usize>) {
415         self.it.size_hint()
416     }
417
418     fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
419         where F: FnMut(Acc, Self::Item) -> Acc,
420     {
421         self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
422     }
423 }
424
425 #[stable(feature = "iter_cloned", since = "1.1.0")]
426 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
427     where I: DoubleEndedIterator<Item=&'a T>, T: Clone
428 {
429     fn next_back(&mut self) -> Option<T> {
430         self.it.next_back().cloned()
431     }
432 }
433
434 #[stable(feature = "iter_cloned", since = "1.1.0")]
435 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
436     where I: ExactSizeIterator<Item=&'a T>, T: Clone
437 {
438     fn len(&self) -> usize {
439         self.it.len()
440     }
441
442     fn is_empty(&self) -> bool {
443         self.it.is_empty()
444     }
445 }
446
447 #[unstable(feature = "fused", issue = "35602")]
448 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
449     where I: FusedIterator<Item=&'a T>, T: Clone
450 {}
451
452 #[doc(hidden)]
453 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
454     where I: TrustedRandomAccess<Item=&'a T>, T: Clone
455 {
456     unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
457         self.it.get_unchecked(i).clone()
458     }
459
460     #[inline]
461     fn may_have_side_effect() -> bool { true }
462 }
463
464 #[unstable(feature = "trusted_len", issue = "37572")]
465 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
466     where I: TrustedLen<Item=&'a T>,
467           T: Clone
468 {}
469
470 /// An iterator that repeats endlessly.
471 ///
472 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
473 /// documentation for more.
474 ///
475 /// [`cycle()`]: trait.Iterator.html#method.cycle
476 /// [`Iterator`]: trait.Iterator.html
477 #[derive(Clone, Debug)]
478 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub struct Cycle<I> {
481     orig: I,
482     iter: I,
483 }
484
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
487     type Item = <I as Iterator>::Item;
488
489     #[inline]
490     fn next(&mut self) -> Option<<I as Iterator>::Item> {
491         match self.iter.next() {
492             None => { self.iter = self.orig.clone(); self.iter.next() }
493             y => y
494         }
495     }
496
497     #[inline]
498     fn size_hint(&self) -> (usize, Option<usize>) {
499         // the cycle iterator is either empty or infinite
500         match self.orig.size_hint() {
501             sz @ (0, Some(0)) => sz,
502             (0, _) => (0, None),
503             _ => (usize::MAX, None)
504         }
505     }
506 }
507
508 #[unstable(feature = "fused", issue = "35602")]
509 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
510
511 /// An iterator that strings two iterators together.
512 ///
513 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
514 /// documentation for more.
515 ///
516 /// [`chain()`]: trait.Iterator.html#method.chain
517 /// [`Iterator`]: trait.Iterator.html
518 #[derive(Clone, Debug)]
519 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub struct Chain<A, B> {
522     a: A,
523     b: B,
524     state: ChainState,
525 }
526
527 // The iterator protocol specifies that iteration ends with the return value
528 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
529 // further calls return. The chain adaptor must account for this since it uses
530 // two subiterators.
531 //
532 //  It uses three states:
533 //
534 //  - Both: `a` and `b` are remaining
535 //  - Front: `a` remaining
536 //  - Back: `b` remaining
537 //
538 //  The fourth state (neither iterator is remaining) only occurs after Chain has
539 //  returned None once, so we don't need to store this state.
540 #[derive(Clone, Debug)]
541 enum ChainState {
542     // both front and back iterator are remaining
543     Both,
544     // only front is remaining
545     Front,
546     // only back is remaining
547     Back,
548 }
549
550 #[stable(feature = "rust1", since = "1.0.0")]
551 impl<A, B> Iterator for Chain<A, B> where
552     A: Iterator,
553     B: Iterator<Item = A::Item>
554 {
555     type Item = A::Item;
556
557     #[inline]
558     fn next(&mut self) -> Option<A::Item> {
559         match self.state {
560             ChainState::Both => match self.a.next() {
561                 elt @ Some(..) => elt,
562                 None => {
563                     self.state = ChainState::Back;
564                     self.b.next()
565                 }
566             },
567             ChainState::Front => self.a.next(),
568             ChainState::Back => self.b.next(),
569         }
570     }
571
572     #[inline]
573     #[rustc_inherit_overflow_checks]
574     fn count(self) -> usize {
575         match self.state {
576             ChainState::Both => self.a.count() + self.b.count(),
577             ChainState::Front => self.a.count(),
578             ChainState::Back => self.b.count(),
579         }
580     }
581
582     fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
583         where F: FnMut(Acc, Self::Item) -> Acc,
584     {
585         let mut accum = init;
586         match self.state {
587             ChainState::Both | ChainState::Front => {
588                 accum = self.a.fold(accum, &mut f);
589             }
590             _ => { }
591         }
592         match self.state {
593             ChainState::Both | ChainState::Back => {
594                 accum = self.b.fold(accum, &mut f);
595             }
596             _ => { }
597         }
598         accum
599     }
600
601     #[inline]
602     fn nth(&mut self, mut n: usize) -> Option<A::Item> {
603         match self.state {
604             ChainState::Both | ChainState::Front => {
605                 for x in self.a.by_ref() {
606                     if n == 0 {
607                         return Some(x)
608                     }
609                     n -= 1;
610                 }
611                 if let ChainState::Both = self.state {
612                     self.state = ChainState::Back;
613                 }
614             }
615             ChainState::Back => {}
616         }
617         if let ChainState::Back = self.state {
618             self.b.nth(n)
619         } else {
620             None
621         }
622     }
623
624     #[inline]
625     fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
626         P: FnMut(&Self::Item) -> bool,
627     {
628         match self.state {
629             ChainState::Both => match self.a.find(&mut predicate) {
630                 None => {
631                     self.state = ChainState::Back;
632                     self.b.find(predicate)
633                 }
634                 v => v
635             },
636             ChainState::Front => self.a.find(predicate),
637             ChainState::Back => self.b.find(predicate),
638         }
639     }
640
641     #[inline]
642     fn last(self) -> Option<A::Item> {
643         match self.state {
644             ChainState::Both => {
645                 // Must exhaust a before b.
646                 let a_last = self.a.last();
647                 let b_last = self.b.last();
648                 b_last.or(a_last)
649             },
650             ChainState::Front => self.a.last(),
651             ChainState::Back => self.b.last()
652         }
653     }
654
655     #[inline]
656     fn size_hint(&self) -> (usize, Option<usize>) {
657         let (a_lower, a_upper) = self.a.size_hint();
658         let (b_lower, b_upper) = self.b.size_hint();
659
660         let lower = a_lower.saturating_add(b_lower);
661
662         let upper = match (a_upper, b_upper) {
663             (Some(x), Some(y)) => x.checked_add(y),
664             _ => None
665         };
666
667         (lower, upper)
668     }
669 }
670
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<A, B> DoubleEndedIterator for Chain<A, B> where
673     A: DoubleEndedIterator,
674     B: DoubleEndedIterator<Item=A::Item>,
675 {
676     #[inline]
677     fn next_back(&mut self) -> Option<A::Item> {
678         match self.state {
679             ChainState::Both => match self.b.next_back() {
680                 elt @ Some(..) => elt,
681                 None => {
682                     self.state = ChainState::Front;
683                     self.a.next_back()
684                 }
685             },
686             ChainState::Front => self.a.next_back(),
687             ChainState::Back => self.b.next_back(),
688         }
689     }
690 }
691
692 // Note: *both* must be fused to handle double-ended iterators.
693 #[unstable(feature = "fused", issue = "35602")]
694 impl<A, B> FusedIterator for Chain<A, B>
695     where A: FusedIterator,
696           B: FusedIterator<Item=A::Item>,
697 {}
698
699 #[unstable(feature = "trusted_len", issue = "37572")]
700 unsafe impl<A, B> TrustedLen for Chain<A, B>
701     where A: TrustedLen, B: TrustedLen<Item=A::Item>,
702 {}
703
704 /// An iterator that iterates two other iterators simultaneously.
705 ///
706 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
707 /// documentation for more.
708 ///
709 /// [`zip()`]: trait.Iterator.html#method.zip
710 /// [`Iterator`]: trait.Iterator.html
711 #[derive(Clone, Debug)]
712 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub struct Zip<A, B> {
715     a: A,
716     b: B,
717     // index and len are only used by the specialized version of zip
718     index: usize,
719     len: usize,
720 }
721
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
724 {
725     type Item = (A::Item, B::Item);
726
727     #[inline]
728     fn next(&mut self) -> Option<Self::Item> {
729         ZipImpl::next(self)
730     }
731
732     #[inline]
733     fn size_hint(&self) -> (usize, Option<usize>) {
734         ZipImpl::size_hint(self)
735     }
736 }
737
738 #[stable(feature = "rust1", since = "1.0.0")]
739 impl<A, B> DoubleEndedIterator for Zip<A, B> where
740     A: DoubleEndedIterator + ExactSizeIterator,
741     B: DoubleEndedIterator + ExactSizeIterator,
742 {
743     #[inline]
744     fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
745         ZipImpl::next_back(self)
746     }
747 }
748
749 // Zip specialization trait
750 #[doc(hidden)]
751 trait ZipImpl<A, B> {
752     type Item;
753     fn new(a: A, b: B) -> Self;
754     fn next(&mut self) -> Option<Self::Item>;
755     fn size_hint(&self) -> (usize, Option<usize>);
756     fn next_back(&mut self) -> Option<Self::Item>
757         where A: DoubleEndedIterator + ExactSizeIterator,
758               B: DoubleEndedIterator + ExactSizeIterator;
759 }
760
761 // General Zip impl
762 #[doc(hidden)]
763 impl<A, B> ZipImpl<A, B> for Zip<A, B>
764     where A: Iterator, B: Iterator
765 {
766     type Item = (A::Item, B::Item);
767     default fn new(a: A, b: B) -> Self {
768         Zip {
769             a: a,
770             b: b,
771             index: 0, // unused
772             len: 0, // unused
773         }
774     }
775
776     #[inline]
777     default fn next(&mut self) -> Option<(A::Item, B::Item)> {
778         self.a.next().and_then(|x| {
779             self.b.next().and_then(|y| {
780                 Some((x, y))
781             })
782         })
783     }
784
785     #[inline]
786     default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
787         where A: DoubleEndedIterator + ExactSizeIterator,
788               B: DoubleEndedIterator + ExactSizeIterator
789     {
790         let a_sz = self.a.len();
791         let b_sz = self.b.len();
792         if a_sz != b_sz {
793             // Adjust a, b to equal length
794             if a_sz > b_sz {
795                 for _ in 0..a_sz - b_sz { self.a.next_back(); }
796             } else {
797                 for _ in 0..b_sz - a_sz { self.b.next_back(); }
798             }
799         }
800         match (self.a.next_back(), self.b.next_back()) {
801             (Some(x), Some(y)) => Some((x, y)),
802             (None, None) => None,
803             _ => unreachable!(),
804         }
805     }
806
807     #[inline]
808     default fn size_hint(&self) -> (usize, Option<usize>) {
809         let (a_lower, a_upper) = self.a.size_hint();
810         let (b_lower, b_upper) = self.b.size_hint();
811
812         let lower = cmp::min(a_lower, b_lower);
813
814         let upper = match (a_upper, b_upper) {
815             (Some(x), Some(y)) => Some(cmp::min(x,y)),
816             (Some(x), None) => Some(x),
817             (None, Some(y)) => Some(y),
818             (None, None) => None
819         };
820
821         (lower, upper)
822     }
823 }
824
825 #[doc(hidden)]
826 impl<A, B> ZipImpl<A, B> for Zip<A, B>
827     where A: TrustedRandomAccess, B: TrustedRandomAccess
828 {
829     fn new(a: A, b: B) -> Self {
830         let len = cmp::min(a.len(), b.len());
831         Zip {
832             a: a,
833             b: b,
834             index: 0,
835             len: len,
836         }
837     }
838
839     #[inline]
840     fn next(&mut self) -> Option<(A::Item, B::Item)> {
841         if self.index < self.len {
842             let i = self.index;
843             self.index += 1;
844             unsafe {
845                 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
846             }
847         } else if A::may_have_side_effect() && self.index < self.a.len() {
848             // match the base implementation's potential side effects
849             unsafe {
850                 self.a.get_unchecked(self.index);
851             }
852             self.index += 1;
853             None
854         } else {
855             None
856         }
857     }
858
859     #[inline]
860     fn size_hint(&self) -> (usize, Option<usize>) {
861         let len = self.len - self.index;
862         (len, Some(len))
863     }
864
865     #[inline]
866     fn next_back(&mut self) -> Option<(A::Item, B::Item)>
867         where A: DoubleEndedIterator + ExactSizeIterator,
868               B: DoubleEndedIterator + ExactSizeIterator
869     {
870         // Adjust a, b to equal length
871         if A::may_have_side_effect() {
872             let sz = self.a.len();
873             if sz > self.len {
874                 for _ in 0..sz - cmp::max(self.len, self.index) {
875                     self.a.next_back();
876                 }
877             }
878         }
879         if B::may_have_side_effect() {
880             let sz = self.b.len();
881             if sz > self.len {
882                 for _ in 0..sz - self.len {
883                     self.b.next_back();
884                 }
885             }
886         }
887         if self.index < self.len {
888             self.len -= 1;
889             let i = self.len;
890             unsafe {
891                 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
892             }
893         } else {
894             None
895         }
896     }
897 }
898
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<A, B> ExactSizeIterator for Zip<A, B>
901     where A: ExactSizeIterator, B: ExactSizeIterator {}
902
903 #[doc(hidden)]
904 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
905     where A: TrustedRandomAccess,
906           B: TrustedRandomAccess,
907 {
908     unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
909         (self.a.get_unchecked(i), self.b.get_unchecked(i))
910     }
911
912     fn may_have_side_effect() -> bool {
913         A::may_have_side_effect() || B::may_have_side_effect()
914     }
915 }
916
917 #[unstable(feature = "fused", issue = "35602")]
918 impl<A, B> FusedIterator for Zip<A, B>
919     where A: FusedIterator, B: FusedIterator, {}
920
921 #[unstable(feature = "trusted_len", issue = "37572")]
922 unsafe impl<A, B> TrustedLen for Zip<A, B>
923     where A: TrustedLen, B: TrustedLen,
924 {}
925
926 /// An iterator that maps the values of `iter` with `f`.
927 ///
928 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
929 /// documentation for more.
930 ///
931 /// [`map()`]: trait.Iterator.html#method.map
932 /// [`Iterator`]: trait.Iterator.html
933 ///
934 /// # Notes about side effects
935 ///
936 /// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
937 /// you can also [`map()`] backwards:
938 ///
939 /// ```rust
940 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
941 ///
942 /// assert_eq!(v, [4, 3, 2]);
943 /// ```
944 ///
945 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
946 ///
947 /// But if your closure has state, iterating backwards may act in a way you do
948 /// not expect. Let's go through an example. First, in the forward direction:
949 ///
950 /// ```rust
951 /// let mut c = 0;
952 ///
953 /// for pair in vec!['a', 'b', 'c'].into_iter()
954 ///                                .map(|letter| { c += 1; (letter, c) }) {
955 ///     println!("{:?}", pair);
956 /// }
957 /// ```
958 ///
959 /// This will print "('a', 1), ('b', 2), ('c', 3)".
960 ///
961 /// Now consider this twist where we add a call to `rev`. This version will
962 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
963 /// but the values of the counter still go in order. This is because `map()` is
964 /// still being called lazilly on each item, but we are popping items off the
965 /// back of the vector now, instead of shifting them from the front.
966 ///
967 /// ```rust
968 /// let mut c = 0;
969 ///
970 /// for pair in vec!['a', 'b', 'c'].into_iter()
971 ///                                .map(|letter| { c += 1; (letter, c) })
972 ///                                .rev() {
973 ///     println!("{:?}", pair);
974 /// }
975 /// ```
976 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
977 #[stable(feature = "rust1", since = "1.0.0")]
978 #[derive(Clone)]
979 pub struct Map<I, F> {
980     iter: I,
981     f: F,
982 }
983
984 #[stable(feature = "core_impl_debug", since = "1.9.0")]
985 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
986     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
987         f.debug_struct("Map")
988             .field("iter", &self.iter)
989             .finish()
990     }
991 }
992
993 #[stable(feature = "rust1", since = "1.0.0")]
994 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
995     type Item = B;
996
997     #[inline]
998     fn next(&mut self) -> Option<B> {
999         self.iter.next().map(&mut self.f)
1000     }
1001
1002     #[inline]
1003     fn size_hint(&self) -> (usize, Option<usize>) {
1004         self.iter.size_hint()
1005     }
1006
1007     fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1008         where G: FnMut(Acc, Self::Item) -> Acc,
1009     {
1010         let mut f = self.f;
1011         self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
1012     }
1013 }
1014
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
1017     F: FnMut(I::Item) -> B,
1018 {
1019     #[inline]
1020     fn next_back(&mut self) -> Option<B> {
1021         self.iter.next_back().map(&mut self.f)
1022     }
1023 }
1024
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
1027     where F: FnMut(I::Item) -> B
1028 {
1029     fn len(&self) -> usize {
1030         self.iter.len()
1031     }
1032
1033     fn is_empty(&self) -> bool {
1034         self.iter.is_empty()
1035     }
1036 }
1037
1038 #[unstable(feature = "fused", issue = "35602")]
1039 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1040     where F: FnMut(I::Item) -> B {}
1041
1042 #[unstable(feature = "trusted_len", issue = "37572")]
1043 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1044     where I: TrustedLen,
1045           F: FnMut(I::Item) -> B {}
1046
1047 #[doc(hidden)]
1048 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1049     where I: TrustedRandomAccess,
1050           F: FnMut(I::Item) -> B,
1051 {
1052     unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1053         (self.f)(self.iter.get_unchecked(i))
1054     }
1055     #[inline]
1056     fn may_have_side_effect() -> bool { true }
1057 }
1058
1059 /// An iterator that filters the elements of `iter` with `predicate`.
1060 ///
1061 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
1062 /// documentation for more.
1063 ///
1064 /// [`filter()`]: trait.Iterator.html#method.filter
1065 /// [`Iterator`]: trait.Iterator.html
1066 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 #[derive(Clone)]
1069 pub struct Filter<I, P> {
1070     iter: I,
1071     predicate: P,
1072 }
1073
1074 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1075 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1076     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1077         f.debug_struct("Filter")
1078             .field("iter", &self.iter)
1079             .finish()
1080     }
1081 }
1082
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
1085     type Item = I::Item;
1086
1087     #[inline]
1088     fn next(&mut self) -> Option<I::Item> {
1089         for x in self.iter.by_ref() {
1090             if (self.predicate)(&x) {
1091                 return Some(x);
1092             }
1093         }
1094         None
1095     }
1096
1097     #[inline]
1098     fn size_hint(&self) -> (usize, Option<usize>) {
1099         let (_, upper) = self.iter.size_hint();
1100         (0, upper) // can't know a lower bound, due to the predicate
1101     }
1102 }
1103
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1106     where P: FnMut(&I::Item) -> bool,
1107 {
1108     #[inline]
1109     fn next_back(&mut self) -> Option<I::Item> {
1110         for x in self.iter.by_ref().rev() {
1111             if (self.predicate)(&x) {
1112                 return Some(x);
1113             }
1114         }
1115         None
1116     }
1117 }
1118
1119 #[unstable(feature = "fused", issue = "35602")]
1120 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1121     where P: FnMut(&I::Item) -> bool {}
1122
1123 /// An iterator that uses `f` to both filter and map elements from `iter`.
1124 ///
1125 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
1126 /// documentation for more.
1127 ///
1128 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
1129 /// [`Iterator`]: trait.Iterator.html
1130 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 #[derive(Clone)]
1133 pub struct FilterMap<I, F> {
1134     iter: I,
1135     f: F,
1136 }
1137
1138 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1139 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1140     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1141         f.debug_struct("FilterMap")
1142             .field("iter", &self.iter)
1143             .finish()
1144     }
1145 }
1146
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1149     where F: FnMut(I::Item) -> Option<B>,
1150 {
1151     type Item = B;
1152
1153     #[inline]
1154     fn next(&mut self) -> Option<B> {
1155         for x in self.iter.by_ref() {
1156             if let Some(y) = (self.f)(x) {
1157                 return Some(y);
1158             }
1159         }
1160         None
1161     }
1162
1163     #[inline]
1164     fn size_hint(&self) -> (usize, Option<usize>) {
1165         let (_, upper) = self.iter.size_hint();
1166         (0, upper) // can't know a lower bound, due to the predicate
1167     }
1168 }
1169
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1172     where F: FnMut(I::Item) -> Option<B>,
1173 {
1174     #[inline]
1175     fn next_back(&mut self) -> Option<B> {
1176         for x in self.iter.by_ref().rev() {
1177             if let Some(y) = (self.f)(x) {
1178                 return Some(y);
1179             }
1180         }
1181         None
1182     }
1183 }
1184
1185 #[unstable(feature = "fused", issue = "35602")]
1186 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1187     where F: FnMut(I::Item) -> Option<B> {}
1188
1189 /// An iterator that yields the current count and the element during iteration.
1190 ///
1191 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
1192 /// documentation for more.
1193 ///
1194 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
1195 /// [`Iterator`]: trait.Iterator.html
1196 #[derive(Clone, Debug)]
1197 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub struct Enumerate<I> {
1200     iter: I,
1201     count: usize,
1202 }
1203
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl<I> Iterator for Enumerate<I> where I: Iterator {
1206     type Item = (usize, <I as Iterator>::Item);
1207
1208     /// # Overflow Behavior
1209     ///
1210     /// The method does no guarding against overflows, so enumerating more than
1211     /// `usize::MAX` elements either produces the wrong result or panics. If
1212     /// debug assertions are enabled, a panic is guaranteed.
1213     ///
1214     /// # Panics
1215     ///
1216     /// Might panic if the index of the element overflows a `usize`.
1217     #[inline]
1218     #[rustc_inherit_overflow_checks]
1219     fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1220         self.iter.next().map(|a| {
1221             let ret = (self.count, a);
1222             // Possible undefined overflow.
1223             self.count += 1;
1224             ret
1225         })
1226     }
1227
1228     #[inline]
1229     fn size_hint(&self) -> (usize, Option<usize>) {
1230         self.iter.size_hint()
1231     }
1232
1233     #[inline]
1234     #[rustc_inherit_overflow_checks]
1235     fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1236         self.iter.nth(n).map(|a| {
1237             let i = self.count + n;
1238             self.count = i + 1;
1239             (i, a)
1240         })
1241     }
1242
1243     #[inline]
1244     fn count(self) -> usize {
1245         self.iter.count()
1246     }
1247 }
1248
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<I> DoubleEndedIterator for Enumerate<I> where
1251     I: ExactSizeIterator + DoubleEndedIterator
1252 {
1253     #[inline]
1254     fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1255         self.iter.next_back().map(|a| {
1256             let len = self.iter.len();
1257             // Can safely add, `ExactSizeIterator` promises that the number of
1258             // elements fits into a `usize`.
1259             (self.count + len, a)
1260         })
1261     }
1262 }
1263
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1266     fn len(&self) -> usize {
1267         self.iter.len()
1268     }
1269
1270     fn is_empty(&self) -> bool {
1271         self.iter.is_empty()
1272     }
1273 }
1274
1275 #[doc(hidden)]
1276 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1277     where I: TrustedRandomAccess
1278 {
1279     unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1280         (self.count + i, self.iter.get_unchecked(i))
1281     }
1282
1283     fn may_have_side_effect() -> bool {
1284         I::may_have_side_effect()
1285     }
1286 }
1287
1288 #[unstable(feature = "fused", issue = "35602")]
1289 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1290
1291 #[unstable(feature = "trusted_len", issue = "37572")]
1292 unsafe impl<I> TrustedLen for Enumerate<I>
1293     where I: TrustedLen,
1294 {}
1295
1296
1297 /// An iterator with a `peek()` that returns an optional reference to the next
1298 /// element.
1299 ///
1300 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
1301 /// documentation for more.
1302 ///
1303 /// [`peekable()`]: trait.Iterator.html#method.peekable
1304 /// [`Iterator`]: trait.Iterator.html
1305 #[derive(Clone, Debug)]
1306 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 pub struct Peekable<I: Iterator> {
1309     iter: I,
1310     /// Remember a peeked value, even if it was None.
1311     peeked: Option<Option<I::Item>>,
1312 }
1313
1314 // Peekable must remember if a None has been seen in the `.peek()` method.
1315 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1316 // underlying iterator at most once. This does not by itself make the iterator
1317 // fused.
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<I: Iterator> Iterator for Peekable<I> {
1320     type Item = I::Item;
1321
1322     #[inline]
1323     fn next(&mut self) -> Option<I::Item> {
1324         match self.peeked.take() {
1325             Some(v) => v,
1326             None => self.iter.next(),
1327         }
1328     }
1329
1330     #[inline]
1331     #[rustc_inherit_overflow_checks]
1332     fn count(mut self) -> usize {
1333         match self.peeked.take() {
1334             Some(None) => 0,
1335             Some(Some(_)) => 1 + self.iter.count(),
1336             None => self.iter.count(),
1337         }
1338     }
1339
1340     #[inline]
1341     fn nth(&mut self, n: usize) -> Option<I::Item> {
1342         match self.peeked.take() {
1343             // the .take() below is just to avoid "move into pattern guard"
1344             Some(ref mut v) if n == 0 => v.take(),
1345             Some(None) => None,
1346             Some(Some(_)) => self.iter.nth(n - 1),
1347             None => self.iter.nth(n),
1348         }
1349     }
1350
1351     #[inline]
1352     fn last(mut self) -> Option<I::Item> {
1353         let peek_opt = match self.peeked.take() {
1354             Some(None) => return None,
1355             Some(v) => v,
1356             None => None,
1357         };
1358         self.iter.last().or(peek_opt)
1359     }
1360
1361     #[inline]
1362     fn size_hint(&self) -> (usize, Option<usize>) {
1363         let peek_len = match self.peeked {
1364             Some(None) => return (0, Some(0)),
1365             Some(Some(_)) => 1,
1366             None => 0,
1367         };
1368         let (lo, hi) = self.iter.size_hint();
1369         let lo = lo.saturating_add(peek_len);
1370         let hi = hi.and_then(|x| x.checked_add(peek_len));
1371         (lo, hi)
1372     }
1373 }
1374
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1377
1378 #[unstable(feature = "fused", issue = "35602")]
1379 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1380
1381 impl<I: Iterator> Peekable<I> {
1382     /// Returns a reference to the next() value without advancing the iterator.
1383     ///
1384     /// Like [`next()`], if there is a value, it is wrapped in a `Some(T)`.
1385     /// But if the iteration is over, `None` is returned.
1386     ///
1387     /// [`next()`]: trait.Iterator.html#tymethod.next
1388     ///
1389     /// Because `peek()` returns a reference, and many iterators iterate over
1390     /// references, there can be a possibly confusing situation where the
1391     /// return value is a double reference. You can see this effect in the
1392     /// examples below.
1393     ///
1394     /// # Examples
1395     ///
1396     /// Basic usage:
1397     ///
1398     /// ```
1399     /// let xs = [1, 2, 3];
1400     ///
1401     /// let mut iter = xs.iter().peekable();
1402     ///
1403     /// // peek() lets us see into the future
1404     /// assert_eq!(iter.peek(), Some(&&1));
1405     /// assert_eq!(iter.next(), Some(&1));
1406     ///
1407     /// assert_eq!(iter.next(), Some(&2));
1408     ///
1409     /// // The iterator does not advance even if we `peek` multiple times
1410     /// assert_eq!(iter.peek(), Some(&&3));
1411     /// assert_eq!(iter.peek(), Some(&&3));
1412     ///
1413     /// assert_eq!(iter.next(), Some(&3));
1414     ///
1415     /// // After the iterator is finished, so is `peek()`
1416     /// assert_eq!(iter.peek(), None);
1417     /// assert_eq!(iter.next(), None);
1418     /// ```
1419     #[inline]
1420     #[stable(feature = "rust1", since = "1.0.0")]
1421     pub fn peek(&mut self) -> Option<&I::Item> {
1422         if self.peeked.is_none() {
1423             self.peeked = Some(self.iter.next());
1424         }
1425         match self.peeked {
1426             Some(Some(ref value)) => Some(value),
1427             Some(None) => None,
1428             _ => unreachable!(),
1429         }
1430     }
1431 }
1432
1433 /// An iterator that rejects elements while `predicate` is true.
1434 ///
1435 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
1436 /// documentation for more.
1437 ///
1438 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
1439 /// [`Iterator`]: trait.Iterator.html
1440 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 #[derive(Clone)]
1443 pub struct SkipWhile<I, P> {
1444     iter: I,
1445     flag: bool,
1446     predicate: P,
1447 }
1448
1449 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1450 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1451     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1452         f.debug_struct("SkipWhile")
1453             .field("iter", &self.iter)
1454             .field("flag", &self.flag)
1455             .finish()
1456     }
1457 }
1458
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1461     where P: FnMut(&I::Item) -> bool
1462 {
1463     type Item = I::Item;
1464
1465     #[inline]
1466     fn next(&mut self) -> Option<I::Item> {
1467         for x in self.iter.by_ref() {
1468             if self.flag || !(self.predicate)(&x) {
1469                 self.flag = true;
1470                 return Some(x);
1471             }
1472         }
1473         None
1474     }
1475
1476     #[inline]
1477     fn size_hint(&self) -> (usize, Option<usize>) {
1478         let (_, upper) = self.iter.size_hint();
1479         (0, upper) // can't know a lower bound, due to the predicate
1480     }
1481 }
1482
1483 #[unstable(feature = "fused", issue = "35602")]
1484 impl<I, P> FusedIterator for SkipWhile<I, P>
1485     where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1486
1487 /// An iterator that only accepts elements while `predicate` is true.
1488 ///
1489 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
1490 /// documentation for more.
1491 ///
1492 /// [`take_while()`]: trait.Iterator.html#method.take_while
1493 /// [`Iterator`]: trait.Iterator.html
1494 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 #[derive(Clone)]
1497 pub struct TakeWhile<I, P> {
1498     iter: I,
1499     flag: bool,
1500     predicate: P,
1501 }
1502
1503 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1504 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1505     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1506         f.debug_struct("TakeWhile")
1507             .field("iter", &self.iter)
1508             .field("flag", &self.flag)
1509             .finish()
1510     }
1511 }
1512
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1515     where P: FnMut(&I::Item) -> bool
1516 {
1517     type Item = I::Item;
1518
1519     #[inline]
1520     fn next(&mut self) -> Option<I::Item> {
1521         if self.flag {
1522             None
1523         } else {
1524             self.iter.next().and_then(|x| {
1525                 if (self.predicate)(&x) {
1526                     Some(x)
1527                 } else {
1528                     self.flag = true;
1529                     None
1530                 }
1531             })
1532         }
1533     }
1534
1535     #[inline]
1536     fn size_hint(&self) -> (usize, Option<usize>) {
1537         let (_, upper) = self.iter.size_hint();
1538         (0, upper) // can't know a lower bound, due to the predicate
1539     }
1540 }
1541
1542 #[unstable(feature = "fused", issue = "35602")]
1543 impl<I, P> FusedIterator for TakeWhile<I, P>
1544     where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1545
1546 /// An iterator that skips over `n` elements of `iter`.
1547 ///
1548 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
1549 /// documentation for more.
1550 ///
1551 /// [`skip()`]: trait.Iterator.html#method.skip
1552 /// [`Iterator`]: trait.Iterator.html
1553 #[derive(Clone, Debug)]
1554 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 pub struct Skip<I> {
1557     iter: I,
1558     n: usize
1559 }
1560
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<I> Iterator for Skip<I> where I: Iterator {
1563     type Item = <I as Iterator>::Item;
1564
1565     #[inline]
1566     fn next(&mut self) -> Option<I::Item> {
1567         if self.n == 0 {
1568             self.iter.next()
1569         } else {
1570             let old_n = self.n;
1571             self.n = 0;
1572             self.iter.nth(old_n)
1573         }
1574     }
1575
1576     #[inline]
1577     fn nth(&mut self, n: usize) -> Option<I::Item> {
1578         // Can't just add n + self.n due to overflow.
1579         if self.n == 0 {
1580             self.iter.nth(n)
1581         } else {
1582             let to_skip = self.n;
1583             self.n = 0;
1584             // nth(n) skips n+1
1585             if self.iter.nth(to_skip-1).is_none() {
1586                 return None;
1587             }
1588             self.iter.nth(n)
1589         }
1590     }
1591
1592     #[inline]
1593     fn count(self) -> usize {
1594         self.iter.count().saturating_sub(self.n)
1595     }
1596
1597     #[inline]
1598     fn last(mut self) -> Option<I::Item> {
1599         if self.n == 0 {
1600             self.iter.last()
1601         } else {
1602             let next = self.next();
1603             if next.is_some() {
1604                 // recurse. n should be 0.
1605                 self.last().or(next)
1606             } else {
1607                 None
1608             }
1609         }
1610     }
1611
1612     #[inline]
1613     fn size_hint(&self) -> (usize, Option<usize>) {
1614         let (lower, upper) = self.iter.size_hint();
1615
1616         let lower = lower.saturating_sub(self.n);
1617         let upper = upper.map(|x| x.saturating_sub(self.n));
1618
1619         (lower, upper)
1620     }
1621 }
1622
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1625
1626 #[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
1627 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1628     fn next_back(&mut self) -> Option<Self::Item> {
1629         if self.len() > 0 {
1630             self.iter.next_back()
1631         } else {
1632             None
1633         }
1634     }
1635 }
1636
1637 #[unstable(feature = "fused", issue = "35602")]
1638 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
1639
1640 /// An iterator that only iterates over the first `n` iterations of `iter`.
1641 ///
1642 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
1643 /// documentation for more.
1644 ///
1645 /// [`take()`]: trait.Iterator.html#method.take
1646 /// [`Iterator`]: trait.Iterator.html
1647 #[derive(Clone, Debug)]
1648 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 pub struct Take<I> {
1651     iter: I,
1652     n: usize
1653 }
1654
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<I> Iterator for Take<I> where I: Iterator{
1657     type Item = <I as Iterator>::Item;
1658
1659     #[inline]
1660     fn next(&mut self) -> Option<<I as Iterator>::Item> {
1661         if self.n != 0 {
1662             self.n -= 1;
1663             self.iter.next()
1664         } else {
1665             None
1666         }
1667     }
1668
1669     #[inline]
1670     fn nth(&mut self, n: usize) -> Option<I::Item> {
1671         if self.n > n {
1672             self.n -= n + 1;
1673             self.iter.nth(n)
1674         } else {
1675             if self.n > 0 {
1676                 self.iter.nth(self.n - 1);
1677                 self.n = 0;
1678             }
1679             None
1680         }
1681     }
1682
1683     #[inline]
1684     fn size_hint(&self) -> (usize, Option<usize>) {
1685         let (lower, upper) = self.iter.size_hint();
1686
1687         let lower = cmp::min(lower, self.n);
1688
1689         let upper = match upper {
1690             Some(x) if x < self.n => Some(x),
1691             _ => Some(self.n)
1692         };
1693
1694         (lower, upper)
1695     }
1696 }
1697
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1700
1701 #[unstable(feature = "fused", issue = "35602")]
1702 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
1703
1704 /// An iterator to maintain state while iterating another iterator.
1705 ///
1706 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
1707 /// documentation for more.
1708 ///
1709 /// [`scan()`]: trait.Iterator.html#method.scan
1710 /// [`Iterator`]: trait.Iterator.html
1711 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 #[derive(Clone)]
1714 pub struct Scan<I, St, F> {
1715     iter: I,
1716     f: F,
1717     state: St,
1718 }
1719
1720 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1721 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1722     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1723         f.debug_struct("Scan")
1724             .field("iter", &self.iter)
1725             .field("state", &self.state)
1726             .finish()
1727     }
1728 }
1729
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1732     I: Iterator,
1733     F: FnMut(&mut St, I::Item) -> Option<B>,
1734 {
1735     type Item = B;
1736
1737     #[inline]
1738     fn next(&mut self) -> Option<B> {
1739         self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1740     }
1741
1742     #[inline]
1743     fn size_hint(&self) -> (usize, Option<usize>) {
1744         let (_, upper) = self.iter.size_hint();
1745         (0, upper) // can't know a lower bound, due to the scan function
1746     }
1747 }
1748
1749 #[unstable(feature = "fused", issue = "35602")]
1750 impl<B, I, St, F> FusedIterator for Scan<I, St, F>
1751     where I: FusedIterator, F: FnMut(&mut St, I::Item) -> Option<B> {}
1752
1753 /// An iterator that maps each element to an iterator, and yields the elements
1754 /// of the produced iterators.
1755 ///
1756 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
1757 /// documentation for more.
1758 ///
1759 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
1760 /// [`Iterator`]: trait.Iterator.html
1761 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 #[derive(Clone)]
1764 pub struct FlatMap<I, U: IntoIterator, F> {
1765     iter: I,
1766     f: F,
1767     frontiter: Option<U::IntoIter>,
1768     backiter: Option<U::IntoIter>,
1769 }
1770
1771 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1772 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1773     where U::IntoIter: fmt::Debug
1774 {
1775     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1776         f.debug_struct("FlatMap")
1777             .field("iter", &self.iter)
1778             .field("frontiter", &self.frontiter)
1779             .field("backiter", &self.backiter)
1780             .finish()
1781     }
1782 }
1783
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1786     where F: FnMut(I::Item) -> U,
1787 {
1788     type Item = U::Item;
1789
1790     #[inline]
1791     fn next(&mut self) -> Option<U::Item> {
1792         loop {
1793             if let Some(ref mut inner) = self.frontiter {
1794                 if let Some(x) = inner.by_ref().next() {
1795                     return Some(x)
1796                 }
1797             }
1798             match self.iter.next().map(&mut self.f) {
1799                 None => return self.backiter.as_mut().and_then(|it| it.next()),
1800                 next => self.frontiter = next.map(IntoIterator::into_iter),
1801             }
1802         }
1803     }
1804
1805     #[inline]
1806     fn size_hint(&self) -> (usize, Option<usize>) {
1807         let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1808         let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1809         let lo = flo.saturating_add(blo);
1810         match (self.iter.size_hint(), fhi, bhi) {
1811             ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1812             _ => (lo, None)
1813         }
1814     }
1815 }
1816
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1819     F: FnMut(I::Item) -> U,
1820     U: IntoIterator,
1821     U::IntoIter: DoubleEndedIterator
1822 {
1823     #[inline]
1824     fn next_back(&mut self) -> Option<U::Item> {
1825         loop {
1826             if let Some(ref mut inner) = self.backiter {
1827                 if let Some(y) = inner.next_back() {
1828                     return Some(y)
1829                 }
1830             }
1831             match self.iter.next_back().map(&mut self.f) {
1832                 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1833                 next => self.backiter = next.map(IntoIterator::into_iter),
1834             }
1835         }
1836     }
1837 }
1838
1839 #[unstable(feature = "fused", issue = "35602")]
1840 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
1841     where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
1842
1843 /// An iterator that yields `None` forever after the underlying iterator
1844 /// yields `None` once.
1845 ///
1846 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
1847 /// documentation for more.
1848 ///
1849 /// [`fuse()`]: trait.Iterator.html#method.fuse
1850 /// [`Iterator`]: trait.Iterator.html
1851 #[derive(Clone, Debug)]
1852 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 pub struct Fuse<I> {
1855     iter: I,
1856     done: bool
1857 }
1858
1859 #[unstable(feature = "fused", issue = "35602")]
1860 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
1861
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<I> Iterator for Fuse<I> where I: Iterator {
1864     type Item = <I as Iterator>::Item;
1865
1866     #[inline]
1867     default fn next(&mut self) -> Option<<I as Iterator>::Item> {
1868         if self.done {
1869             None
1870         } else {
1871             let next = self.iter.next();
1872             self.done = next.is_none();
1873             next
1874         }
1875     }
1876
1877     #[inline]
1878     default fn nth(&mut self, n: usize) -> Option<I::Item> {
1879         if self.done {
1880             None
1881         } else {
1882             let nth = self.iter.nth(n);
1883             self.done = nth.is_none();
1884             nth
1885         }
1886     }
1887
1888     #[inline]
1889     default fn last(self) -> Option<I::Item> {
1890         if self.done {
1891             None
1892         } else {
1893             self.iter.last()
1894         }
1895     }
1896
1897     #[inline]
1898     default fn count(self) -> usize {
1899         if self.done {
1900             0
1901         } else {
1902             self.iter.count()
1903         }
1904     }
1905
1906     #[inline]
1907     default fn size_hint(&self) -> (usize, Option<usize>) {
1908         if self.done {
1909             (0, Some(0))
1910         } else {
1911             self.iter.size_hint()
1912         }
1913     }
1914 }
1915
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
1918     #[inline]
1919     default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1920         if self.done {
1921             None
1922         } else {
1923             let next = self.iter.next_back();
1924             self.done = next.is_none();
1925             next
1926         }
1927     }
1928 }
1929
1930 unsafe impl<I> TrustedRandomAccess for Fuse<I>
1931     where I: TrustedRandomAccess,
1932 {
1933     unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
1934         self.iter.get_unchecked(i)
1935     }
1936
1937     fn may_have_side_effect() -> bool {
1938         I::may_have_side_effect()
1939     }
1940 }
1941
1942 #[unstable(feature = "fused", issue = "35602")]
1943 impl<I> Iterator for Fuse<I> where I: FusedIterator {
1944     #[inline]
1945     fn next(&mut self) -> Option<<I as Iterator>::Item> {
1946         self.iter.next()
1947     }
1948
1949     #[inline]
1950     fn nth(&mut self, n: usize) -> Option<I::Item> {
1951         self.iter.nth(n)
1952     }
1953
1954     #[inline]
1955     fn last(self) -> Option<I::Item> {
1956         self.iter.last()
1957     }
1958
1959     #[inline]
1960     fn count(self) -> usize {
1961         self.iter.count()
1962     }
1963
1964     #[inline]
1965     fn size_hint(&self) -> (usize, Option<usize>) {
1966         self.iter.size_hint()
1967     }
1968 }
1969
1970 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
1971 impl<I> DoubleEndedIterator for Fuse<I>
1972     where I: DoubleEndedIterator + FusedIterator
1973 {
1974     #[inline]
1975     fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1976         self.iter.next_back()
1977     }
1978 }
1979
1980
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
1983     fn len(&self) -> usize {
1984         self.iter.len()
1985     }
1986
1987     fn is_empty(&self) -> bool {
1988         self.iter.is_empty()
1989     }
1990 }
1991
1992 /// An iterator that calls a function with a reference to each element before
1993 /// yielding it.
1994 ///
1995 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
1996 /// documentation for more.
1997 ///
1998 /// [`inspect()`]: trait.Iterator.html#method.inspect
1999 /// [`Iterator`]: trait.Iterator.html
2000 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2001 #[stable(feature = "rust1", since = "1.0.0")]
2002 #[derive(Clone)]
2003 pub struct Inspect<I, F> {
2004     iter: I,
2005     f: F,
2006 }
2007
2008 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2009 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2010     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2011         f.debug_struct("Inspect")
2012             .field("iter", &self.iter)
2013             .finish()
2014     }
2015 }
2016
2017 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2018     #[inline]
2019     fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2020         if let Some(ref a) = elt {
2021             (self.f)(a);
2022         }
2023
2024         elt
2025     }
2026 }
2027
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2030     type Item = I::Item;
2031
2032     #[inline]
2033     fn next(&mut self) -> Option<I::Item> {
2034         let next = self.iter.next();
2035         self.do_inspect(next)
2036     }
2037
2038     #[inline]
2039     fn size_hint(&self) -> (usize, Option<usize>) {
2040         self.iter.size_hint()
2041     }
2042 }
2043
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2046     where F: FnMut(&I::Item),
2047 {
2048     #[inline]
2049     fn next_back(&mut self) -> Option<I::Item> {
2050         let next = self.iter.next_back();
2051         self.do_inspect(next)
2052     }
2053 }
2054
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2057     where F: FnMut(&I::Item)
2058 {
2059     fn len(&self) -> usize {
2060         self.iter.len()
2061     }
2062
2063     fn is_empty(&self) -> bool {
2064         self.iter.is_empty()
2065     }
2066 }
2067
2068 #[unstable(feature = "fused", issue = "35602")]
2069 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
2070     where F: FnMut(&I::Item) {}