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 [`filter()`].
229 //! For more, see their documentation.
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`filter()`]: trait.Iterator.html#method.filter
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()`] method 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 iter_private::TrustedRandomAccess;
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub use self::iterator::Iterator;
310 #[unstable(feature = "step_trait",
311 reason = "likely to be replaced by finer-grained traits",
313 pub use self::range::Step;
314 #[unstable(feature = "step_by", reason = "recent addition",
316 pub use self::range::StepBy;
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};
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;
339 /// A 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 fn len(&self) -> usize {
377 fn is_empty(&self) -> bool {
382 #[unstable(feature = "fused", issue = "35602")]
383 impl<I> FusedIterator for Rev<I>
384 where I: FusedIterator + DoubleEndedIterator {}
386 #[unstable(feature = "trusted_len", issue = "37572")]
387 unsafe impl<I> TrustedLen for Rev<I>
388 where I: TrustedLen + DoubleEndedIterator {}
390 /// An iterator that clones the elements of an underlying iterator.
392 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
393 /// documentation for more.
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> {
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
410 fn next(&mut self) -> Option<T> {
411 self.it.next().cloned()
414 fn size_hint(&self) -> (usize, Option<usize>) {
418 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
419 where F: FnMut(Acc, Self::Item) -> Acc,
421 self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
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
429 fn next_back(&mut self) -> Option<T> {
430 self.it.next_back().cloned()
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
438 fn len(&self) -> usize {
442 fn is_empty(&self) -> bool {
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
453 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
454 where I: TrustedRandomAccess<Item=&'a T>, T: Clone
456 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
457 self.it.get_unchecked(i).clone()
461 fn may_have_side_effect() -> bool { true }
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>,
470 /// An iterator that repeats endlessly.
472 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
473 /// documentation for more.
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> {
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;
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() }
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,
503 _ => (usize::MAX, None)
508 #[unstable(feature = "fused", issue = "35602")]
509 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
511 /// An iterator that strings two iterators together.
513 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
514 /// documentation for more.
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> {
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
532 // It uses three states:
534 // - Both: `a` and `b` are remaining
535 // - Front: `a` remaining
536 // - Back: `b` remaining
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)]
542 // both front and back iterator are remaining
544 // only front is remaining
546 // only back is remaining
550 #[stable(feature = "rust1", since = "1.0.0")]
551 impl<A, B> Iterator for Chain<A, B> where
553 B: Iterator<Item = A::Item>
558 fn next(&mut self) -> Option<A::Item> {
560 ChainState::Both => match self.a.next() {
561 elt @ Some(..) => elt,
563 self.state = ChainState::Back;
567 ChainState::Front => self.a.next(),
568 ChainState::Back => self.b.next(),
573 #[rustc_inherit_overflow_checks]
574 fn count(self) -> usize {
576 ChainState::Both => self.a.count() + self.b.count(),
577 ChainState::Front => self.a.count(),
578 ChainState::Back => self.b.count(),
582 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
583 where F: FnMut(Acc, Self::Item) -> Acc,
585 let mut accum = init;
587 ChainState::Both | ChainState::Front => {
588 accum = self.a.fold(accum, &mut f);
593 ChainState::Both | ChainState::Back => {
594 accum = self.b.fold(accum, &mut f);
602 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
604 ChainState::Both | ChainState::Front => {
605 for x in self.a.by_ref() {
611 if let ChainState::Both = self.state {
612 self.state = ChainState::Back;
615 ChainState::Back => {}
617 if let ChainState::Back = self.state {
625 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
626 P: FnMut(&Self::Item) -> bool,
629 ChainState::Both => match self.a.find(&mut predicate) {
631 self.state = ChainState::Back;
632 self.b.find(predicate)
636 ChainState::Front => self.a.find(predicate),
637 ChainState::Back => self.b.find(predicate),
642 fn last(self) -> Option<A::Item> {
644 ChainState::Both => {
645 // Must exhaust a before b.
646 let a_last = self.a.last();
647 let b_last = self.b.last();
650 ChainState::Front => self.a.last(),
651 ChainState::Back => self.b.last()
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();
660 let lower = a_lower.saturating_add(b_lower);
662 let upper = match (a_upper, b_upper) {
663 (Some(x), Some(y)) => x.checked_add(y),
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>,
677 fn next_back(&mut self) -> Option<A::Item> {
679 ChainState::Both => match self.b.next_back() {
680 elt @ Some(..) => elt,
682 self.state = ChainState::Front;
686 ChainState::Front => self.a.next_back(),
687 ChainState::Back => self.b.next_back(),
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>,
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>,
704 /// An iterator that iterates two other iterators simultaneously.
706 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
707 /// documentation for more.
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> {
717 // index and len are only used by the specialized version of zip
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
725 type Item = (A::Item, B::Item);
728 fn next(&mut self) -> Option<Self::Item> {
733 fn size_hint(&self) -> (usize, Option<usize>) {
734 ZipImpl::size_hint(self)
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,
744 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
745 ZipImpl::next_back(self)
749 // Zip specialization trait
751 trait ZipImpl<A, B> {
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;
763 impl<A, B> ZipImpl<A, B> for Zip<A, B>
764 where A: Iterator, B: Iterator
766 type Item = (A::Item, B::Item);
767 default fn new(a: A, b: B) -> Self {
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| {
786 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
787 where A: DoubleEndedIterator + ExactSizeIterator,
788 B: DoubleEndedIterator + ExactSizeIterator
790 let a_sz = self.a.len();
791 let b_sz = self.b.len();
793 // Adjust a, b to equal length
795 for _ in 0..a_sz - b_sz { self.a.next_back(); }
797 for _ in 0..b_sz - a_sz { self.b.next_back(); }
800 match (self.a.next_back(), self.b.next_back()) {
801 (Some(x), Some(y)) => Some((x, y)),
802 (None, None) => None,
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();
812 let lower = cmp::min(a_lower, b_lower);
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),
826 impl<A, B> ZipImpl<A, B> for Zip<A, B>
827 where A: TrustedRandomAccess, B: TrustedRandomAccess
829 fn new(a: A, b: B) -> Self {
830 let len = cmp::min(a.len(), b.len());
840 fn next(&mut self) -> Option<(A::Item, B::Item)> {
841 if self.index < self.len {
845 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
847 } else if A::may_have_side_effect() && self.index < self.a.len() {
848 // match the base implementation's potential side effects
850 self.a.get_unchecked(self.index);
860 fn size_hint(&self) -> (usize, Option<usize>) {
861 let len = self.len - self.index;
866 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
867 where A: DoubleEndedIterator + ExactSizeIterator,
868 B: DoubleEndedIterator + ExactSizeIterator
870 // Adjust a, b to equal length
871 if A::may_have_side_effect() {
872 let sz = self.a.len();
874 for _ in 0..sz - cmp::max(self.len, self.index) {
879 if B::may_have_side_effect() {
880 let sz = self.b.len();
882 for _ in 0..sz - self.len {
887 if self.index < self.len {
891 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<A, B> ExactSizeIterator for Zip<A, B>
901 where A: ExactSizeIterator, B: ExactSizeIterator {}
904 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
905 where A: TrustedRandomAccess,
906 B: TrustedRandomAccess,
908 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
909 (self.a.get_unchecked(i), self.b.get_unchecked(i))
912 fn may_have_side_effect() -> bool {
913 A::may_have_side_effect() || B::may_have_side_effect()
917 #[unstable(feature = "fused", issue = "35602")]
918 impl<A, B> FusedIterator for Zip<A, B>
919 where A: FusedIterator, B: FusedIterator, {}
921 #[unstable(feature = "trusted_len", issue = "37572")]
922 unsafe impl<A, B> TrustedLen for Zip<A, B>
923 where A: TrustedLen, B: TrustedLen,
926 /// An iterator that maps the values of `iter` with `f`.
928 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
929 /// documentation for more.
931 /// [`map()`]: trait.Iterator.html#method.map
932 /// [`Iterator`]: trait.Iterator.html
934 /// # Notes about side effects
936 /// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
937 /// you can also [`map()`] backwards:
940 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
942 /// assert_eq!(v, [4, 3, 2]);
945 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
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:
953 /// for pair in vec!['a', 'b', 'c'].into_iter()
954 /// .map(|letter| { c += 1; (letter, c) }) {
955 /// println!("{:?}", pair);
959 /// This will print "('a', 1), ('b', 2), ('c', 3)".
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.
970 /// for pair in vec!['a', 'b', 'c'].into_iter()
971 /// .map(|letter| { c += 1; (letter, c) })
973 /// println!("{:?}", pair);
976 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
977 #[stable(feature = "rust1", since = "1.0.0")]
979 pub struct Map<I, F> {
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)
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 {
998 fn next(&mut self) -> Option<B> {
999 self.iter.next().map(&mut self.f)
1003 fn size_hint(&self) -> (usize, Option<usize>) {
1004 self.iter.size_hint()
1007 fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1008 where G: FnMut(Acc, Self::Item) -> Acc,
1011 self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
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,
1020 fn next_back(&mut self) -> Option<B> {
1021 self.iter.next_back().map(&mut self.f)
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
1029 fn len(&self) -> usize {
1033 fn is_empty(&self) -> bool {
1034 self.iter.is_empty()
1038 #[unstable(feature = "fused", issue = "35602")]
1039 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1040 where F: FnMut(I::Item) -> B {}
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 {}
1048 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1049 where I: TrustedRandomAccess,
1050 F: FnMut(I::Item) -> B,
1052 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1053 (self.f)(self.iter.get_unchecked(i))
1056 fn may_have_side_effect() -> bool { true }
1059 /// An iterator that filters the elements of `iter` with `predicate`.
1061 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
1062 /// documentation for more.
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")]
1069 pub struct Filter<I, P> {
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)
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;
1088 fn next(&mut self) -> Option<I::Item> {
1089 for x in &mut self.iter {
1090 if (self.predicate)(&x) {
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
1103 // this special case allows the compiler to make `.filter(_).count()`
1104 // branchless. Barring perfect branch prediction (which is unattainable in
1105 // the general case), this will be much faster in >90% of cases (containing
1106 // virtually all real workloads) and only a tiny bit slower in the rest.
1108 // Having this specialization thus allows us to write `.filter(p).count()`
1109 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1110 // less readable and also less backwards-compatible to Rust before 1.10.
1112 // Using the branchless version will also simplify the LLVM byte code, thus
1113 // leaving more budget for LLVM optimizations.
1115 fn count(mut self) -> usize {
1117 for x in &mut self.iter {
1118 count += (self.predicate)(&x) as usize;
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1126 where P: FnMut(&I::Item) -> bool,
1129 fn next_back(&mut self) -> Option<I::Item> {
1130 for x in self.iter.by_ref().rev() {
1131 if (self.predicate)(&x) {
1139 #[unstable(feature = "fused", issue = "35602")]
1140 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1141 where P: FnMut(&I::Item) -> bool {}
1143 /// An iterator that uses `f` to both filter and map elements from `iter`.
1145 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
1146 /// documentation for more.
1148 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
1149 /// [`Iterator`]: trait.Iterator.html
1150 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1151 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub struct FilterMap<I, F> {
1158 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1159 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1161 f.debug_struct("FilterMap")
1162 .field("iter", &self.iter)
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1169 where F: FnMut(I::Item) -> Option<B>,
1174 fn next(&mut self) -> Option<B> {
1175 for x in self.iter.by_ref() {
1176 if let Some(y) = (self.f)(x) {
1184 fn size_hint(&self) -> (usize, Option<usize>) {
1185 let (_, upper) = self.iter.size_hint();
1186 (0, upper) // can't know a lower bound, due to the predicate
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1192 where F: FnMut(I::Item) -> Option<B>,
1195 fn next_back(&mut self) -> Option<B> {
1196 for x in self.iter.by_ref().rev() {
1197 if let Some(y) = (self.f)(x) {
1205 #[unstable(feature = "fused", issue = "35602")]
1206 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1207 where F: FnMut(I::Item) -> Option<B> {}
1209 /// An iterator that yields the current count and the element during iteration.
1211 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
1212 /// documentation for more.
1214 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
1215 /// [`Iterator`]: trait.Iterator.html
1216 #[derive(Clone, Debug)]
1217 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub struct Enumerate<I> {
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 impl<I> Iterator for Enumerate<I> where I: Iterator {
1226 type Item = (usize, <I as Iterator>::Item);
1228 /// # Overflow Behavior
1230 /// The method does no guarding against overflows, so enumerating more than
1231 /// `usize::MAX` elements either produces the wrong result or panics. If
1232 /// debug assertions are enabled, a panic is guaranteed.
1236 /// Might panic if the index of the element overflows a `usize`.
1238 #[rustc_inherit_overflow_checks]
1239 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1240 self.iter.next().map(|a| {
1241 let ret = (self.count, a);
1242 // Possible undefined overflow.
1249 fn size_hint(&self) -> (usize, Option<usize>) {
1250 self.iter.size_hint()
1254 #[rustc_inherit_overflow_checks]
1255 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1256 self.iter.nth(n).map(|a| {
1257 let i = self.count + n;
1264 fn count(self) -> usize {
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<I> DoubleEndedIterator for Enumerate<I> where
1271 I: ExactSizeIterator + DoubleEndedIterator
1274 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1275 self.iter.next_back().map(|a| {
1276 let len = self.iter.len();
1277 // Can safely add, `ExactSizeIterator` promises that the number of
1278 // elements fits into a `usize`.
1279 (self.count + len, a)
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1286 fn len(&self) -> usize {
1290 fn is_empty(&self) -> bool {
1291 self.iter.is_empty()
1296 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1297 where I: TrustedRandomAccess
1299 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1300 (self.count + i, self.iter.get_unchecked(i))
1303 fn may_have_side_effect() -> bool {
1304 I::may_have_side_effect()
1308 #[unstable(feature = "fused", issue = "35602")]
1309 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1311 #[unstable(feature = "trusted_len", issue = "37572")]
1312 unsafe impl<I> TrustedLen for Enumerate<I>
1313 where I: TrustedLen,
1317 /// An iterator with a `peek()` that returns an optional reference to the next
1320 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
1321 /// documentation for more.
1323 /// [`peekable()`]: trait.Iterator.html#method.peekable
1324 /// [`Iterator`]: trait.Iterator.html
1325 #[derive(Clone, Debug)]
1326 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 pub struct Peekable<I: Iterator> {
1330 /// Remember a peeked value, even if it was None.
1331 peeked: Option<Option<I::Item>>,
1334 // Peekable must remember if a None has been seen in the `.peek()` method.
1335 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1336 // underlying iterator at most once. This does not by itself make the iterator
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 impl<I: Iterator> Iterator for Peekable<I> {
1340 type Item = I::Item;
1343 fn next(&mut self) -> Option<I::Item> {
1344 match self.peeked.take() {
1346 None => self.iter.next(),
1351 #[rustc_inherit_overflow_checks]
1352 fn count(mut self) -> usize {
1353 match self.peeked.take() {
1355 Some(Some(_)) => 1 + self.iter.count(),
1356 None => self.iter.count(),
1361 fn nth(&mut self, n: usize) -> Option<I::Item> {
1362 match self.peeked.take() {
1363 // the .take() below is just to avoid "move into pattern guard"
1364 Some(ref mut v) if n == 0 => v.take(),
1366 Some(Some(_)) => self.iter.nth(n - 1),
1367 None => self.iter.nth(n),
1372 fn last(mut self) -> Option<I::Item> {
1373 let peek_opt = match self.peeked.take() {
1374 Some(None) => return None,
1378 self.iter.last().or(peek_opt)
1382 fn size_hint(&self) -> (usize, Option<usize>) {
1383 let peek_len = match self.peeked {
1384 Some(None) => return (0, Some(0)),
1388 let (lo, hi) = self.iter.size_hint();
1389 let lo = lo.saturating_add(peek_len);
1390 let hi = hi.and_then(|x| x.checked_add(peek_len));
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1398 #[unstable(feature = "fused", issue = "35602")]
1399 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1401 impl<I: Iterator> Peekable<I> {
1402 /// Returns a reference to the next() value without advancing the iterator.
1404 /// Like [`next()`], if there is a value, it is wrapped in a `Some(T)`.
1405 /// But if the iteration is over, `None` is returned.
1407 /// [`next()`]: trait.Iterator.html#tymethod.next
1409 /// Because `peek()` returns a reference, and many iterators iterate over
1410 /// references, there can be a possibly confusing situation where the
1411 /// return value is a double reference. You can see this effect in the
1419 /// let xs = [1, 2, 3];
1421 /// let mut iter = xs.iter().peekable();
1423 /// // peek() lets us see into the future
1424 /// assert_eq!(iter.peek(), Some(&&1));
1425 /// assert_eq!(iter.next(), Some(&1));
1427 /// assert_eq!(iter.next(), Some(&2));
1429 /// // The iterator does not advance even if we `peek` multiple times
1430 /// assert_eq!(iter.peek(), Some(&&3));
1431 /// assert_eq!(iter.peek(), Some(&&3));
1433 /// assert_eq!(iter.next(), Some(&3));
1435 /// // After the iterator is finished, so is `peek()`
1436 /// assert_eq!(iter.peek(), None);
1437 /// assert_eq!(iter.next(), None);
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn peek(&mut self) -> Option<&I::Item> {
1442 if self.peeked.is_none() {
1443 self.peeked = Some(self.iter.next());
1446 Some(Some(ref value)) => Some(value),
1448 _ => unreachable!(),
1453 /// An iterator that rejects elements while `predicate` is true.
1455 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
1456 /// documentation for more.
1458 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
1459 /// [`Iterator`]: trait.Iterator.html
1460 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1461 #[stable(feature = "rust1", since = "1.0.0")]
1463 pub struct SkipWhile<I, P> {
1469 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1470 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1472 f.debug_struct("SkipWhile")
1473 .field("iter", &self.iter)
1474 .field("flag", &self.flag)
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1481 where P: FnMut(&I::Item) -> bool
1483 type Item = I::Item;
1486 fn next(&mut self) -> Option<I::Item> {
1487 for x in self.iter.by_ref() {
1488 if self.flag || !(self.predicate)(&x) {
1497 fn size_hint(&self) -> (usize, Option<usize>) {
1498 let (_, upper) = self.iter.size_hint();
1499 (0, upper) // can't know a lower bound, due to the predicate
1503 #[unstable(feature = "fused", issue = "35602")]
1504 impl<I, P> FusedIterator for SkipWhile<I, P>
1505 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1507 /// An iterator that only accepts elements while `predicate` is true.
1509 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
1510 /// documentation for more.
1512 /// [`take_while()`]: trait.Iterator.html#method.take_while
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 TakeWhile<I, P> {
1523 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1524 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1526 f.debug_struct("TakeWhile")
1527 .field("iter", &self.iter)
1528 .field("flag", &self.flag)
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1535 where P: FnMut(&I::Item) -> bool
1537 type Item = I::Item;
1540 fn next(&mut self) -> Option<I::Item> {
1544 self.iter.next().and_then(|x| {
1545 if (self.predicate)(&x) {
1556 fn size_hint(&self) -> (usize, Option<usize>) {
1557 let (_, upper) = self.iter.size_hint();
1558 (0, upper) // can't know a lower bound, due to the predicate
1562 #[unstable(feature = "fused", issue = "35602")]
1563 impl<I, P> FusedIterator for TakeWhile<I, P>
1564 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1566 /// An iterator that skips over `n` elements of `iter`.
1568 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
1569 /// documentation for more.
1571 /// [`skip()`]: trait.Iterator.html#method.skip
1572 /// [`Iterator`]: trait.Iterator.html
1573 #[derive(Clone, Debug)]
1574 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 pub struct Skip<I> {
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<I> Iterator for Skip<I> where I: Iterator {
1583 type Item = <I as Iterator>::Item;
1586 fn next(&mut self) -> Option<I::Item> {
1592 self.iter.nth(old_n)
1597 fn nth(&mut self, n: usize) -> Option<I::Item> {
1598 // Can't just add n + self.n due to overflow.
1602 let to_skip = self.n;
1605 if self.iter.nth(to_skip-1).is_none() {
1613 fn count(self) -> usize {
1614 self.iter.count().saturating_sub(self.n)
1618 fn last(mut self) -> Option<I::Item> {
1622 let next = self.next();
1624 // recurse. n should be 0.
1625 self.last().or(next)
1633 fn size_hint(&self) -> (usize, Option<usize>) {
1634 let (lower, upper) = self.iter.size_hint();
1636 let lower = lower.saturating_sub(self.n);
1637 let upper = upper.map(|x| x.saturating_sub(self.n));
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1646 #[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
1647 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1648 fn next_back(&mut self) -> Option<Self::Item> {
1650 self.iter.next_back()
1657 #[unstable(feature = "fused", issue = "35602")]
1658 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
1660 /// An iterator that only iterates over the first `n` iterations of `iter`.
1662 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
1663 /// documentation for more.
1665 /// [`take()`]: trait.Iterator.html#method.take
1666 /// [`Iterator`]: trait.Iterator.html
1667 #[derive(Clone, Debug)]
1668 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 pub struct Take<I> {
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<I> Iterator for Take<I> where I: Iterator{
1677 type Item = <I as Iterator>::Item;
1680 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1690 fn nth(&mut self, n: usize) -> Option<I::Item> {
1696 self.iter.nth(self.n - 1);
1704 fn size_hint(&self) -> (usize, Option<usize>) {
1705 let (lower, upper) = self.iter.size_hint();
1707 let lower = cmp::min(lower, self.n);
1709 let upper = match upper {
1710 Some(x) if x < self.n => Some(x),
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1721 #[unstable(feature = "fused", issue = "35602")]
1722 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
1724 /// An iterator to maintain state while iterating another iterator.
1726 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
1727 /// documentation for more.
1729 /// [`scan()`]: trait.Iterator.html#method.scan
1730 /// [`Iterator`]: trait.Iterator.html
1731 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1732 #[stable(feature = "rust1", since = "1.0.0")]
1734 pub struct Scan<I, St, F> {
1740 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1741 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1743 f.debug_struct("Scan")
1744 .field("iter", &self.iter)
1745 .field("state", &self.state)
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1753 F: FnMut(&mut St, I::Item) -> Option<B>,
1758 fn next(&mut self) -> Option<B> {
1759 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1763 fn size_hint(&self) -> (usize, Option<usize>) {
1764 let (_, upper) = self.iter.size_hint();
1765 (0, upper) // can't know a lower bound, due to the scan function
1769 #[unstable(feature = "fused", issue = "35602")]
1770 impl<B, I, St, F> FusedIterator for Scan<I, St, F>
1771 where I: FusedIterator, F: FnMut(&mut St, I::Item) -> Option<B> {}
1773 /// An iterator that maps each element to an iterator, and yields the elements
1774 /// of the produced iterators.
1776 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
1777 /// documentation for more.
1779 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
1780 /// [`Iterator`]: trait.Iterator.html
1781 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1782 #[stable(feature = "rust1", since = "1.0.0")]
1784 pub struct FlatMap<I, U: IntoIterator, F> {
1787 frontiter: Option<U::IntoIter>,
1788 backiter: Option<U::IntoIter>,
1791 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1792 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1793 where U::IntoIter: fmt::Debug
1795 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1796 f.debug_struct("FlatMap")
1797 .field("iter", &self.iter)
1798 .field("frontiter", &self.frontiter)
1799 .field("backiter", &self.backiter)
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1806 where F: FnMut(I::Item) -> U,
1808 type Item = U::Item;
1811 fn next(&mut self) -> Option<U::Item> {
1813 if let Some(ref mut inner) = self.frontiter {
1814 if let Some(x) = inner.by_ref().next() {
1818 match self.iter.next().map(&mut self.f) {
1819 None => return self.backiter.as_mut().and_then(|it| it.next()),
1820 next => self.frontiter = next.map(IntoIterator::into_iter),
1826 fn size_hint(&self) -> (usize, Option<usize>) {
1827 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1828 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1829 let lo = flo.saturating_add(blo);
1830 match (self.iter.size_hint(), fhi, bhi) {
1831 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1837 #[stable(feature = "rust1", since = "1.0.0")]
1838 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1839 F: FnMut(I::Item) -> U,
1841 U::IntoIter: DoubleEndedIterator
1844 fn next_back(&mut self) -> Option<U::Item> {
1846 if let Some(ref mut inner) = self.backiter {
1847 if let Some(y) = inner.next_back() {
1851 match self.iter.next_back().map(&mut self.f) {
1852 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1853 next => self.backiter = next.map(IntoIterator::into_iter),
1859 #[unstable(feature = "fused", issue = "35602")]
1860 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
1861 where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
1863 /// An iterator that yields `None` forever after the underlying iterator
1864 /// yields `None` once.
1866 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
1867 /// documentation for more.
1869 /// [`fuse()`]: trait.Iterator.html#method.fuse
1870 /// [`Iterator`]: trait.Iterator.html
1871 #[derive(Clone, Debug)]
1872 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub struct Fuse<I> {
1879 #[unstable(feature = "fused", issue = "35602")]
1880 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 impl<I> Iterator for Fuse<I> where I: Iterator {
1884 type Item = <I as Iterator>::Item;
1887 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
1891 let next = self.iter.next();
1892 self.done = next.is_none();
1898 default fn nth(&mut self, n: usize) -> Option<I::Item> {
1902 let nth = self.iter.nth(n);
1903 self.done = nth.is_none();
1909 default fn last(self) -> Option<I::Item> {
1918 default fn count(self) -> usize {
1927 default fn size_hint(&self) -> (usize, Option<usize>) {
1931 self.iter.size_hint()
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
1939 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1943 let next = self.iter.next_back();
1944 self.done = next.is_none();
1950 unsafe impl<I> TrustedRandomAccess for Fuse<I>
1951 where I: TrustedRandomAccess,
1953 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
1954 self.iter.get_unchecked(i)
1957 fn may_have_side_effect() -> bool {
1958 I::may_have_side_effect()
1962 #[unstable(feature = "fused", issue = "35602")]
1963 impl<I> Iterator for Fuse<I> where I: FusedIterator {
1965 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1970 fn nth(&mut self, n: usize) -> Option<I::Item> {
1975 fn last(self) -> Option<I::Item> {
1980 fn count(self) -> usize {
1985 fn size_hint(&self) -> (usize, Option<usize>) {
1986 self.iter.size_hint()
1990 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
1991 impl<I> DoubleEndedIterator for Fuse<I>
1992 where I: DoubleEndedIterator + FusedIterator
1995 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1996 self.iter.next_back()
2001 #[stable(feature = "rust1", since = "1.0.0")]
2002 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
2003 fn len(&self) -> usize {
2007 fn is_empty(&self) -> bool {
2008 self.iter.is_empty()
2012 /// An iterator that calls a function with a reference to each element before
2015 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
2016 /// documentation for more.
2018 /// [`inspect()`]: trait.Iterator.html#method.inspect
2019 /// [`Iterator`]: trait.Iterator.html
2020 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2021 #[stable(feature = "rust1", since = "1.0.0")]
2023 pub struct Inspect<I, F> {
2028 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2029 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2031 f.debug_struct("Inspect")
2032 .field("iter", &self.iter)
2037 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2039 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2040 if let Some(ref a) = elt {
2048 #[stable(feature = "rust1", since = "1.0.0")]
2049 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2050 type Item = I::Item;
2053 fn next(&mut self) -> Option<I::Item> {
2054 let next = self.iter.next();
2055 self.do_inspect(next)
2059 fn size_hint(&self) -> (usize, Option<usize>) {
2060 self.iter.size_hint()
2064 #[stable(feature = "rust1", since = "1.0.0")]
2065 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2066 where F: FnMut(&I::Item),
2069 fn next_back(&mut self) -> Option<I::Item> {
2070 let next = self.iter.next_back();
2071 self.do_inspect(next)
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2077 where F: FnMut(&I::Item)
2079 fn len(&self) -> usize {
2083 fn is_empty(&self) -> bool {
2084 self.iter.is_empty()
2088 #[unstable(feature = "fused", issue = "35602")]
2089 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
2090 where F: FnMut(&I::Item) {}