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() }
362 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
363 where P: FnMut(&Self::Item) -> bool
365 self.iter.rfind(predicate)
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
372 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
374 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
375 where P: FnMut(&Self::Item) -> bool
377 self.iter.find(predicate)
381 #[stable(feature = "rust1", since = "1.0.0")]
382 impl<I> ExactSizeIterator for Rev<I>
383 where I: ExactSizeIterator + DoubleEndedIterator
385 fn len(&self) -> usize {
389 fn is_empty(&self) -> bool {
394 #[unstable(feature = "fused", issue = "35602")]
395 impl<I> FusedIterator for Rev<I>
396 where I: FusedIterator + DoubleEndedIterator {}
398 #[unstable(feature = "trusted_len", issue = "37572")]
399 unsafe impl<I> TrustedLen for Rev<I>
400 where I: TrustedLen + DoubleEndedIterator {}
402 /// An iterator that clones the elements of an underlying iterator.
404 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
405 /// documentation for more.
407 /// [`cloned`]: trait.Iterator.html#method.cloned
408 /// [`Iterator`]: trait.Iterator.html
409 #[stable(feature = "iter_cloned", since = "1.1.0")]
410 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
411 #[derive(Clone, Debug)]
412 pub struct Cloned<I> {
416 #[stable(feature = "iter_cloned", since = "1.1.0")]
417 impl<'a, I, T: 'a> Iterator for Cloned<I>
418 where I: Iterator<Item=&'a T>, T: Clone
422 fn next(&mut self) -> Option<T> {
423 self.it.next().cloned()
426 fn size_hint(&self) -> (usize, Option<usize>) {
430 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
431 where F: FnMut(Acc, Self::Item) -> Acc,
433 self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
437 #[stable(feature = "iter_cloned", since = "1.1.0")]
438 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
439 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
441 fn next_back(&mut self) -> Option<T> {
442 self.it.next_back().cloned()
446 #[stable(feature = "iter_cloned", since = "1.1.0")]
447 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
448 where I: ExactSizeIterator<Item=&'a T>, T: Clone
450 fn len(&self) -> usize {
454 fn is_empty(&self) -> bool {
459 #[unstable(feature = "fused", issue = "35602")]
460 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
461 where I: FusedIterator<Item=&'a T>, T: Clone
465 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
466 where I: TrustedRandomAccess<Item=&'a T>, T: Clone
468 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
469 self.it.get_unchecked(i).clone()
473 fn may_have_side_effect() -> bool { true }
476 #[unstable(feature = "trusted_len", issue = "37572")]
477 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
478 where I: TrustedLen<Item=&'a T>,
482 /// An iterator that repeats endlessly.
484 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
485 /// documentation for more.
487 /// [`cycle`]: trait.Iterator.html#method.cycle
488 /// [`Iterator`]: trait.Iterator.html
489 #[derive(Clone, Debug)]
490 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub struct Cycle<I> {
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
499 type Item = <I as Iterator>::Item;
502 fn next(&mut self) -> Option<<I as Iterator>::Item> {
503 match self.iter.next() {
504 None => { self.iter = self.orig.clone(); self.iter.next() }
510 fn size_hint(&self) -> (usize, Option<usize>) {
511 // the cycle iterator is either empty or infinite
512 match self.orig.size_hint() {
513 sz @ (0, Some(0)) => sz,
515 _ => (usize::MAX, None)
520 #[unstable(feature = "fused", issue = "35602")]
521 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
523 /// An iterator that strings two iterators together.
525 /// This `struct` is created by the [`chain`] method on [`Iterator`]. See its
526 /// documentation for more.
528 /// [`chain`]: trait.Iterator.html#method.chain
529 /// [`Iterator`]: trait.Iterator.html
530 #[derive(Clone, Debug)]
531 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub struct Chain<A, B> {
539 // The iterator protocol specifies that iteration ends with the return value
540 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
541 // further calls return. The chain adaptor must account for this since it uses
544 // It uses three states:
546 // - Both: `a` and `b` are remaining
547 // - Front: `a` remaining
548 // - Back: `b` remaining
550 // The fourth state (neither iterator is remaining) only occurs after Chain has
551 // returned None once, so we don't need to store this state.
552 #[derive(Clone, Debug)]
554 // both front and back iterator are remaining
556 // only front is remaining
558 // only back is remaining
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<A, B> Iterator for Chain<A, B> where
565 B: Iterator<Item = A::Item>
570 fn next(&mut self) -> Option<A::Item> {
572 ChainState::Both => match self.a.next() {
573 elt @ Some(..) => elt,
575 self.state = ChainState::Back;
579 ChainState::Front => self.a.next(),
580 ChainState::Back => self.b.next(),
585 #[rustc_inherit_overflow_checks]
586 fn count(self) -> usize {
588 ChainState::Both => self.a.count() + self.b.count(),
589 ChainState::Front => self.a.count(),
590 ChainState::Back => self.b.count(),
594 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
595 where F: FnMut(Acc, Self::Item) -> Acc,
597 let mut accum = init;
599 ChainState::Both | ChainState::Front => {
600 accum = self.a.fold(accum, &mut f);
605 ChainState::Both | ChainState::Back => {
606 accum = self.b.fold(accum, &mut f);
614 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
616 ChainState::Both | ChainState::Front => {
617 for x in self.a.by_ref() {
623 if let ChainState::Both = self.state {
624 self.state = ChainState::Back;
627 ChainState::Back => {}
629 if let ChainState::Back = self.state {
637 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
638 P: FnMut(&Self::Item) -> bool,
641 ChainState::Both => match self.a.find(&mut predicate) {
643 self.state = ChainState::Back;
644 self.b.find(predicate)
648 ChainState::Front => self.a.find(predicate),
649 ChainState::Back => self.b.find(predicate),
654 fn last(self) -> Option<A::Item> {
656 ChainState::Both => {
657 // Must exhaust a before b.
658 let a_last = self.a.last();
659 let b_last = self.b.last();
662 ChainState::Front => self.a.last(),
663 ChainState::Back => self.b.last()
668 fn size_hint(&self) -> (usize, Option<usize>) {
669 let (a_lower, a_upper) = self.a.size_hint();
670 let (b_lower, b_upper) = self.b.size_hint();
672 let lower = a_lower.saturating_add(b_lower);
674 let upper = match (a_upper, b_upper) {
675 (Some(x), Some(y)) => x.checked_add(y),
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl<A, B> DoubleEndedIterator for Chain<A, B> where
685 A: DoubleEndedIterator,
686 B: DoubleEndedIterator<Item=A::Item>,
689 fn next_back(&mut self) -> Option<A::Item> {
691 ChainState::Both => match self.b.next_back() {
692 elt @ Some(..) => elt,
694 self.state = ChainState::Front;
698 ChainState::Front => self.a.next_back(),
699 ChainState::Back => self.b.next_back(),
704 // Note: *both* must be fused to handle double-ended iterators.
705 #[unstable(feature = "fused", issue = "35602")]
706 impl<A, B> FusedIterator for Chain<A, B>
707 where A: FusedIterator,
708 B: FusedIterator<Item=A::Item>,
711 #[unstable(feature = "trusted_len", issue = "37572")]
712 unsafe impl<A, B> TrustedLen for Chain<A, B>
713 where A: TrustedLen, B: TrustedLen<Item=A::Item>,
716 /// An iterator that iterates two other iterators simultaneously.
718 /// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
719 /// documentation for more.
721 /// [`zip`]: trait.Iterator.html#method.zip
722 /// [`Iterator`]: trait.Iterator.html
723 #[derive(Clone, Debug)]
724 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
725 #[stable(feature = "rust1", since = "1.0.0")]
726 pub struct Zip<A, B> {
729 // index and len are only used by the specialized version of zip
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
737 type Item = (A::Item, B::Item);
740 fn next(&mut self) -> Option<Self::Item> {
745 fn size_hint(&self) -> (usize, Option<usize>) {
746 ZipImpl::size_hint(self)
750 #[stable(feature = "rust1", since = "1.0.0")]
751 impl<A, B> DoubleEndedIterator for Zip<A, B> where
752 A: DoubleEndedIterator + ExactSizeIterator,
753 B: DoubleEndedIterator + ExactSizeIterator,
756 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
757 ZipImpl::next_back(self)
761 // Zip specialization trait
763 trait ZipImpl<A, B> {
765 fn new(a: A, b: B) -> Self;
766 fn next(&mut self) -> Option<Self::Item>;
767 fn size_hint(&self) -> (usize, Option<usize>);
768 fn next_back(&mut self) -> Option<Self::Item>
769 where A: DoubleEndedIterator + ExactSizeIterator,
770 B: DoubleEndedIterator + ExactSizeIterator;
775 impl<A, B> ZipImpl<A, B> for Zip<A, B>
776 where A: Iterator, B: Iterator
778 type Item = (A::Item, B::Item);
779 default fn new(a: A, b: B) -> Self {
789 default fn next(&mut self) -> Option<(A::Item, B::Item)> {
790 self.a.next().and_then(|x| {
791 self.b.next().and_then(|y| {
798 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
799 where A: DoubleEndedIterator + ExactSizeIterator,
800 B: DoubleEndedIterator + ExactSizeIterator
802 let a_sz = self.a.len();
803 let b_sz = self.b.len();
805 // Adjust a, b to equal length
807 for _ in 0..a_sz - b_sz { self.a.next_back(); }
809 for _ in 0..b_sz - a_sz { self.b.next_back(); }
812 match (self.a.next_back(), self.b.next_back()) {
813 (Some(x), Some(y)) => Some((x, y)),
814 (None, None) => None,
820 default fn size_hint(&self) -> (usize, Option<usize>) {
821 let (a_lower, a_upper) = self.a.size_hint();
822 let (b_lower, b_upper) = self.b.size_hint();
824 let lower = cmp::min(a_lower, b_lower);
826 let upper = match (a_upper, b_upper) {
827 (Some(x), Some(y)) => Some(cmp::min(x,y)),
828 (Some(x), None) => Some(x),
829 (None, Some(y)) => Some(y),
838 impl<A, B> ZipImpl<A, B> for Zip<A, B>
839 where A: TrustedRandomAccess, B: TrustedRandomAccess
841 fn new(a: A, b: B) -> Self {
842 let len = cmp::min(a.len(), b.len());
852 fn next(&mut self) -> Option<(A::Item, B::Item)> {
853 if self.index < self.len {
857 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
859 } else if A::may_have_side_effect() && self.index < self.a.len() {
860 // match the base implementation's potential side effects
862 self.a.get_unchecked(self.index);
872 fn size_hint(&self) -> (usize, Option<usize>) {
873 let len = self.len - self.index;
878 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
879 where A: DoubleEndedIterator + ExactSizeIterator,
880 B: DoubleEndedIterator + ExactSizeIterator
882 // Adjust a, b to equal length
883 if A::may_have_side_effect() {
884 let sz = self.a.len();
886 for _ in 0..sz - cmp::max(self.len, self.index) {
891 if B::may_have_side_effect() {
892 let sz = self.b.len();
894 for _ in 0..sz - self.len {
899 if self.index < self.len {
903 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<A, B> ExactSizeIterator for Zip<A, B>
913 where A: ExactSizeIterator, B: ExactSizeIterator {}
916 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
917 where A: TrustedRandomAccess,
918 B: TrustedRandomAccess,
920 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
921 (self.a.get_unchecked(i), self.b.get_unchecked(i))
924 fn may_have_side_effect() -> bool {
925 A::may_have_side_effect() || B::may_have_side_effect()
929 #[unstable(feature = "fused", issue = "35602")]
930 impl<A, B> FusedIterator for Zip<A, B>
931 where A: FusedIterator, B: FusedIterator, {}
933 #[unstable(feature = "trusted_len", issue = "37572")]
934 unsafe impl<A, B> TrustedLen for Zip<A, B>
935 where A: TrustedLen, B: TrustedLen,
938 /// An iterator that maps the values of `iter` with `f`.
940 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
941 /// documentation for more.
943 /// [`map`]: trait.Iterator.html#method.map
944 /// [`Iterator`]: trait.Iterator.html
946 /// # Notes about side effects
948 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
949 /// you can also [`map`] backwards:
952 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
954 /// assert_eq!(v, [4, 3, 2]);
957 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
959 /// But if your closure has state, iterating backwards may act in a way you do
960 /// not expect. Let's go through an example. First, in the forward direction:
965 /// for pair in vec!['a', 'b', 'c'].into_iter()
966 /// .map(|letter| { c += 1; (letter, c) }) {
967 /// println!("{:?}", pair);
971 /// This will print "('a', 1), ('b', 2), ('c', 3)".
973 /// Now consider this twist where we add a call to `rev`. This version will
974 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
975 /// but the values of the counter still go in order. This is because `map()` is
976 /// still being called lazilly on each item, but we are popping items off the
977 /// back of the vector now, instead of shifting them from the front.
982 /// for pair in vec!['a', 'b', 'c'].into_iter()
983 /// .map(|letter| { c += 1; (letter, c) })
985 /// println!("{:?}", pair);
988 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
989 #[stable(feature = "rust1", since = "1.0.0")]
991 pub struct Map<I, F> {
996 #[stable(feature = "core_impl_debug", since = "1.9.0")]
997 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
998 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
999 f.debug_struct("Map")
1000 .field("iter", &self.iter)
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
1010 fn next(&mut self) -> Option<B> {
1011 self.iter.next().map(&mut self.f)
1015 fn size_hint(&self) -> (usize, Option<usize>) {
1016 self.iter.size_hint()
1019 fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1020 where G: FnMut(Acc, Self::Item) -> Acc,
1023 self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
1029 F: FnMut(I::Item) -> B,
1032 fn next_back(&mut self) -> Option<B> {
1033 self.iter.next_back().map(&mut self.f)
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
1039 where F: FnMut(I::Item) -> B
1041 fn len(&self) -> usize {
1045 fn is_empty(&self) -> bool {
1046 self.iter.is_empty()
1050 #[unstable(feature = "fused", issue = "35602")]
1051 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1052 where F: FnMut(I::Item) -> B {}
1054 #[unstable(feature = "trusted_len", issue = "37572")]
1055 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1056 where I: TrustedLen,
1057 F: FnMut(I::Item) -> B {}
1060 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1061 where I: TrustedRandomAccess,
1062 F: FnMut(I::Item) -> B,
1064 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1065 (self.f)(self.iter.get_unchecked(i))
1068 fn may_have_side_effect() -> bool { true }
1071 /// An iterator that filters the elements of `iter` with `predicate`.
1073 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1074 /// documentation for more.
1076 /// [`filter`]: trait.Iterator.html#method.filter
1077 /// [`Iterator`]: trait.Iterator.html
1078 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1079 #[stable(feature = "rust1", since = "1.0.0")]
1081 pub struct Filter<I, P> {
1086 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1087 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1088 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1089 f.debug_struct("Filter")
1090 .field("iter", &self.iter)
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
1097 type Item = I::Item;
1100 fn next(&mut self) -> Option<I::Item> {
1101 for x in &mut self.iter {
1102 if (self.predicate)(&x) {
1110 fn size_hint(&self) -> (usize, Option<usize>) {
1111 let (_, upper) = self.iter.size_hint();
1112 (0, upper) // can't know a lower bound, due to the predicate
1115 // this special case allows the compiler to make `.filter(_).count()`
1116 // branchless. Barring perfect branch prediction (which is unattainable in
1117 // the general case), this will be much faster in >90% of cases (containing
1118 // virtually all real workloads) and only a tiny bit slower in the rest.
1120 // Having this specialization thus allows us to write `.filter(p).count()`
1121 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1122 // less readable and also less backwards-compatible to Rust before 1.10.
1124 // Using the branchless version will also simplify the LLVM byte code, thus
1125 // leaving more budget for LLVM optimizations.
1127 fn count(mut self) -> usize {
1129 for x in &mut self.iter {
1130 count += (self.predicate)(&x) as usize;
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1138 where P: FnMut(&I::Item) -> bool,
1141 fn next_back(&mut self) -> Option<I::Item> {
1142 for x in self.iter.by_ref().rev() {
1143 if (self.predicate)(&x) {
1151 #[unstable(feature = "fused", issue = "35602")]
1152 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1153 where P: FnMut(&I::Item) -> bool {}
1155 /// An iterator that uses `f` to both filter and map elements from `iter`.
1157 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1158 /// documentation for more.
1160 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1161 /// [`Iterator`]: trait.Iterator.html
1162 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1163 #[stable(feature = "rust1", since = "1.0.0")]
1165 pub struct FilterMap<I, F> {
1170 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1171 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1173 f.debug_struct("FilterMap")
1174 .field("iter", &self.iter)
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1181 where F: FnMut(I::Item) -> Option<B>,
1186 fn next(&mut self) -> Option<B> {
1187 for x in self.iter.by_ref() {
1188 if let Some(y) = (self.f)(x) {
1196 fn size_hint(&self) -> (usize, Option<usize>) {
1197 let (_, upper) = self.iter.size_hint();
1198 (0, upper) // can't know a lower bound, due to the predicate
1202 #[stable(feature = "rust1", since = "1.0.0")]
1203 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1204 where F: FnMut(I::Item) -> Option<B>,
1207 fn next_back(&mut self) -> Option<B> {
1208 for x in self.iter.by_ref().rev() {
1209 if let Some(y) = (self.f)(x) {
1217 #[unstable(feature = "fused", issue = "35602")]
1218 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1219 where F: FnMut(I::Item) -> Option<B> {}
1221 /// An iterator that yields the current count and the element during iteration.
1223 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1224 /// documentation for more.
1226 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1227 /// [`Iterator`]: trait.Iterator.html
1228 #[derive(Clone, Debug)]
1229 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub struct Enumerate<I> {
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<I> Iterator for Enumerate<I> where I: Iterator {
1238 type Item = (usize, <I as Iterator>::Item);
1240 /// # Overflow Behavior
1242 /// The method does no guarding against overflows, so enumerating more than
1243 /// `usize::MAX` elements either produces the wrong result or panics. If
1244 /// debug assertions are enabled, a panic is guaranteed.
1248 /// Might panic if the index of the element overflows a `usize`.
1250 #[rustc_inherit_overflow_checks]
1251 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1252 self.iter.next().map(|a| {
1253 let ret = (self.count, a);
1254 // Possible undefined overflow.
1261 fn size_hint(&self) -> (usize, Option<usize>) {
1262 self.iter.size_hint()
1266 #[rustc_inherit_overflow_checks]
1267 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1268 self.iter.nth(n).map(|a| {
1269 let i = self.count + n;
1276 fn count(self) -> usize {
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<I> DoubleEndedIterator for Enumerate<I> where
1283 I: ExactSizeIterator + DoubleEndedIterator
1286 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1287 self.iter.next_back().map(|a| {
1288 let len = self.iter.len();
1289 // Can safely add, `ExactSizeIterator` promises that the number of
1290 // elements fits into a `usize`.
1291 (self.count + len, a)
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1298 fn len(&self) -> usize {
1302 fn is_empty(&self) -> bool {
1303 self.iter.is_empty()
1308 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1309 where I: TrustedRandomAccess
1311 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1312 (self.count + i, self.iter.get_unchecked(i))
1315 fn may_have_side_effect() -> bool {
1316 I::may_have_side_effect()
1320 #[unstable(feature = "fused", issue = "35602")]
1321 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1323 #[unstable(feature = "trusted_len", issue = "37572")]
1324 unsafe impl<I> TrustedLen for Enumerate<I>
1325 where I: TrustedLen,
1329 /// An iterator with a `peek()` that returns an optional reference to the next
1332 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1333 /// documentation for more.
1335 /// [`peekable`]: trait.Iterator.html#method.peekable
1336 /// [`Iterator`]: trait.Iterator.html
1337 #[derive(Clone, Debug)]
1338 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 pub struct Peekable<I: Iterator> {
1342 /// Remember a peeked value, even if it was None.
1343 peeked: Option<Option<I::Item>>,
1346 // Peekable must remember if a None has been seen in the `.peek()` method.
1347 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1348 // underlying iterator at most once. This does not by itself make the iterator
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<I: Iterator> Iterator for Peekable<I> {
1352 type Item = I::Item;
1355 fn next(&mut self) -> Option<I::Item> {
1356 match self.peeked.take() {
1358 None => self.iter.next(),
1363 #[rustc_inherit_overflow_checks]
1364 fn count(mut self) -> usize {
1365 match self.peeked.take() {
1367 Some(Some(_)) => 1 + self.iter.count(),
1368 None => self.iter.count(),
1373 fn nth(&mut self, n: usize) -> Option<I::Item> {
1374 match self.peeked.take() {
1375 // the .take() below is just to avoid "move into pattern guard"
1376 Some(ref mut v) if n == 0 => v.take(),
1378 Some(Some(_)) => self.iter.nth(n - 1),
1379 None => self.iter.nth(n),
1384 fn last(mut self) -> Option<I::Item> {
1385 let peek_opt = match self.peeked.take() {
1386 Some(None) => return None,
1390 self.iter.last().or(peek_opt)
1394 fn size_hint(&self) -> (usize, Option<usize>) {
1395 let peek_len = match self.peeked {
1396 Some(None) => return (0, Some(0)),
1400 let (lo, hi) = self.iter.size_hint();
1401 let lo = lo.saturating_add(peek_len);
1402 let hi = hi.and_then(|x| x.checked_add(peek_len));
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1410 #[unstable(feature = "fused", issue = "35602")]
1411 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1413 impl<I: Iterator> Peekable<I> {
1414 /// Returns a reference to the next() value without advancing the iterator.
1416 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1417 /// But if the iteration is over, `None` is returned.
1419 /// [`next`]: trait.Iterator.html#tymethod.next
1421 /// Because `peek()` returns a reference, and many iterators iterate over
1422 /// references, there can be a possibly confusing situation where the
1423 /// return value is a double reference. You can see this effect in the
1431 /// let xs = [1, 2, 3];
1433 /// let mut iter = xs.iter().peekable();
1435 /// // peek() lets us see into the future
1436 /// assert_eq!(iter.peek(), Some(&&1));
1437 /// assert_eq!(iter.next(), Some(&1));
1439 /// assert_eq!(iter.next(), Some(&2));
1441 /// // The iterator does not advance even if we `peek` multiple times
1442 /// assert_eq!(iter.peek(), Some(&&3));
1443 /// assert_eq!(iter.peek(), Some(&&3));
1445 /// assert_eq!(iter.next(), Some(&3));
1447 /// // After the iterator is finished, so is `peek()`
1448 /// assert_eq!(iter.peek(), None);
1449 /// assert_eq!(iter.next(), None);
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 pub fn peek(&mut self) -> Option<&I::Item> {
1454 if self.peeked.is_none() {
1455 self.peeked = Some(self.iter.next());
1458 Some(Some(ref value)) => Some(value),
1460 _ => unreachable!(),
1465 /// An iterator that rejects elements while `predicate` is true.
1467 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1468 /// documentation for more.
1470 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1471 /// [`Iterator`]: trait.Iterator.html
1472 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1473 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub struct SkipWhile<I, P> {
1481 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1482 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1484 f.debug_struct("SkipWhile")
1485 .field("iter", &self.iter)
1486 .field("flag", &self.flag)
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1493 where P: FnMut(&I::Item) -> bool
1495 type Item = I::Item;
1498 fn next(&mut self) -> Option<I::Item> {
1499 for x in self.iter.by_ref() {
1500 if self.flag || !(self.predicate)(&x) {
1509 fn size_hint(&self) -> (usize, Option<usize>) {
1510 let (_, upper) = self.iter.size_hint();
1511 (0, upper) // can't know a lower bound, due to the predicate
1515 #[unstable(feature = "fused", issue = "35602")]
1516 impl<I, P> FusedIterator for SkipWhile<I, P>
1517 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1519 /// An iterator that only accepts elements while `predicate` is true.
1521 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1522 /// documentation for more.
1524 /// [`take_while`]: trait.Iterator.html#method.take_while
1525 /// [`Iterator`]: trait.Iterator.html
1526 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1527 #[stable(feature = "rust1", since = "1.0.0")]
1529 pub struct TakeWhile<I, P> {
1535 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1536 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1538 f.debug_struct("TakeWhile")
1539 .field("iter", &self.iter)
1540 .field("flag", &self.flag)
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1547 where P: FnMut(&I::Item) -> bool
1549 type Item = I::Item;
1552 fn next(&mut self) -> Option<I::Item> {
1556 self.iter.next().and_then(|x| {
1557 if (self.predicate)(&x) {
1568 fn size_hint(&self) -> (usize, Option<usize>) {
1569 let (_, upper) = self.iter.size_hint();
1570 (0, upper) // can't know a lower bound, due to the predicate
1574 #[unstable(feature = "fused", issue = "35602")]
1575 impl<I, P> FusedIterator for TakeWhile<I, P>
1576 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1578 /// An iterator that skips over `n` elements of `iter`.
1580 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
1581 /// documentation for more.
1583 /// [`skip`]: trait.Iterator.html#method.skip
1584 /// [`Iterator`]: trait.Iterator.html
1585 #[derive(Clone, Debug)]
1586 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1587 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub struct Skip<I> {
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<I> Iterator for Skip<I> where I: Iterator {
1595 type Item = <I as Iterator>::Item;
1598 fn next(&mut self) -> Option<I::Item> {
1604 self.iter.nth(old_n)
1609 fn nth(&mut self, n: usize) -> Option<I::Item> {
1610 // Can't just add n + self.n due to overflow.
1614 let to_skip = self.n;
1617 if self.iter.nth(to_skip-1).is_none() {
1625 fn count(self) -> usize {
1626 self.iter.count().saturating_sub(self.n)
1630 fn last(mut self) -> Option<I::Item> {
1634 let next = self.next();
1636 // recurse. n should be 0.
1637 self.last().or(next)
1645 fn size_hint(&self) -> (usize, Option<usize>) {
1646 let (lower, upper) = self.iter.size_hint();
1648 let lower = lower.saturating_sub(self.n);
1649 let upper = upper.map(|x| x.saturating_sub(self.n));
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1658 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
1659 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1660 fn next_back(&mut self) -> Option<Self::Item> {
1662 self.iter.next_back()
1669 #[unstable(feature = "fused", issue = "35602")]
1670 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
1672 /// An iterator that only iterates over the first `n` iterations of `iter`.
1674 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
1675 /// documentation for more.
1677 /// [`take`]: trait.Iterator.html#method.take
1678 /// [`Iterator`]: trait.Iterator.html
1679 #[derive(Clone, Debug)]
1680 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 pub struct Take<I> {
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl<I> Iterator for Take<I> where I: Iterator{
1689 type Item = <I as Iterator>::Item;
1692 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1702 fn nth(&mut self, n: usize) -> Option<I::Item> {
1708 self.iter.nth(self.n - 1);
1716 fn size_hint(&self) -> (usize, Option<usize>) {
1717 let (lower, upper) = self.iter.size_hint();
1719 let lower = cmp::min(lower, self.n);
1721 let upper = match upper {
1722 Some(x) if x < self.n => Some(x),
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1733 #[unstable(feature = "fused", issue = "35602")]
1734 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
1736 /// An iterator to maintain state while iterating another iterator.
1738 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
1739 /// documentation for more.
1741 /// [`scan`]: trait.Iterator.html#method.scan
1742 /// [`Iterator`]: trait.Iterator.html
1743 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1744 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub struct Scan<I, St, F> {
1752 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1753 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1754 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1755 f.debug_struct("Scan")
1756 .field("iter", &self.iter)
1757 .field("state", &self.state)
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1765 F: FnMut(&mut St, I::Item) -> Option<B>,
1770 fn next(&mut self) -> Option<B> {
1771 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1775 fn size_hint(&self) -> (usize, Option<usize>) {
1776 let (_, upper) = self.iter.size_hint();
1777 (0, upper) // can't know a lower bound, due to the scan function
1781 #[unstable(feature = "fused", issue = "35602")]
1782 impl<B, I, St, F> FusedIterator for Scan<I, St, F>
1783 where I: FusedIterator, F: FnMut(&mut St, I::Item) -> Option<B> {}
1785 /// An iterator that maps each element to an iterator, and yields the elements
1786 /// of the produced iterators.
1788 /// This `struct` is created by the [`flat_map`] method on [`Iterator`]. See its
1789 /// documentation for more.
1791 /// [`flat_map`]: trait.Iterator.html#method.flat_map
1792 /// [`Iterator`]: trait.Iterator.html
1793 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1794 #[stable(feature = "rust1", since = "1.0.0")]
1796 pub struct FlatMap<I, U: IntoIterator, F> {
1799 frontiter: Option<U::IntoIter>,
1800 backiter: Option<U::IntoIter>,
1803 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1804 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1805 where U::IntoIter: fmt::Debug
1807 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1808 f.debug_struct("FlatMap")
1809 .field("iter", &self.iter)
1810 .field("frontiter", &self.frontiter)
1811 .field("backiter", &self.backiter)
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1818 where F: FnMut(I::Item) -> U,
1820 type Item = U::Item;
1823 fn next(&mut self) -> Option<U::Item> {
1825 if let Some(ref mut inner) = self.frontiter {
1826 if let Some(x) = inner.by_ref().next() {
1830 match self.iter.next().map(&mut self.f) {
1831 None => return self.backiter.as_mut().and_then(|it| it.next()),
1832 next => self.frontiter = next.map(IntoIterator::into_iter),
1838 fn size_hint(&self) -> (usize, Option<usize>) {
1839 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1840 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1841 let lo = flo.saturating_add(blo);
1842 match (self.iter.size_hint(), fhi, bhi) {
1843 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1851 F: FnMut(I::Item) -> U,
1853 U::IntoIter: DoubleEndedIterator
1856 fn next_back(&mut self) -> Option<U::Item> {
1858 if let Some(ref mut inner) = self.backiter {
1859 if let Some(y) = inner.next_back() {
1863 match self.iter.next_back().map(&mut self.f) {
1864 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1865 next => self.backiter = next.map(IntoIterator::into_iter),
1871 #[unstable(feature = "fused", issue = "35602")]
1872 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
1873 where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
1875 /// An iterator that yields `None` forever after the underlying iterator
1876 /// yields `None` once.
1878 /// This `struct` is created by the [`fuse`] method on [`Iterator`]. See its
1879 /// documentation for more.
1881 /// [`fuse`]: trait.Iterator.html#method.fuse
1882 /// [`Iterator`]: trait.Iterator.html
1883 #[derive(Clone, Debug)]
1884 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 pub struct Fuse<I> {
1891 #[unstable(feature = "fused", issue = "35602")]
1892 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 impl<I> Iterator for Fuse<I> where I: Iterator {
1896 type Item = <I as Iterator>::Item;
1899 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
1903 let next = self.iter.next();
1904 self.done = next.is_none();
1910 default fn nth(&mut self, n: usize) -> Option<I::Item> {
1914 let nth = self.iter.nth(n);
1915 self.done = nth.is_none();
1921 default fn last(self) -> Option<I::Item> {
1930 default fn count(self) -> usize {
1939 default fn size_hint(&self) -> (usize, Option<usize>) {
1943 self.iter.size_hint()
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
1951 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1955 let next = self.iter.next_back();
1956 self.done = next.is_none();
1962 unsafe impl<I> TrustedRandomAccess for Fuse<I>
1963 where I: TrustedRandomAccess,
1965 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
1966 self.iter.get_unchecked(i)
1969 fn may_have_side_effect() -> bool {
1970 I::may_have_side_effect()
1974 #[unstable(feature = "fused", issue = "35602")]
1975 impl<I> Iterator for Fuse<I> where I: FusedIterator {
1977 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1982 fn nth(&mut self, n: usize) -> Option<I::Item> {
1987 fn last(self) -> Option<I::Item> {
1992 fn count(self) -> usize {
1997 fn size_hint(&self) -> (usize, Option<usize>) {
1998 self.iter.size_hint()
2002 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
2003 impl<I> DoubleEndedIterator for Fuse<I>
2004 where I: DoubleEndedIterator + FusedIterator
2007 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2008 self.iter.next_back()
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
2015 fn len(&self) -> usize {
2019 fn is_empty(&self) -> bool {
2020 self.iter.is_empty()
2024 /// An iterator that calls a function with a reference to each element before
2027 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2028 /// documentation for more.
2030 /// [`inspect`]: trait.Iterator.html#method.inspect
2031 /// [`Iterator`]: trait.Iterator.html
2032 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2033 #[stable(feature = "rust1", since = "1.0.0")]
2035 pub struct Inspect<I, F> {
2040 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2041 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2042 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2043 f.debug_struct("Inspect")
2044 .field("iter", &self.iter)
2049 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2051 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2052 if let Some(ref a) = elt {
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2062 type Item = I::Item;
2065 fn next(&mut self) -> Option<I::Item> {
2066 let next = self.iter.next();
2067 self.do_inspect(next)
2071 fn size_hint(&self) -> (usize, Option<usize>) {
2072 self.iter.size_hint()
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2078 where F: FnMut(&I::Item),
2081 fn next_back(&mut self) -> Option<I::Item> {
2082 let next = self.iter.next_back();
2083 self.do_inspect(next)
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2089 where F: FnMut(&I::Item)
2091 fn len(&self) -> usize {
2095 fn is_empty(&self) -> bool {
2096 self.iter.is_empty()
2100 #[unstable(feature = "fused", issue = "35602")]
2101 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
2102 where F: FnMut(&I::Item) {}