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 //! let x = match iter.next() {
195 //! Some(val) => val,
198 //! let () = { println!("{}", x); };
205 //! First, we call `into_iter()` on the value. Then, we match on the iterator
206 //! that returns, calling [`next`] over and over until we see a `None`. At
207 //! that point, we `break` out of the loop, and we're done iterating.
209 //! There's one more subtle bit here: the standard library contains an
210 //! interesting implementation of [`IntoIterator`]:
213 //! impl<I: Iterator> IntoIterator for I
216 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
217 //! returning themselves. This means two things:
219 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
220 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
221 //! will allow your collection to be used with the `for` loop.
225 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
226 //! often called 'iterator adapters', as they're a form of the 'adapter
229 //! Common iterator adapters include [`map`], [`take`], and [`filter`].
230 //! For more, see their documentation.
232 //! [`map`]: trait.Iterator.html#method.map
233 //! [`take`]: trait.Iterator.html#method.take
234 //! [`filter`]: trait.Iterator.html#method.filter
238 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
239 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
240 //! until you call [`next`]. This is sometimes a source of confusion when
241 //! creating an iterator solely for its side effects. For example, the [`map`]
242 //! method calls a closure on each element it iterates over:
245 //! # #![allow(unused_must_use)]
246 //! let v = vec![1, 2, 3, 4, 5];
247 //! v.iter().map(|x| println!("{}", x));
250 //! This will not print any values, as we only created an iterator, rather than
251 //! using it. The compiler will warn us about this kind of behavior:
254 //! warning: unused result which must be used: iterator adaptors are lazy and
255 //! do nothing unless consumed
258 //! The idiomatic way to write a [`map`] for its side effects is to use a
259 //! `for` loop instead:
262 //! let v = vec![1, 2, 3, 4, 5];
265 //! println!("{}", x);
269 //! [`map`]: trait.Iterator.html#method.map
271 //! The two most common ways to evaluate an iterator are to use a `for` loop
272 //! like this, or using the [`collect`] method to produce a new collection.
274 //! [`collect`]: trait.Iterator.html#method.collect
278 //! Iterators do not have to be finite. As an example, an open-ended range is
279 //! an infinite iterator:
282 //! let numbers = 0..;
285 //! It is common to use the [`take`] iterator adapter to turn an infinite
286 //! iterator into a finite one:
289 //! let numbers = 0..;
290 //! let five_numbers = numbers.take(5);
292 //! for number in five_numbers {
293 //! println!("{}", number);
297 //! This will print the numbers `0` through `4`, each on their own line.
299 //! [`take`]: trait.Iterator.html#method.take
301 #![stable(feature = "rust1", since = "1.0.0")]
305 use iter_private::TrustedRandomAccess;
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub use self::iterator::Iterator;
311 #[unstable(feature = "step_trait",
312 reason = "likely to be replaced by finer-grained traits",
314 pub use self::range::Step;
315 #[unstable(feature = "step_by", reason = "recent addition",
317 pub use self::range::StepBy as DeprecatedStepBy;
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub use self::sources::{Repeat, repeat};
321 #[stable(feature = "iter_empty", since = "1.2.0")]
322 pub use self::sources::{Empty, empty};
323 #[stable(feature = "iter_once", since = "1.2.0")]
324 pub use self::sources::{Once, once};
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend};
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub use self::traits::{ExactSizeIterator, Sum, Product};
330 #[unstable(feature = "fused", issue = "35602")]
331 pub use self::traits::FusedIterator;
332 #[unstable(feature = "trusted_len", issue = "37572")]
333 pub use self::traits::TrustedLen;
340 /// A double-ended iterator with the direction inverted.
342 /// This `struct` is created by the [`rev`] method on [`Iterator`]. See its
343 /// documentation for more.
345 /// [`rev`]: trait.Iterator.html#method.rev
346 /// [`Iterator`]: trait.Iterator.html
347 #[derive(Clone, Debug)]
348 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
349 #[stable(feature = "rust1", since = "1.0.0")]
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
356 type Item = <I as Iterator>::Item;
359 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
361 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
363 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
364 where P: FnMut(&Self::Item) -> bool
366 self.iter.rfind(predicate)
370 #[stable(feature = "rust1", since = "1.0.0")]
371 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
373 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
375 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
376 where P: FnMut(&Self::Item) -> bool
378 self.iter.find(predicate)
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<I> ExactSizeIterator for Rev<I>
384 where I: ExactSizeIterator + DoubleEndedIterator
386 fn len(&self) -> usize {
390 fn is_empty(&self) -> bool {
395 #[unstable(feature = "fused", issue = "35602")]
396 impl<I> FusedIterator for Rev<I>
397 where I: FusedIterator + DoubleEndedIterator {}
399 #[unstable(feature = "trusted_len", issue = "37572")]
400 unsafe impl<I> TrustedLen for Rev<I>
401 where I: TrustedLen + DoubleEndedIterator {}
403 /// An iterator that clones the elements of an underlying iterator.
405 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
406 /// documentation for more.
408 /// [`cloned`]: trait.Iterator.html#method.cloned
409 /// [`Iterator`]: trait.Iterator.html
410 #[stable(feature = "iter_cloned", since = "1.1.0")]
411 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
412 #[derive(Clone, Debug)]
413 pub struct Cloned<I> {
417 #[stable(feature = "iter_cloned", since = "1.1.0")]
418 impl<'a, I, T: 'a> Iterator for Cloned<I>
419 where I: Iterator<Item=&'a T>, T: Clone
423 fn next(&mut self) -> Option<T> {
424 self.it.next().cloned()
427 fn size_hint(&self) -> (usize, Option<usize>) {
431 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
432 where F: FnMut(Acc, Self::Item) -> Acc,
434 self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
438 #[stable(feature = "iter_cloned", since = "1.1.0")]
439 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
440 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
442 fn next_back(&mut self) -> Option<T> {
443 self.it.next_back().cloned()
447 #[stable(feature = "iter_cloned", since = "1.1.0")]
448 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
449 where I: ExactSizeIterator<Item=&'a T>, T: Clone
451 fn len(&self) -> usize {
455 fn is_empty(&self) -> bool {
460 #[unstable(feature = "fused", issue = "35602")]
461 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
462 where I: FusedIterator<Item=&'a T>, T: Clone
466 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
467 where I: TrustedRandomAccess<Item=&'a T>, T: Clone
469 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
470 self.it.get_unchecked(i).clone()
474 fn may_have_side_effect() -> bool { true }
477 #[unstable(feature = "trusted_len", issue = "37572")]
478 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
479 where I: TrustedLen<Item=&'a T>,
483 /// An iterator that repeats endlessly.
485 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
486 /// documentation for more.
488 /// [`cycle`]: trait.Iterator.html#method.cycle
489 /// [`Iterator`]: trait.Iterator.html
490 #[derive(Clone, Debug)]
491 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub struct Cycle<I> {
498 #[stable(feature = "rust1", since = "1.0.0")]
499 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
500 type Item = <I as Iterator>::Item;
503 fn next(&mut self) -> Option<<I as Iterator>::Item> {
504 match self.iter.next() {
505 None => { self.iter = self.orig.clone(); self.iter.next() }
511 fn size_hint(&self) -> (usize, Option<usize>) {
512 // the cycle iterator is either empty or infinite
513 match self.orig.size_hint() {
514 sz @ (0, Some(0)) => sz,
516 _ => (usize::MAX, None)
521 #[unstable(feature = "fused", issue = "35602")]
522 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
524 /// An iterator that steps by n elements every iteration.
526 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
527 /// its documentation for more.
529 /// [`step_by`]: trait.Iterator.html#method.step_by
530 /// [`Iterator`]: trait.Iterator.html
531 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
532 #[unstable(feature = "iterator_step_by",
533 reason = "unstable replacement of Range::step_by",
535 #[derive(Clone, Debug)]
536 pub struct StepBy<I> {
542 #[unstable(feature = "iterator_step_by",
543 reason = "unstable replacement of Range::step_by",
545 impl<I> Iterator for StepBy<I> where I: Iterator {
549 fn next(&mut self) -> Option<Self::Item> {
551 self.first_take = false;
554 self.iter.nth(self.step)
559 /// An iterator that strings two iterators together.
561 /// This `struct` is created by the [`chain`] method on [`Iterator`]. See its
562 /// documentation for more.
564 /// [`chain`]: trait.Iterator.html#method.chain
565 /// [`Iterator`]: trait.Iterator.html
566 #[derive(Clone, Debug)]
567 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
568 #[stable(feature = "rust1", since = "1.0.0")]
569 pub struct Chain<A, B> {
575 // The iterator protocol specifies that iteration ends with the return value
576 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
577 // further calls return. The chain adaptor must account for this since it uses
580 // It uses three states:
582 // - Both: `a` and `b` are remaining
583 // - Front: `a` remaining
584 // - Back: `b` remaining
586 // The fourth state (neither iterator is remaining) only occurs after Chain has
587 // returned None once, so we don't need to store this state.
588 #[derive(Clone, Debug)]
590 // both front and back iterator are remaining
592 // only front is remaining
594 // only back is remaining
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl<A, B> Iterator for Chain<A, B> where
601 B: Iterator<Item = A::Item>
606 fn next(&mut self) -> Option<A::Item> {
608 ChainState::Both => match self.a.next() {
609 elt @ Some(..) => elt,
611 self.state = ChainState::Back;
615 ChainState::Front => self.a.next(),
616 ChainState::Back => self.b.next(),
621 #[rustc_inherit_overflow_checks]
622 fn count(self) -> usize {
624 ChainState::Both => self.a.count() + self.b.count(),
625 ChainState::Front => self.a.count(),
626 ChainState::Back => self.b.count(),
630 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
631 where F: FnMut(Acc, Self::Item) -> Acc,
633 let mut accum = init;
635 ChainState::Both | ChainState::Front => {
636 accum = self.a.fold(accum, &mut f);
641 ChainState::Both | ChainState::Back => {
642 accum = self.b.fold(accum, &mut f);
650 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
652 ChainState::Both | ChainState::Front => {
653 for x in self.a.by_ref() {
659 if let ChainState::Both = self.state {
660 self.state = ChainState::Back;
663 ChainState::Back => {}
665 if let ChainState::Back = self.state {
673 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
674 P: FnMut(&Self::Item) -> bool,
677 ChainState::Both => match self.a.find(&mut predicate) {
679 self.state = ChainState::Back;
680 self.b.find(predicate)
684 ChainState::Front => self.a.find(predicate),
685 ChainState::Back => self.b.find(predicate),
690 fn last(self) -> Option<A::Item> {
692 ChainState::Both => {
693 // Must exhaust a before b.
694 let a_last = self.a.last();
695 let b_last = self.b.last();
698 ChainState::Front => self.a.last(),
699 ChainState::Back => self.b.last()
704 fn size_hint(&self) -> (usize, Option<usize>) {
705 let (a_lower, a_upper) = self.a.size_hint();
706 let (b_lower, b_upper) = self.b.size_hint();
708 let lower = a_lower.saturating_add(b_lower);
710 let upper = match (a_upper, b_upper) {
711 (Some(x), Some(y)) => x.checked_add(y),
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<A, B> DoubleEndedIterator for Chain<A, B> where
721 A: DoubleEndedIterator,
722 B: DoubleEndedIterator<Item=A::Item>,
725 fn next_back(&mut self) -> Option<A::Item> {
727 ChainState::Both => match self.b.next_back() {
728 elt @ Some(..) => elt,
730 self.state = ChainState::Front;
734 ChainState::Front => self.a.next_back(),
735 ChainState::Back => self.b.next_back(),
740 // Note: *both* must be fused to handle double-ended iterators.
741 #[unstable(feature = "fused", issue = "35602")]
742 impl<A, B> FusedIterator for Chain<A, B>
743 where A: FusedIterator,
744 B: FusedIterator<Item=A::Item>,
747 #[unstable(feature = "trusted_len", issue = "37572")]
748 unsafe impl<A, B> TrustedLen for Chain<A, B>
749 where A: TrustedLen, B: TrustedLen<Item=A::Item>,
752 /// An iterator that iterates two other iterators simultaneously.
754 /// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
755 /// documentation for more.
757 /// [`zip`]: trait.Iterator.html#method.zip
758 /// [`Iterator`]: trait.Iterator.html
759 #[derive(Clone, Debug)]
760 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
761 #[stable(feature = "rust1", since = "1.0.0")]
762 pub struct Zip<A, B> {
765 // index and len are only used by the specialized version of zip
770 #[stable(feature = "rust1", since = "1.0.0")]
771 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
773 type Item = (A::Item, B::Item);
776 fn next(&mut self) -> Option<Self::Item> {
781 fn size_hint(&self) -> (usize, Option<usize>) {
782 ZipImpl::size_hint(self)
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl<A, B> DoubleEndedIterator for Zip<A, B> where
788 A: DoubleEndedIterator + ExactSizeIterator,
789 B: DoubleEndedIterator + ExactSizeIterator,
792 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
793 ZipImpl::next_back(self)
797 // Zip specialization trait
799 trait ZipImpl<A, B> {
801 fn new(a: A, b: B) -> Self;
802 fn next(&mut self) -> Option<Self::Item>;
803 fn size_hint(&self) -> (usize, Option<usize>);
804 fn next_back(&mut self) -> Option<Self::Item>
805 where A: DoubleEndedIterator + ExactSizeIterator,
806 B: DoubleEndedIterator + ExactSizeIterator;
811 impl<A, B> ZipImpl<A, B> for Zip<A, B>
812 where A: Iterator, B: Iterator
814 type Item = (A::Item, B::Item);
815 default fn new(a: A, b: B) -> Self {
825 default fn next(&mut self) -> Option<(A::Item, B::Item)> {
826 self.a.next().and_then(|x| {
827 self.b.next().and_then(|y| {
834 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
835 where A: DoubleEndedIterator + ExactSizeIterator,
836 B: DoubleEndedIterator + ExactSizeIterator
838 let a_sz = self.a.len();
839 let b_sz = self.b.len();
841 // Adjust a, b to equal length
843 for _ in 0..a_sz - b_sz { self.a.next_back(); }
845 for _ in 0..b_sz - a_sz { self.b.next_back(); }
848 match (self.a.next_back(), self.b.next_back()) {
849 (Some(x), Some(y)) => Some((x, y)),
850 (None, None) => None,
856 default fn size_hint(&self) -> (usize, Option<usize>) {
857 let (a_lower, a_upper) = self.a.size_hint();
858 let (b_lower, b_upper) = self.b.size_hint();
860 let lower = cmp::min(a_lower, b_lower);
862 let upper = match (a_upper, b_upper) {
863 (Some(x), Some(y)) => Some(cmp::min(x,y)),
864 (Some(x), None) => Some(x),
865 (None, Some(y)) => Some(y),
874 impl<A, B> ZipImpl<A, B> for Zip<A, B>
875 where A: TrustedRandomAccess, B: TrustedRandomAccess
877 fn new(a: A, b: B) -> Self {
878 let len = cmp::min(a.len(), b.len());
888 fn next(&mut self) -> Option<(A::Item, B::Item)> {
889 if self.index < self.len {
893 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
895 } else if A::may_have_side_effect() && self.index < self.a.len() {
896 // match the base implementation's potential side effects
898 self.a.get_unchecked(self.index);
908 fn size_hint(&self) -> (usize, Option<usize>) {
909 let len = self.len - self.index;
914 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
915 where A: DoubleEndedIterator + ExactSizeIterator,
916 B: DoubleEndedIterator + ExactSizeIterator
918 // Adjust a, b to equal length
919 if A::may_have_side_effect() {
920 let sz = self.a.len();
922 for _ in 0..sz - cmp::max(self.len, self.index) {
927 if B::may_have_side_effect() {
928 let sz = self.b.len();
930 for _ in 0..sz - self.len {
935 if self.index < self.len {
939 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<A, B> ExactSizeIterator for Zip<A, B>
949 where A: ExactSizeIterator, B: ExactSizeIterator {}
952 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
953 where A: TrustedRandomAccess,
954 B: TrustedRandomAccess,
956 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
957 (self.a.get_unchecked(i), self.b.get_unchecked(i))
960 fn may_have_side_effect() -> bool {
961 A::may_have_side_effect() || B::may_have_side_effect()
965 #[unstable(feature = "fused", issue = "35602")]
966 impl<A, B> FusedIterator for Zip<A, B>
967 where A: FusedIterator, B: FusedIterator, {}
969 #[unstable(feature = "trusted_len", issue = "37572")]
970 unsafe impl<A, B> TrustedLen for Zip<A, B>
971 where A: TrustedLen, B: TrustedLen,
974 /// An iterator that maps the values of `iter` with `f`.
976 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
977 /// documentation for more.
979 /// [`map`]: trait.Iterator.html#method.map
980 /// [`Iterator`]: trait.Iterator.html
982 /// # Notes about side effects
984 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
985 /// you can also [`map`] backwards:
988 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
990 /// assert_eq!(v, [4, 3, 2]);
993 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
995 /// But if your closure has state, iterating backwards may act in a way you do
996 /// not expect. Let's go through an example. First, in the forward direction:
1001 /// for pair in vec!['a', 'b', 'c'].into_iter()
1002 /// .map(|letter| { c += 1; (letter, c) }) {
1003 /// println!("{:?}", pair);
1007 /// This will print "('a', 1), ('b', 2), ('c', 3)".
1009 /// Now consider this twist where we add a call to `rev`. This version will
1010 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
1011 /// but the values of the counter still go in order. This is because `map()` is
1012 /// still being called lazilly on each item, but we are popping items off the
1013 /// back of the vector now, instead of shifting them from the front.
1018 /// for pair in vec!['a', 'b', 'c'].into_iter()
1019 /// .map(|letter| { c += 1; (letter, c) })
1021 /// println!("{:?}", pair);
1024 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1025 #[stable(feature = "rust1", since = "1.0.0")]
1027 pub struct Map<I, F> {
1032 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1033 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
1034 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1035 f.debug_struct("Map")
1036 .field("iter", &self.iter)
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
1046 fn next(&mut self) -> Option<B> {
1047 self.iter.next().map(&mut self.f)
1051 fn size_hint(&self) -> (usize, Option<usize>) {
1052 self.iter.size_hint()
1055 fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1056 where G: FnMut(Acc, Self::Item) -> Acc,
1059 self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
1065 F: FnMut(I::Item) -> B,
1068 fn next_back(&mut self) -> Option<B> {
1069 self.iter.next_back().map(&mut self.f)
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
1075 where F: FnMut(I::Item) -> B
1077 fn len(&self) -> usize {
1081 fn is_empty(&self) -> bool {
1082 self.iter.is_empty()
1086 #[unstable(feature = "fused", issue = "35602")]
1087 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1088 where F: FnMut(I::Item) -> B {}
1090 #[unstable(feature = "trusted_len", issue = "37572")]
1091 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1092 where I: TrustedLen,
1093 F: FnMut(I::Item) -> B {}
1096 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1097 where I: TrustedRandomAccess,
1098 F: FnMut(I::Item) -> B,
1100 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1101 (self.f)(self.iter.get_unchecked(i))
1104 fn may_have_side_effect() -> bool { true }
1107 /// An iterator that filters the elements of `iter` with `predicate`.
1109 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1110 /// documentation for more.
1112 /// [`filter`]: trait.Iterator.html#method.filter
1113 /// [`Iterator`]: trait.Iterator.html
1114 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1115 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub struct Filter<I, P> {
1122 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1123 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1125 f.debug_struct("Filter")
1126 .field("iter", &self.iter)
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
1133 type Item = I::Item;
1136 fn next(&mut self) -> Option<I::Item> {
1137 for x in &mut self.iter {
1138 if (self.predicate)(&x) {
1146 fn size_hint(&self) -> (usize, Option<usize>) {
1147 let (_, upper) = self.iter.size_hint();
1148 (0, upper) // can't know a lower bound, due to the predicate
1151 // this special case allows the compiler to make `.filter(_).count()`
1152 // branchless. Barring perfect branch prediction (which is unattainable in
1153 // the general case), this will be much faster in >90% of cases (containing
1154 // virtually all real workloads) and only a tiny bit slower in the rest.
1156 // Having this specialization thus allows us to write `.filter(p).count()`
1157 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1158 // less readable and also less backwards-compatible to Rust before 1.10.
1160 // Using the branchless version will also simplify the LLVM byte code, thus
1161 // leaving more budget for LLVM optimizations.
1163 fn count(mut self) -> usize {
1165 for x in &mut self.iter {
1166 count += (self.predicate)(&x) as usize;
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1174 where P: FnMut(&I::Item) -> bool,
1177 fn next_back(&mut self) -> Option<I::Item> {
1178 for x in self.iter.by_ref().rev() {
1179 if (self.predicate)(&x) {
1187 #[unstable(feature = "fused", issue = "35602")]
1188 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1189 where P: FnMut(&I::Item) -> bool {}
1191 /// An iterator that uses `f` to both filter and map elements from `iter`.
1193 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1194 /// documentation for more.
1196 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1197 /// [`Iterator`]: trait.Iterator.html
1198 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1199 #[stable(feature = "rust1", since = "1.0.0")]
1201 pub struct FilterMap<I, F> {
1206 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1207 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1209 f.debug_struct("FilterMap")
1210 .field("iter", &self.iter)
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1217 where F: FnMut(I::Item) -> Option<B>,
1222 fn next(&mut self) -> Option<B> {
1223 for x in self.iter.by_ref() {
1224 if let Some(y) = (self.f)(x) {
1232 fn size_hint(&self) -> (usize, Option<usize>) {
1233 let (_, upper) = self.iter.size_hint();
1234 (0, upper) // can't know a lower bound, due to the predicate
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1240 where F: FnMut(I::Item) -> Option<B>,
1243 fn next_back(&mut self) -> Option<B> {
1244 for x in self.iter.by_ref().rev() {
1245 if let Some(y) = (self.f)(x) {
1253 #[unstable(feature = "fused", issue = "35602")]
1254 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1255 where F: FnMut(I::Item) -> Option<B> {}
1257 /// An iterator that yields the current count and the element during iteration.
1259 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1260 /// documentation for more.
1262 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1263 /// [`Iterator`]: trait.Iterator.html
1264 #[derive(Clone, Debug)]
1265 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 pub struct Enumerate<I> {
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl<I> Iterator for Enumerate<I> where I: Iterator {
1274 type Item = (usize, <I as Iterator>::Item);
1276 /// # Overflow Behavior
1278 /// The method does no guarding against overflows, so enumerating more than
1279 /// `usize::MAX` elements either produces the wrong result or panics. If
1280 /// debug assertions are enabled, a panic is guaranteed.
1284 /// Might panic if the index of the element overflows a `usize`.
1286 #[rustc_inherit_overflow_checks]
1287 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1288 self.iter.next().map(|a| {
1289 let ret = (self.count, a);
1290 // Possible undefined overflow.
1297 fn size_hint(&self) -> (usize, Option<usize>) {
1298 self.iter.size_hint()
1302 #[rustc_inherit_overflow_checks]
1303 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1304 self.iter.nth(n).map(|a| {
1305 let i = self.count + n;
1312 fn count(self) -> usize {
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl<I> DoubleEndedIterator for Enumerate<I> where
1319 I: ExactSizeIterator + DoubleEndedIterator
1322 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1323 self.iter.next_back().map(|a| {
1324 let len = self.iter.len();
1325 // Can safely add, `ExactSizeIterator` promises that the number of
1326 // elements fits into a `usize`.
1327 (self.count + len, a)
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1334 fn len(&self) -> usize {
1338 fn is_empty(&self) -> bool {
1339 self.iter.is_empty()
1344 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1345 where I: TrustedRandomAccess
1347 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1348 (self.count + i, self.iter.get_unchecked(i))
1351 fn may_have_side_effect() -> bool {
1352 I::may_have_side_effect()
1356 #[unstable(feature = "fused", issue = "35602")]
1357 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1359 #[unstable(feature = "trusted_len", issue = "37572")]
1360 unsafe impl<I> TrustedLen for Enumerate<I>
1361 where I: TrustedLen,
1365 /// An iterator with a `peek()` that returns an optional reference to the next
1368 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1369 /// documentation for more.
1371 /// [`peekable`]: trait.Iterator.html#method.peekable
1372 /// [`Iterator`]: trait.Iterator.html
1373 #[derive(Clone, Debug)]
1374 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 pub struct Peekable<I: Iterator> {
1378 /// Remember a peeked value, even if it was None.
1379 peeked: Option<Option<I::Item>>,
1382 // Peekable must remember if a None has been seen in the `.peek()` method.
1383 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1384 // underlying iterator at most once. This does not by itself make the iterator
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl<I: Iterator> Iterator for Peekable<I> {
1388 type Item = I::Item;
1391 fn next(&mut self) -> Option<I::Item> {
1392 match self.peeked.take() {
1394 None => self.iter.next(),
1399 #[rustc_inherit_overflow_checks]
1400 fn count(mut self) -> usize {
1401 match self.peeked.take() {
1403 Some(Some(_)) => 1 + self.iter.count(),
1404 None => self.iter.count(),
1409 fn nth(&mut self, n: usize) -> Option<I::Item> {
1410 match self.peeked.take() {
1411 // the .take() below is just to avoid "move into pattern guard"
1412 Some(ref mut v) if n == 0 => v.take(),
1414 Some(Some(_)) => self.iter.nth(n - 1),
1415 None => self.iter.nth(n),
1420 fn last(mut self) -> Option<I::Item> {
1421 let peek_opt = match self.peeked.take() {
1422 Some(None) => return None,
1426 self.iter.last().or(peek_opt)
1430 fn size_hint(&self) -> (usize, Option<usize>) {
1431 let peek_len = match self.peeked {
1432 Some(None) => return (0, Some(0)),
1436 let (lo, hi) = self.iter.size_hint();
1437 let lo = lo.saturating_add(peek_len);
1438 let hi = hi.and_then(|x| x.checked_add(peek_len));
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1446 #[unstable(feature = "fused", issue = "35602")]
1447 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1449 impl<I: Iterator> Peekable<I> {
1450 /// Returns a reference to the next() value without advancing the iterator.
1452 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1453 /// But if the iteration is over, `None` is returned.
1455 /// [`next`]: trait.Iterator.html#tymethod.next
1457 /// Because `peek()` returns a reference, and many iterators iterate over
1458 /// references, there can be a possibly confusing situation where the
1459 /// return value is a double reference. You can see this effect in the
1467 /// let xs = [1, 2, 3];
1469 /// let mut iter = xs.iter().peekable();
1471 /// // peek() lets us see into the future
1472 /// assert_eq!(iter.peek(), Some(&&1));
1473 /// assert_eq!(iter.next(), Some(&1));
1475 /// assert_eq!(iter.next(), Some(&2));
1477 /// // The iterator does not advance even if we `peek` multiple times
1478 /// assert_eq!(iter.peek(), Some(&&3));
1479 /// assert_eq!(iter.peek(), Some(&&3));
1481 /// assert_eq!(iter.next(), Some(&3));
1483 /// // After the iterator is finished, so is `peek()`
1484 /// assert_eq!(iter.peek(), None);
1485 /// assert_eq!(iter.next(), None);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 pub fn peek(&mut self) -> Option<&I::Item> {
1490 if self.peeked.is_none() {
1491 self.peeked = Some(self.iter.next());
1494 Some(Some(ref value)) => Some(value),
1496 _ => unreachable!(),
1501 /// An iterator that rejects elements while `predicate` is true.
1503 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1504 /// documentation for more.
1506 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1507 /// [`Iterator`]: trait.Iterator.html
1508 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1509 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub struct SkipWhile<I, P> {
1517 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1518 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1519 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1520 f.debug_struct("SkipWhile")
1521 .field("iter", &self.iter)
1522 .field("flag", &self.flag)
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1529 where P: FnMut(&I::Item) -> bool
1531 type Item = I::Item;
1534 fn next(&mut self) -> Option<I::Item> {
1535 for x in self.iter.by_ref() {
1536 if self.flag || !(self.predicate)(&x) {
1545 fn size_hint(&self) -> (usize, Option<usize>) {
1546 let (_, upper) = self.iter.size_hint();
1547 (0, upper) // can't know a lower bound, due to the predicate
1551 #[unstable(feature = "fused", issue = "35602")]
1552 impl<I, P> FusedIterator for SkipWhile<I, P>
1553 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1555 /// An iterator that only accepts elements while `predicate` is true.
1557 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1558 /// documentation for more.
1560 /// [`take_while`]: trait.Iterator.html#method.take_while
1561 /// [`Iterator`]: trait.Iterator.html
1562 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1563 #[stable(feature = "rust1", since = "1.0.0")]
1565 pub struct TakeWhile<I, P> {
1571 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1572 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1573 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1574 f.debug_struct("TakeWhile")
1575 .field("iter", &self.iter)
1576 .field("flag", &self.flag)
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1583 where P: FnMut(&I::Item) -> bool
1585 type Item = I::Item;
1588 fn next(&mut self) -> Option<I::Item> {
1592 self.iter.next().and_then(|x| {
1593 if (self.predicate)(&x) {
1604 fn size_hint(&self) -> (usize, Option<usize>) {
1605 let (_, upper) = self.iter.size_hint();
1606 (0, upper) // can't know a lower bound, due to the predicate
1610 #[unstable(feature = "fused", issue = "35602")]
1611 impl<I, P> FusedIterator for TakeWhile<I, P>
1612 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1614 /// An iterator that skips over `n` elements of `iter`.
1616 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
1617 /// documentation for more.
1619 /// [`skip`]: trait.Iterator.html#method.skip
1620 /// [`Iterator`]: trait.Iterator.html
1621 #[derive(Clone, Debug)]
1622 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 pub struct Skip<I> {
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl<I> Iterator for Skip<I> where I: Iterator {
1631 type Item = <I as Iterator>::Item;
1634 fn next(&mut self) -> Option<I::Item> {
1640 self.iter.nth(old_n)
1645 fn nth(&mut self, n: usize) -> Option<I::Item> {
1646 // Can't just add n + self.n due to overflow.
1650 let to_skip = self.n;
1653 if self.iter.nth(to_skip-1).is_none() {
1661 fn count(self) -> usize {
1662 self.iter.count().saturating_sub(self.n)
1666 fn last(mut self) -> Option<I::Item> {
1670 let next = self.next();
1672 // recurse. n should be 0.
1673 self.last().or(next)
1681 fn size_hint(&self) -> (usize, Option<usize>) {
1682 let (lower, upper) = self.iter.size_hint();
1684 let lower = lower.saturating_sub(self.n);
1685 let upper = upper.map(|x| x.saturating_sub(self.n));
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1694 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
1695 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1696 fn next_back(&mut self) -> Option<Self::Item> {
1698 self.iter.next_back()
1705 #[unstable(feature = "fused", issue = "35602")]
1706 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
1708 /// An iterator that only iterates over the first `n` iterations of `iter`.
1710 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
1711 /// documentation for more.
1713 /// [`take`]: trait.Iterator.html#method.take
1714 /// [`Iterator`]: trait.Iterator.html
1715 #[derive(Clone, Debug)]
1716 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 pub struct Take<I> {
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl<I> Iterator for Take<I> where I: Iterator{
1725 type Item = <I as Iterator>::Item;
1728 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1738 fn nth(&mut self, n: usize) -> Option<I::Item> {
1744 self.iter.nth(self.n - 1);
1752 fn size_hint(&self) -> (usize, Option<usize>) {
1753 let (lower, upper) = self.iter.size_hint();
1755 let lower = cmp::min(lower, self.n);
1757 let upper = match upper {
1758 Some(x) if x < self.n => Some(x),
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1769 #[unstable(feature = "fused", issue = "35602")]
1770 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
1772 /// An iterator to maintain state while iterating another iterator.
1774 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
1775 /// documentation for more.
1777 /// [`scan`]: trait.Iterator.html#method.scan
1778 /// [`Iterator`]: trait.Iterator.html
1779 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1780 #[stable(feature = "rust1", since = "1.0.0")]
1782 pub struct Scan<I, St, F> {
1788 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1789 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1790 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1791 f.debug_struct("Scan")
1792 .field("iter", &self.iter)
1793 .field("state", &self.state)
1798 #[stable(feature = "rust1", since = "1.0.0")]
1799 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1801 F: FnMut(&mut St, I::Item) -> Option<B>,
1806 fn next(&mut self) -> Option<B> {
1807 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1811 fn size_hint(&self) -> (usize, Option<usize>) {
1812 let (_, upper) = self.iter.size_hint();
1813 (0, upper) // can't know a lower bound, due to the scan function
1817 /// An iterator that maps each element to an iterator, and yields the elements
1818 /// of the produced iterators.
1820 /// This `struct` is created by the [`flat_map`] method on [`Iterator`]. See its
1821 /// documentation for more.
1823 /// [`flat_map`]: trait.Iterator.html#method.flat_map
1824 /// [`Iterator`]: trait.Iterator.html
1825 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1826 #[stable(feature = "rust1", since = "1.0.0")]
1828 pub struct FlatMap<I, U: IntoIterator, F> {
1831 frontiter: Option<U::IntoIter>,
1832 backiter: Option<U::IntoIter>,
1835 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1836 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1837 where U::IntoIter: fmt::Debug
1839 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1840 f.debug_struct("FlatMap")
1841 .field("iter", &self.iter)
1842 .field("frontiter", &self.frontiter)
1843 .field("backiter", &self.backiter)
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1850 where F: FnMut(I::Item) -> U,
1852 type Item = U::Item;
1855 fn next(&mut self) -> Option<U::Item> {
1857 if let Some(ref mut inner) = self.frontiter {
1858 if let Some(x) = inner.by_ref().next() {
1862 match self.iter.next().map(&mut self.f) {
1863 None => return self.backiter.as_mut().and_then(|it| it.next()),
1864 next => self.frontiter = next.map(IntoIterator::into_iter),
1870 fn size_hint(&self) -> (usize, Option<usize>) {
1871 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1872 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1873 let lo = flo.saturating_add(blo);
1874 match (self.iter.size_hint(), fhi, bhi) {
1875 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1883 F: FnMut(I::Item) -> U,
1885 U::IntoIter: DoubleEndedIterator
1888 fn next_back(&mut self) -> Option<U::Item> {
1890 if let Some(ref mut inner) = self.backiter {
1891 if let Some(y) = inner.next_back() {
1895 match self.iter.next_back().map(&mut self.f) {
1896 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1897 next => self.backiter = next.map(IntoIterator::into_iter),
1903 #[unstable(feature = "fused", issue = "35602")]
1904 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
1905 where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
1907 /// An iterator that yields `None` forever after the underlying iterator
1908 /// yields `None` once.
1910 /// This `struct` is created by the [`fuse`] method on [`Iterator`]. See its
1911 /// documentation for more.
1913 /// [`fuse`]: trait.Iterator.html#method.fuse
1914 /// [`Iterator`]: trait.Iterator.html
1915 #[derive(Clone, Debug)]
1916 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 pub struct Fuse<I> {
1923 #[unstable(feature = "fused", issue = "35602")]
1924 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl<I> Iterator for Fuse<I> where I: Iterator {
1928 type Item = <I as Iterator>::Item;
1931 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
1935 let next = self.iter.next();
1936 self.done = next.is_none();
1942 default fn nth(&mut self, n: usize) -> Option<I::Item> {
1946 let nth = self.iter.nth(n);
1947 self.done = nth.is_none();
1953 default fn last(self) -> Option<I::Item> {
1962 default fn count(self) -> usize {
1971 default fn size_hint(&self) -> (usize, Option<usize>) {
1975 self.iter.size_hint()
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
1983 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1987 let next = self.iter.next_back();
1988 self.done = next.is_none();
1994 unsafe impl<I> TrustedRandomAccess for Fuse<I>
1995 where I: TrustedRandomAccess,
1997 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
1998 self.iter.get_unchecked(i)
2001 fn may_have_side_effect() -> bool {
2002 I::may_have_side_effect()
2006 #[unstable(feature = "fused", issue = "35602")]
2007 impl<I> Iterator for Fuse<I> where I: FusedIterator {
2009 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2014 fn nth(&mut self, n: usize) -> Option<I::Item> {
2019 fn last(self) -> Option<I::Item> {
2024 fn count(self) -> usize {
2029 fn size_hint(&self) -> (usize, Option<usize>) {
2030 self.iter.size_hint()
2034 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
2035 impl<I> DoubleEndedIterator for Fuse<I>
2036 where I: DoubleEndedIterator + FusedIterator
2039 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2040 self.iter.next_back()
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
2047 fn len(&self) -> usize {
2051 fn is_empty(&self) -> bool {
2052 self.iter.is_empty()
2056 /// An iterator that calls a function with a reference to each element before
2059 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2060 /// documentation for more.
2062 /// [`inspect`]: trait.Iterator.html#method.inspect
2063 /// [`Iterator`]: trait.Iterator.html
2064 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2065 #[stable(feature = "rust1", since = "1.0.0")]
2067 pub struct Inspect<I, F> {
2072 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2073 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2074 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2075 f.debug_struct("Inspect")
2076 .field("iter", &self.iter)
2081 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2083 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2084 if let Some(ref a) = elt {
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2094 type Item = I::Item;
2097 fn next(&mut self) -> Option<I::Item> {
2098 let next = self.iter.next();
2099 self.do_inspect(next)
2103 fn size_hint(&self) -> (usize, Option<usize>) {
2104 self.iter.size_hint()
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2110 where F: FnMut(&I::Item),
2113 fn next_back(&mut self) -> Option<I::Item> {
2114 let next = self.iter.next_back();
2115 self.do_inspect(next)
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2121 where F: FnMut(&I::Item)
2123 fn len(&self) -> usize {
2127 fn is_empty(&self) -> bool {
2128 self.iter.is_empty()
2132 #[unstable(feature = "fused", issue = "35602")]
2133 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
2134 where F: FnMut(&I::Item) {}