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.
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.
11 //! Composable external iteration.
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.
18 //! Before explaining more, let's talk about how this module is structured:
22 //! This module is largely organized by type:
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)'.
34 //! [Functions]: #functions
35 //! [Structs]: #structs
37 //! That's it! Let's dig into iterators.
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
47 //! fn next(&mut self) -> Option<Self::Item>;
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.
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
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.
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../../std/option/enum.Option.html
70 //! # The three forms of iteration
72 //! There are three common methods which can create iterators from a collection:
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
81 //! # Implementing Iterator
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.
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
91 //! // First, the struct:
93 //! /// An iterator which counts from one to five
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.
102 //! fn new() -> Counter {
103 //! Counter { count: 0 }
107 //! // Then, we implement `Iterator` for our `Counter`:
109 //! impl Iterator for Counter {
110 //! // we will be counting with usize
111 //! type Item = usize;
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.
118 //! // check to see if we've finished counting or not.
119 //! if self.count < 6 {
127 //! // And now we can use it!
129 //! let mut counter = Counter::new();
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
147 //! This will print `1` through `5`, each on their own line.
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
153 //! # for Loops and IntoIterator
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
159 //! let values = vec![1, 2, 3, 4, 5];
161 //! for x in values {
162 //! println!("{}", x);
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?
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
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
180 //! let values = vec![1, 2, 3, 4, 5];
182 //! for x in values {
183 //! println!("{}", x);
187 //! Rust de-sugars this into:
190 //! let values = vec![1, 2, 3, 4, 5];
192 //! let result = match IntoIterator::into_iter(values) {
193 //! mut iter => loop {
194 //! match iter.next() {
195 //! Some(x) => { println!("{}", x); },
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.
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
212 //! impl<I: Iterator> IntoIterator for I
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
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.
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
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:
244 //! # #![allow(unused_must_use)]
245 //! let v = vec![1, 2, 3, 4, 5];
246 //! v.iter().map(|x| println!("{}", x));
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:
253 //! warning: unused result which must be used: iterator adaptors are lazy and
254 //! do nothing unless consumed
257 //! The idiomatic way to write a [`map()`] for its side effects is to use a
258 //! `for` loop instead:
261 //! let v = vec![1, 2, 3, 4, 5];
264 //! println!("{}", x);
268 //! [`map()`]: trait.Iterator.html#method.map
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.
273 //! [`collect()`]: trait.Iterator.html#method.collect
277 //! Iterators do not have to be finite. As an example, an open-ended range is
278 //! an infinite iterator:
281 //! let numbers = 0..;
284 //! It is common to use the [`take()`] iterator adapter to turn an infinite
285 //! iterator into a finite one:
288 //! let numbers = 0..;
289 //! let five_numbers = numbers.take(5);
291 //! for number in five_numbers {
292 //! println!("{}", number);
296 //! This will print the numbers `0` through `4`, each on their own line.
298 //! [`take()`]: trait.Iterator.html#method.take
300 #![stable(feature = "rust1", since = "1.0.0")]
304 use default::Default;
306 use iter_private::TrustedRandomAccess;
308 use option::Option::{self, Some, None};
311 #[stable(feature = "rust1", since = "1.0.0")]
312 pub use self::iterator::Iterator;
314 #[unstable(feature = "step_trait",
315 reason = "likely to be replaced by finer-grained traits",
317 pub use self::range::Step;
318 #[unstable(feature = "step_by", reason = "recent addition",
320 pub use self::range::StepBy;
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub use self::sources::{Repeat, repeat};
324 #[stable(feature = "iter_empty", since = "1.2.0")]
325 pub use self::sources::{Empty, empty};
326 #[stable(feature = "iter_once", since = "1.2.0")]
327 pub use self::sources::{Once, once};
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend};
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub use self::traits::{ExactSizeIterator, Sum, Product};
339 /// An double-ended iterator with the direction inverted.
341 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
342 /// documentation for more.
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")]
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;
358 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
360 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
366 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<I> ExactSizeIterator for Rev<I>
371 where I: ExactSizeIterator + DoubleEndedIterator {}
373 /// An iterator that clones the elements of an underlying iterator.
375 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
376 /// documentation for more.
378 /// [`cloned()`]: trait.Iterator.html#method.cloned
379 /// [`Iterator`]: trait.Iterator.html
380 #[stable(feature = "iter_cloned", since = "1.1.0")]
381 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
382 #[derive(Clone, Debug)]
383 pub struct Cloned<I> {
387 #[stable(feature = "rust1", since = "1.0.0")]
388 impl<'a, I, T: 'a> Iterator for Cloned<I>
389 where I: Iterator<Item=&'a T>, T: Clone
393 fn next(&mut self) -> Option<T> {
394 self.it.next().cloned()
397 fn size_hint(&self) -> (usize, Option<usize>) {
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
404 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
406 fn next_back(&mut self) -> Option<T> {
407 self.it.next_back().cloned()
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
413 where I: ExactSizeIterator<Item=&'a T>, T: Clone
416 /// An iterator that repeats endlessly.
418 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
419 /// documentation for more.
421 /// [`cycle()`]: trait.Iterator.html#method.cycle
422 /// [`Iterator`]: trait.Iterator.html
423 #[derive(Clone, Debug)]
424 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
425 #[stable(feature = "rust1", since = "1.0.0")]
426 pub struct Cycle<I> {
431 #[stable(feature = "rust1", since = "1.0.0")]
432 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
433 type Item = <I as Iterator>::Item;
436 fn next(&mut self) -> Option<<I as Iterator>::Item> {
437 match self.iter.next() {
438 None => { self.iter = self.orig.clone(); self.iter.next() }
444 fn size_hint(&self) -> (usize, Option<usize>) {
445 // the cycle iterator is either empty or infinite
446 match self.orig.size_hint() {
447 sz @ (0, Some(0)) => sz,
449 _ => (usize::MAX, None)
454 /// An iterator that strings two iterators together.
456 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
457 /// documentation for more.
459 /// [`chain()`]: trait.Iterator.html#method.chain
460 /// [`Iterator`]: trait.Iterator.html
461 #[derive(Clone, Debug)]
462 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub struct Chain<A, B> {
470 // The iterator protocol specifies that iteration ends with the return value
471 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
472 // further calls return. The chain adaptor must account for this since it uses
475 // It uses three states:
477 // - Both: `a` and `b` are remaining
478 // - Front: `a` remaining
479 // - Back: `b` remaining
481 // The fourth state (neither iterator is remaining) only occurs after Chain has
482 // returned None once, so we don't need to store this state.
483 #[derive(Clone, Debug)]
485 // both front and back iterator are remaining
487 // only front is remaining
489 // only back is remaining
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl<A, B> Iterator for Chain<A, B> where
496 B: Iterator<Item = A::Item>
501 fn next(&mut self) -> Option<A::Item> {
503 ChainState::Both => match self.a.next() {
504 elt @ Some(..) => elt,
506 self.state = ChainState::Back;
510 ChainState::Front => self.a.next(),
511 ChainState::Back => self.b.next(),
516 #[rustc_inherit_overflow_checks]
517 fn count(self) -> usize {
519 ChainState::Both => self.a.count() + self.b.count(),
520 ChainState::Front => self.a.count(),
521 ChainState::Back => self.b.count(),
526 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
528 ChainState::Both | ChainState::Front => {
529 for x in self.a.by_ref() {
535 if let ChainState::Both = self.state {
536 self.state = ChainState::Back;
539 ChainState::Back => {}
541 if let ChainState::Back = self.state {
549 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
550 P: FnMut(&Self::Item) -> bool,
553 ChainState::Both => match self.a.find(&mut predicate) {
555 self.state = ChainState::Back;
556 self.b.find(predicate)
560 ChainState::Front => self.a.find(predicate),
561 ChainState::Back => self.b.find(predicate),
566 fn last(self) -> Option<A::Item> {
568 ChainState::Both => {
569 // Must exhaust a before b.
570 let a_last = self.a.last();
571 let b_last = self.b.last();
574 ChainState::Front => self.a.last(),
575 ChainState::Back => self.b.last()
580 fn size_hint(&self) -> (usize, Option<usize>) {
581 let (a_lower, a_upper) = self.a.size_hint();
582 let (b_lower, b_upper) = self.b.size_hint();
584 let lower = a_lower.saturating_add(b_lower);
586 let upper = match (a_upper, b_upper) {
587 (Some(x), Some(y)) => x.checked_add(y),
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl<A, B> DoubleEndedIterator for Chain<A, B> where
597 A: DoubleEndedIterator,
598 B: DoubleEndedIterator<Item=A::Item>,
601 fn next_back(&mut self) -> Option<A::Item> {
603 ChainState::Both => match self.b.next_back() {
604 elt @ Some(..) => elt,
606 self.state = ChainState::Front;
610 ChainState::Front => self.a.next_back(),
611 ChainState::Back => self.b.next_back(),
616 /// An iterator that iterates two other iterators simultaneously.
618 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
619 /// documentation for more.
621 /// [`zip()`]: trait.Iterator.html#method.zip
622 /// [`Iterator`]: trait.Iterator.html
623 #[derive(Clone, Debug)]
624 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub struct Zip<A, B> {
629 spec: <(A, B) as ZipImplData>::Data,
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
635 type Item = (A::Item, B::Item);
638 fn next(&mut self) -> Option<Self::Item> {
643 fn size_hint(&self) -> (usize, Option<usize>) {
644 ZipImpl::size_hint(self)
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<A, B> DoubleEndedIterator for Zip<A, B> where
650 A: DoubleEndedIterator + ExactSizeIterator,
651 B: DoubleEndedIterator + ExactSizeIterator,
654 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
655 ZipImpl::next_back(self)
659 // Zip specialization trait
661 trait ZipImpl<A, B> {
663 fn new(a: A, b: B) -> Self;
664 fn next(&mut self) -> Option<Self::Item>;
665 fn size_hint(&self) -> (usize, Option<usize>);
666 fn next_back(&mut self) -> Option<Self::Item>
667 where A: DoubleEndedIterator + ExactSizeIterator,
668 B: DoubleEndedIterator + ExactSizeIterator;
671 // Zip specialization data members
674 type Data: 'static + Clone + Default + fmt::Debug;
678 impl<T> ZipImplData for T {
679 default type Data = ();
684 impl<A, B> ZipImpl<A, B> for Zip<A, B>
685 where A: Iterator, B: Iterator
687 type Item = (A::Item, B::Item);
688 default fn new(a: A, b: B) -> Self {
692 spec: Default::default(), // unused
697 default fn next(&mut self) -> Option<(A::Item, B::Item)> {
698 self.a.next().and_then(|x| {
699 self.b.next().and_then(|y| {
706 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
707 where A: DoubleEndedIterator + ExactSizeIterator,
708 B: DoubleEndedIterator + ExactSizeIterator
710 let a_sz = self.a.len();
711 let b_sz = self.b.len();
713 // Adjust a, b to equal length
715 for _ in 0..a_sz - b_sz { self.a.next_back(); }
717 for _ in 0..b_sz - a_sz { self.b.next_back(); }
720 match (self.a.next_back(), self.b.next_back()) {
721 (Some(x), Some(y)) => Some((x, y)),
722 (None, None) => None,
728 default fn size_hint(&self) -> (usize, Option<usize>) {
729 let (a_lower, a_upper) = self.a.size_hint();
730 let (b_lower, b_upper) = self.b.size_hint();
732 let lower = cmp::min(a_lower, b_lower);
734 let upper = match (a_upper, b_upper) {
735 (Some(x), Some(y)) => Some(cmp::min(x,y)),
736 (Some(x), None) => Some(x),
737 (None, Some(y)) => Some(y),
746 #[derive(Default, Debug, Clone)]
747 struct ZipImplFields {
753 impl<A, B> ZipImplData for (A, B)
754 where A: TrustedRandomAccess, B: TrustedRandomAccess
756 type Data = ZipImplFields;
760 impl<A, B> ZipImpl<A, B> for Zip<A, B>
761 where A: TrustedRandomAccess, B: TrustedRandomAccess
763 fn new(a: A, b: B) -> Self {
764 let len = cmp::min(a.len(), b.len());
768 spec: ZipImplFields {
776 fn next(&mut self) -> Option<(A::Item, B::Item)> {
777 if self.spec.index < self.spec.len {
778 let i = self.spec.index;
779 self.spec.index += 1;
781 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
789 fn size_hint(&self) -> (usize, Option<usize>) {
790 let len = self.spec.len - self.spec.index;
795 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
796 where A: DoubleEndedIterator + ExactSizeIterator,
797 B: DoubleEndedIterator + ExactSizeIterator
799 if self.spec.index < self.spec.len {
801 let i = self.spec.len;
803 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl<A, B> ExactSizeIterator for Zip<A, B>
813 where A: ExactSizeIterator, B: ExactSizeIterator {}
816 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
817 where A: TrustedRandomAccess,
818 B: TrustedRandomAccess,
820 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
821 (self.a.get_unchecked(i), self.b.get_unchecked(i))
826 /// An iterator that maps the values of `iter` with `f`.
828 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
829 /// documentation for more.
831 /// [`map()`]: trait.Iterator.html#method.map
832 /// [`Iterator`]: trait.Iterator.html
834 /// # Notes about side effects
836 /// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
837 /// you can also [`map()`] backwards:
840 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
842 /// assert_eq!(v, [4, 3, 2]);
845 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
847 /// But if your closure has state, iterating backwards may act in a way you do
848 /// not expect. Let's go through an example. First, in the forward direction:
853 /// for pair in vec!['a', 'b', 'c'].into_iter()
854 /// .map(|letter| { c += 1; (letter, c) }) {
855 /// println!("{:?}", pair);
859 /// This will print "('a', 1), ('b', 2), ('c', 3)".
861 /// Now consider this twist where we add a call to `rev`. This version will
862 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
863 /// but the values of the counter still go in order. This is because `map()` is
864 /// still being called lazilly on each item, but we are popping items off the
865 /// back of the vector now, instead of shifting them from the front.
870 /// for pair in vec!['a', 'b', 'c'].into_iter()
871 /// .map(|letter| { c += 1; (letter, c) })
873 /// println!("{:?}", pair);
876 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
877 #[stable(feature = "rust1", since = "1.0.0")]
879 pub struct Map<I, F> {
884 #[stable(feature = "core_impl_debug", since = "1.9.0")]
885 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
886 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887 f.debug_struct("Map")
888 .field("iter", &self.iter)
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
898 fn next(&mut self) -> Option<B> {
899 self.iter.next().map(&mut self.f)
903 fn size_hint(&self) -> (usize, Option<usize>) {
904 self.iter.size_hint()
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
910 F: FnMut(I::Item) -> B,
913 fn next_back(&mut self) -> Option<B> {
914 self.iter.next_back().map(&mut self.f)
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
920 where F: FnMut(I::Item) -> B {}
922 /// An iterator that filters the elements of `iter` with `predicate`.
924 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
925 /// documentation for more.
927 /// [`filter()`]: trait.Iterator.html#method.filter
928 /// [`Iterator`]: trait.Iterator.html
929 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
930 #[stable(feature = "rust1", since = "1.0.0")]
932 pub struct Filter<I, P> {
937 #[stable(feature = "core_impl_debug", since = "1.9.0")]
938 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
939 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
940 f.debug_struct("Filter")
941 .field("iter", &self.iter)
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
951 fn next(&mut self) -> Option<I::Item> {
952 for x in self.iter.by_ref() {
953 if (self.predicate)(&x) {
961 fn size_hint(&self) -> (usize, Option<usize>) {
962 let (_, upper) = self.iter.size_hint();
963 (0, upper) // can't know a lower bound, due to the predicate
967 #[stable(feature = "rust1", since = "1.0.0")]
968 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
969 where P: FnMut(&I::Item) -> bool,
972 fn next_back(&mut self) -> Option<I::Item> {
973 for x in self.iter.by_ref().rev() {
974 if (self.predicate)(&x) {
982 /// An iterator that uses `f` to both filter and map elements from `iter`.
984 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
985 /// documentation for more.
987 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
988 /// [`Iterator`]: trait.Iterator.html
989 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
990 #[stable(feature = "rust1", since = "1.0.0")]
992 pub struct FilterMap<I, F> {
997 #[stable(feature = "core_impl_debug", since = "1.9.0")]
998 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1000 f.debug_struct("FilterMap")
1001 .field("iter", &self.iter)
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1008 where F: FnMut(I::Item) -> Option<B>,
1013 fn next(&mut self) -> Option<B> {
1014 for x in self.iter.by_ref() {
1015 if let Some(y) = (self.f)(x) {
1023 fn size_hint(&self) -> (usize, Option<usize>) {
1024 let (_, upper) = self.iter.size_hint();
1025 (0, upper) // can't know a lower bound, due to the predicate
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1031 where F: FnMut(I::Item) -> Option<B>,
1034 fn next_back(&mut self) -> Option<B> {
1035 for x in self.iter.by_ref().rev() {
1036 if let Some(y) = (self.f)(x) {
1044 /// An iterator that yields the current count and the element during iteration.
1046 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
1047 /// documentation for more.
1049 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
1050 /// [`Iterator`]: trait.Iterator.html
1051 #[derive(Clone, Debug)]
1052 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 pub struct Enumerate<I> {
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<I> Iterator for Enumerate<I> where I: Iterator {
1061 type Item = (usize, <I as Iterator>::Item);
1063 /// # Overflow Behavior
1065 /// The method does no guarding against overflows, so enumerating more than
1066 /// `usize::MAX` elements either produces the wrong result or panics. If
1067 /// debug assertions are enabled, a panic is guaranteed.
1071 /// Might panic if the index of the element overflows a `usize`.
1073 #[rustc_inherit_overflow_checks]
1074 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1075 self.iter.next().map(|a| {
1076 let ret = (self.count, a);
1077 // Possible undefined overflow.
1084 fn size_hint(&self) -> (usize, Option<usize>) {
1085 self.iter.size_hint()
1089 #[rustc_inherit_overflow_checks]
1090 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1091 self.iter.nth(n).map(|a| {
1092 let i = self.count + n;
1099 fn count(self) -> usize {
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<I> DoubleEndedIterator for Enumerate<I> where
1106 I: ExactSizeIterator + DoubleEndedIterator
1109 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1110 self.iter.next_back().map(|a| {
1111 let len = self.iter.len();
1112 // Can safely add, `ExactSizeIterator` promises that the number of
1113 // elements fits into a `usize`.
1114 (self.count + len, a)
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1123 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1124 where I: TrustedRandomAccess
1126 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1127 (self.count + i, self.iter.get_unchecked(i))
1131 /// An iterator with a `peek()` that returns an optional reference to the next
1134 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
1135 /// documentation for more.
1137 /// [`peekable()`]: trait.Iterator.html#method.peekable
1138 /// [`Iterator`]: trait.Iterator.html
1139 #[derive(Clone, Debug)]
1140 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub struct Peekable<I: Iterator> {
1144 peeked: Option<I::Item>,
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<I: Iterator> Iterator for Peekable<I> {
1149 type Item = I::Item;
1152 fn next(&mut self) -> Option<I::Item> {
1154 Some(_) => self.peeked.take(),
1155 None => self.iter.next(),
1160 #[rustc_inherit_overflow_checks]
1161 fn count(self) -> usize {
1162 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
1166 fn nth(&mut self, n: usize) -> Option<I::Item> {
1168 Some(_) if n == 0 => self.peeked.take(),
1173 None => self.iter.nth(n)
1178 fn last(self) -> Option<I::Item> {
1179 self.iter.last().or(self.peeked)
1183 fn size_hint(&self) -> (usize, Option<usize>) {
1184 let (lo, hi) = self.iter.size_hint();
1185 if self.peeked.is_some() {
1186 let lo = lo.saturating_add(1);
1187 let hi = hi.and_then(|x| x.checked_add(1));
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1198 impl<I: Iterator> Peekable<I> {
1199 /// Returns a reference to the next() value without advancing the iterator.
1201 /// Like [`next()`], if there is a value, it is wrapped in a `Some(T)`.
1202 /// But if the iteration is over, `None` is returned.
1204 /// [`next()`]: trait.Iterator.html#tymethod.next
1206 /// Because `peek()` returns a reference, and many iterators iterate over
1207 /// references, there can be a possibly confusing situation where the
1208 /// return value is a double reference. You can see this effect in the
1216 /// let xs = [1, 2, 3];
1218 /// let mut iter = xs.iter().peekable();
1220 /// // peek() lets us see into the future
1221 /// assert_eq!(iter.peek(), Some(&&1));
1222 /// assert_eq!(iter.next(), Some(&1));
1224 /// assert_eq!(iter.next(), Some(&2));
1226 /// // The iterator does not advance even if we `peek` multiple times
1227 /// assert_eq!(iter.peek(), Some(&&3));
1228 /// assert_eq!(iter.peek(), Some(&&3));
1230 /// assert_eq!(iter.next(), Some(&3));
1232 /// // After the iterator is finished, so is `peek()`
1233 /// assert_eq!(iter.peek(), None);
1234 /// assert_eq!(iter.next(), None);
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub fn peek(&mut self) -> Option<&I::Item> {
1239 if self.peeked.is_none() {
1240 self.peeked = self.iter.next();
1243 Some(ref value) => Some(value),
1249 /// An iterator that rejects elements while `predicate` is true.
1251 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
1252 /// documentation for more.
1254 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
1255 /// [`Iterator`]: trait.Iterator.html
1256 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1257 #[stable(feature = "rust1", since = "1.0.0")]
1259 pub struct SkipWhile<I, P> {
1265 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1266 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1268 f.debug_struct("SkipWhile")
1269 .field("iter", &self.iter)
1270 .field("flag", &self.flag)
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1277 where P: FnMut(&I::Item) -> bool
1279 type Item = I::Item;
1282 fn next(&mut self) -> Option<I::Item> {
1283 for x in self.iter.by_ref() {
1284 if self.flag || !(self.predicate)(&x) {
1293 fn size_hint(&self) -> (usize, Option<usize>) {
1294 let (_, upper) = self.iter.size_hint();
1295 (0, upper) // can't know a lower bound, due to the predicate
1299 /// An iterator that only accepts elements while `predicate` is true.
1301 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
1302 /// documentation for more.
1304 /// [`take_while()`]: trait.Iterator.html#method.take_while
1305 /// [`Iterator`]: trait.Iterator.html
1306 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1307 #[stable(feature = "rust1", since = "1.0.0")]
1309 pub struct TakeWhile<I, P> {
1315 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1316 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 f.debug_struct("TakeWhile")
1319 .field("iter", &self.iter)
1320 .field("flag", &self.flag)
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1327 where P: FnMut(&I::Item) -> bool
1329 type Item = I::Item;
1332 fn next(&mut self) -> Option<I::Item> {
1336 self.iter.next().and_then(|x| {
1337 if (self.predicate)(&x) {
1348 fn size_hint(&self) -> (usize, Option<usize>) {
1349 let (_, upper) = self.iter.size_hint();
1350 (0, upper) // can't know a lower bound, due to the predicate
1354 /// An iterator that skips over `n` elements of `iter`.
1356 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
1357 /// documentation for more.
1359 /// [`skip()`]: trait.Iterator.html#method.skip
1360 /// [`Iterator`]: trait.Iterator.html
1361 #[derive(Clone, Debug)]
1362 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 pub struct Skip<I> {
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<I> Iterator for Skip<I> where I: Iterator {
1371 type Item = <I as Iterator>::Item;
1374 fn next(&mut self) -> Option<I::Item> {
1380 self.iter.nth(old_n)
1385 fn nth(&mut self, n: usize) -> Option<I::Item> {
1386 // Can't just add n + self.n due to overflow.
1390 let to_skip = self.n;
1393 if self.iter.nth(to_skip-1).is_none() {
1401 fn count(self) -> usize {
1402 self.iter.count().saturating_sub(self.n)
1406 fn last(mut self) -> Option<I::Item> {
1410 let next = self.next();
1412 // recurse. n should be 0.
1413 self.last().or(next)
1421 fn size_hint(&self) -> (usize, Option<usize>) {
1422 let (lower, upper) = self.iter.size_hint();
1424 let lower = lower.saturating_sub(self.n);
1425 let upper = upper.map(|x| x.saturating_sub(self.n));
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1434 #[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
1435 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1436 fn next_back(&mut self) -> Option<Self::Item> {
1438 self.iter.next_back()
1445 /// An iterator that only iterates over the first `n` iterations of `iter`.
1447 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
1448 /// documentation for more.
1450 /// [`take()`]: trait.Iterator.html#method.take
1451 /// [`Iterator`]: trait.Iterator.html
1452 #[derive(Clone, Debug)]
1453 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 pub struct Take<I> {
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl<I> Iterator for Take<I> where I: Iterator{
1462 type Item = <I as Iterator>::Item;
1465 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1475 fn nth(&mut self, n: usize) -> Option<I::Item> {
1481 self.iter.nth(self.n - 1);
1489 fn size_hint(&self) -> (usize, Option<usize>) {
1490 let (lower, upper) = self.iter.size_hint();
1492 let lower = cmp::min(lower, self.n);
1494 let upper = match upper {
1495 Some(x) if x < self.n => Some(x),
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1507 /// An iterator to maintain state while iterating another iterator.
1509 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
1510 /// documentation for more.
1512 /// [`scan()`]: trait.Iterator.html#method.scan
1513 /// [`Iterator`]: trait.Iterator.html
1514 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1515 #[stable(feature = "rust1", since = "1.0.0")]
1517 pub struct Scan<I, St, F> {
1523 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1524 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1526 f.debug_struct("Scan")
1527 .field("iter", &self.iter)
1528 .field("state", &self.state)
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1536 F: FnMut(&mut St, I::Item) -> Option<B>,
1541 fn next(&mut self) -> Option<B> {
1542 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1546 fn size_hint(&self) -> (usize, Option<usize>) {
1547 let (_, upper) = self.iter.size_hint();
1548 (0, upper) // can't know a lower bound, due to the scan function
1552 /// An iterator that maps each element to an iterator, and yields the elements
1553 /// of the produced iterators.
1555 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
1556 /// documentation for more.
1558 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
1559 /// [`Iterator`]: trait.Iterator.html
1560 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1561 #[stable(feature = "rust1", since = "1.0.0")]
1563 pub struct FlatMap<I, U: IntoIterator, F> {
1566 frontiter: Option<U::IntoIter>,
1567 backiter: Option<U::IntoIter>,
1570 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1571 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1572 where U::IntoIter: fmt::Debug
1574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1575 f.debug_struct("FlatMap")
1576 .field("iter", &self.iter)
1577 .field("frontiter", &self.frontiter)
1578 .field("backiter", &self.backiter)
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1585 where F: FnMut(I::Item) -> U,
1587 type Item = U::Item;
1590 fn next(&mut self) -> Option<U::Item> {
1592 if let Some(ref mut inner) = self.frontiter {
1593 if let Some(x) = inner.by_ref().next() {
1597 match self.iter.next().map(&mut self.f) {
1598 None => return self.backiter.as_mut().and_then(|it| it.next()),
1599 next => self.frontiter = next.map(IntoIterator::into_iter),
1605 fn size_hint(&self) -> (usize, Option<usize>) {
1606 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1607 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1608 let lo = flo.saturating_add(blo);
1609 match (self.iter.size_hint(), fhi, bhi) {
1610 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1618 F: FnMut(I::Item) -> U,
1620 U::IntoIter: DoubleEndedIterator
1623 fn next_back(&mut self) -> Option<U::Item> {
1625 if let Some(ref mut inner) = self.backiter {
1626 if let Some(y) = inner.next_back() {
1630 match self.iter.next_back().map(&mut self.f) {
1631 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1632 next => self.backiter = next.map(IntoIterator::into_iter),
1638 /// An iterator that yields `None` forever after the underlying iterator
1639 /// yields `None` once.
1641 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
1642 /// documentation for more.
1644 /// [`fuse()`]: trait.Iterator.html#method.fuse
1645 /// [`Iterator`]: trait.Iterator.html
1646 #[derive(Clone, Debug)]
1647 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 pub struct Fuse<I> {
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl<I> Iterator for Fuse<I> where I: Iterator {
1656 type Item = <I as Iterator>::Item;
1659 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1663 let next = self.iter.next();
1664 self.done = next.is_none();
1670 fn nth(&mut self, n: usize) -> Option<I::Item> {
1674 let nth = self.iter.nth(n);
1675 self.done = nth.is_none();
1681 fn last(self) -> Option<I::Item> {
1690 fn count(self) -> usize {
1699 fn size_hint(&self) -> (usize, Option<usize>) {
1703 self.iter.size_hint()
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
1711 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1715 let next = self.iter.next_back();
1716 self.done = next.is_none();
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
1725 /// An iterator that calls a function with a reference to each element before
1728 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
1729 /// documentation for more.
1731 /// [`inspect()`]: trait.Iterator.html#method.inspect
1732 /// [`Iterator`]: trait.Iterator.html
1733 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1734 #[stable(feature = "rust1", since = "1.0.0")]
1736 pub struct Inspect<I, F> {
1741 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1742 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
1743 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1744 f.debug_struct("Inspect")
1745 .field("iter", &self.iter)
1750 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
1752 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
1753 if let Some(ref a) = elt {
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
1763 type Item = I::Item;
1766 fn next(&mut self) -> Option<I::Item> {
1767 let next = self.iter.next();
1768 self.do_inspect(next)
1772 fn size_hint(&self) -> (usize, Option<usize>) {
1773 self.iter.size_hint()
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
1779 where F: FnMut(&I::Item),
1782 fn next_back(&mut self) -> Option<I::Item> {
1783 let next = self.iter.next_back();
1784 self.do_inspect(next)
1788 #[stable(feature = "rust1", since = "1.0.0")]
1789 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
1790 where F: FnMut(&I::Item) {}