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 as DeprecatedStepBy;
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 adapter for stepping iterators by a custom amount.
525 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
526 /// its documentation for more.
528 /// [`step_by`]: trait.Iterator.html#method.step_by
529 /// [`Iterator`]: trait.Iterator.html
530 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
531 #[unstable(feature = "iterator_step_by",
532 reason = "unstable replacement of Range::step_by",
534 #[derive(Clone, Debug)]
535 pub struct StepBy<I> {
541 #[unstable(feature = "iterator_step_by",
542 reason = "unstable replacement of Range::step_by",
544 impl<I> Iterator for StepBy<I> where I: Iterator {
548 fn next(&mut self) -> Option<Self::Item> {
550 self.first_take = false;
553 self.iter.nth(self.step)
558 fn size_hint(&self) -> (usize, Option<usize>) {
559 let inner_hint = self.iter.size_hint();
562 let f = |n| if n == 0 { 0 } else { 1 + (n-1)/(self.step+1) };
563 (f(inner_hint.0), inner_hint.1.map(f))
565 let f = |n| n / (self.step+1);
566 (f(inner_hint.0), inner_hint.1.map(f))
571 // StepBy can only make the iterator shorter, so the len will still fit.
572 #[unstable(feature = "iterator_step_by",
573 reason = "unstable replacement of Range::step_by",
575 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
577 /// An iterator that strings two iterators together.
579 /// This `struct` is created by the [`chain`] method on [`Iterator`]. See its
580 /// documentation for more.
582 /// [`chain`]: trait.Iterator.html#method.chain
583 /// [`Iterator`]: trait.Iterator.html
584 #[derive(Clone, Debug)]
585 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub struct Chain<A, B> {
593 // The iterator protocol specifies that iteration ends with the return value
594 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
595 // further calls return. The chain adaptor must account for this since it uses
598 // It uses three states:
600 // - Both: `a` and `b` are remaining
601 // - Front: `a` remaining
602 // - Back: `b` remaining
604 // The fourth state (neither iterator is remaining) only occurs after Chain has
605 // returned None once, so we don't need to store this state.
606 #[derive(Clone, Debug)]
608 // both front and back iterator are remaining
610 // only front is remaining
612 // only back is remaining
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl<A, B> Iterator for Chain<A, B> where
619 B: Iterator<Item = A::Item>
624 fn next(&mut self) -> Option<A::Item> {
626 ChainState::Both => match self.a.next() {
627 elt @ Some(..) => elt,
629 self.state = ChainState::Back;
633 ChainState::Front => self.a.next(),
634 ChainState::Back => self.b.next(),
639 #[rustc_inherit_overflow_checks]
640 fn count(self) -> usize {
642 ChainState::Both => self.a.count() + self.b.count(),
643 ChainState::Front => self.a.count(),
644 ChainState::Back => self.b.count(),
648 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
649 where F: FnMut(Acc, Self::Item) -> Acc,
651 let mut accum = init;
653 ChainState::Both | ChainState::Front => {
654 accum = self.a.fold(accum, &mut f);
659 ChainState::Both | ChainState::Back => {
660 accum = self.b.fold(accum, &mut f);
668 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
670 ChainState::Both | ChainState::Front => {
671 for x in self.a.by_ref() {
677 if let ChainState::Both = self.state {
678 self.state = ChainState::Back;
681 ChainState::Back => {}
683 if let ChainState::Back = self.state {
691 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
692 P: FnMut(&Self::Item) -> bool,
695 ChainState::Both => match self.a.find(&mut predicate) {
697 self.state = ChainState::Back;
698 self.b.find(predicate)
702 ChainState::Front => self.a.find(predicate),
703 ChainState::Back => self.b.find(predicate),
708 fn last(self) -> Option<A::Item> {
710 ChainState::Both => {
711 // Must exhaust a before b.
712 let a_last = self.a.last();
713 let b_last = self.b.last();
716 ChainState::Front => self.a.last(),
717 ChainState::Back => self.b.last()
722 fn size_hint(&self) -> (usize, Option<usize>) {
723 let (a_lower, a_upper) = self.a.size_hint();
724 let (b_lower, b_upper) = self.b.size_hint();
726 let lower = a_lower.saturating_add(b_lower);
728 let upper = match (a_upper, b_upper) {
729 (Some(x), Some(y)) => x.checked_add(y),
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<A, B> DoubleEndedIterator for Chain<A, B> where
739 A: DoubleEndedIterator,
740 B: DoubleEndedIterator<Item=A::Item>,
743 fn next_back(&mut self) -> Option<A::Item> {
745 ChainState::Both => match self.b.next_back() {
746 elt @ Some(..) => elt,
748 self.state = ChainState::Front;
752 ChainState::Front => self.a.next_back(),
753 ChainState::Back => self.b.next_back(),
758 // Note: *both* must be fused to handle double-ended iterators.
759 #[unstable(feature = "fused", issue = "35602")]
760 impl<A, B> FusedIterator for Chain<A, B>
761 where A: FusedIterator,
762 B: FusedIterator<Item=A::Item>,
765 #[unstable(feature = "trusted_len", issue = "37572")]
766 unsafe impl<A, B> TrustedLen for Chain<A, B>
767 where A: TrustedLen, B: TrustedLen<Item=A::Item>,
770 /// An iterator that iterates two other iterators simultaneously.
772 /// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
773 /// documentation for more.
775 /// [`zip`]: trait.Iterator.html#method.zip
776 /// [`Iterator`]: trait.Iterator.html
777 #[derive(Clone, Debug)]
778 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
779 #[stable(feature = "rust1", since = "1.0.0")]
780 pub struct Zip<A, B> {
783 // index and len are only used by the specialized version of zip
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
791 type Item = (A::Item, B::Item);
794 fn next(&mut self) -> Option<Self::Item> {
799 fn size_hint(&self) -> (usize, Option<usize>) {
800 ZipImpl::size_hint(self)
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl<A, B> DoubleEndedIterator for Zip<A, B> where
806 A: DoubleEndedIterator + ExactSizeIterator,
807 B: DoubleEndedIterator + ExactSizeIterator,
810 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
811 ZipImpl::next_back(self)
815 // Zip specialization trait
817 trait ZipImpl<A, B> {
819 fn new(a: A, b: B) -> Self;
820 fn next(&mut self) -> Option<Self::Item>;
821 fn size_hint(&self) -> (usize, Option<usize>);
822 fn next_back(&mut self) -> Option<Self::Item>
823 where A: DoubleEndedIterator + ExactSizeIterator,
824 B: DoubleEndedIterator + ExactSizeIterator;
829 impl<A, B> ZipImpl<A, B> for Zip<A, B>
830 where A: Iterator, B: Iterator
832 type Item = (A::Item, B::Item);
833 default fn new(a: A, b: B) -> Self {
843 default fn next(&mut self) -> Option<(A::Item, B::Item)> {
844 self.a.next().and_then(|x| {
845 self.b.next().and_then(|y| {
852 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
853 where A: DoubleEndedIterator + ExactSizeIterator,
854 B: DoubleEndedIterator + ExactSizeIterator
856 let a_sz = self.a.len();
857 let b_sz = self.b.len();
859 // Adjust a, b to equal length
861 for _ in 0..a_sz - b_sz { self.a.next_back(); }
863 for _ in 0..b_sz - a_sz { self.b.next_back(); }
866 match (self.a.next_back(), self.b.next_back()) {
867 (Some(x), Some(y)) => Some((x, y)),
868 (None, None) => None,
874 default fn size_hint(&self) -> (usize, Option<usize>) {
875 let (a_lower, a_upper) = self.a.size_hint();
876 let (b_lower, b_upper) = self.b.size_hint();
878 let lower = cmp::min(a_lower, b_lower);
880 let upper = match (a_upper, b_upper) {
881 (Some(x), Some(y)) => Some(cmp::min(x,y)),
882 (Some(x), None) => Some(x),
883 (None, Some(y)) => Some(y),
892 impl<A, B> ZipImpl<A, B> for Zip<A, B>
893 where A: TrustedRandomAccess, B: TrustedRandomAccess
895 fn new(a: A, b: B) -> Self {
896 let len = cmp::min(a.len(), b.len());
906 fn next(&mut self) -> Option<(A::Item, B::Item)> {
907 if self.index < self.len {
911 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
913 } else if A::may_have_side_effect() && self.index < self.a.len() {
914 // match the base implementation's potential side effects
916 self.a.get_unchecked(self.index);
926 fn size_hint(&self) -> (usize, Option<usize>) {
927 let len = self.len - self.index;
932 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
933 where A: DoubleEndedIterator + ExactSizeIterator,
934 B: DoubleEndedIterator + ExactSizeIterator
936 // Adjust a, b to equal length
937 if A::may_have_side_effect() {
938 let sz = self.a.len();
940 for _ in 0..sz - cmp::max(self.len, self.index) {
945 if B::may_have_side_effect() {
946 let sz = self.b.len();
948 for _ in 0..sz - self.len {
953 if self.index < self.len {
957 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
965 #[stable(feature = "rust1", since = "1.0.0")]
966 impl<A, B> ExactSizeIterator for Zip<A, B>
967 where A: ExactSizeIterator, B: ExactSizeIterator {}
970 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
971 where A: TrustedRandomAccess,
972 B: TrustedRandomAccess,
974 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
975 (self.a.get_unchecked(i), self.b.get_unchecked(i))
978 fn may_have_side_effect() -> bool {
979 A::may_have_side_effect() || B::may_have_side_effect()
983 #[unstable(feature = "fused", issue = "35602")]
984 impl<A, B> FusedIterator for Zip<A, B>
985 where A: FusedIterator, B: FusedIterator, {}
987 #[unstable(feature = "trusted_len", issue = "37572")]
988 unsafe impl<A, B> TrustedLen for Zip<A, B>
989 where A: TrustedLen, B: TrustedLen,
992 /// An iterator that maps the values of `iter` with `f`.
994 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
995 /// documentation for more.
997 /// [`map`]: trait.Iterator.html#method.map
998 /// [`Iterator`]: trait.Iterator.html
1000 /// # Notes about side effects
1002 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
1003 /// you can also [`map`] backwards:
1006 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
1008 /// assert_eq!(v, [4, 3, 2]);
1011 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1013 /// But if your closure has state, iterating backwards may act in a way you do
1014 /// not expect. Let's go through an example. First, in the forward direction:
1019 /// for pair in vec!['a', 'b', 'c'].into_iter()
1020 /// .map(|letter| { c += 1; (letter, c) }) {
1021 /// println!("{:?}", pair);
1025 /// This will print "('a', 1), ('b', 2), ('c', 3)".
1027 /// Now consider this twist where we add a call to `rev`. This version will
1028 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
1029 /// but the values of the counter still go in order. This is because `map()` is
1030 /// still being called lazilly on each item, but we are popping items off the
1031 /// back of the vector now, instead of shifting them from the front.
1036 /// for pair in vec!['a', 'b', 'c'].into_iter()
1037 /// .map(|letter| { c += 1; (letter, c) })
1039 /// println!("{:?}", pair);
1042 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1043 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub struct Map<I, F> {
1050 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1051 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
1052 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1053 f.debug_struct("Map")
1054 .field("iter", &self.iter)
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
1064 fn next(&mut self) -> Option<B> {
1065 self.iter.next().map(&mut self.f)
1069 fn size_hint(&self) -> (usize, Option<usize>) {
1070 self.iter.size_hint()
1073 fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1074 where G: FnMut(Acc, Self::Item) -> Acc,
1077 self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
1083 F: FnMut(I::Item) -> B,
1086 fn next_back(&mut self) -> Option<B> {
1087 self.iter.next_back().map(&mut self.f)
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
1093 where F: FnMut(I::Item) -> B
1095 fn len(&self) -> usize {
1099 fn is_empty(&self) -> bool {
1100 self.iter.is_empty()
1104 #[unstable(feature = "fused", issue = "35602")]
1105 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1106 where F: FnMut(I::Item) -> B {}
1108 #[unstable(feature = "trusted_len", issue = "37572")]
1109 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1110 where I: TrustedLen,
1111 F: FnMut(I::Item) -> B {}
1114 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1115 where I: TrustedRandomAccess,
1116 F: FnMut(I::Item) -> B,
1118 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1119 (self.f)(self.iter.get_unchecked(i))
1122 fn may_have_side_effect() -> bool { true }
1125 /// An iterator that filters the elements of `iter` with `predicate`.
1127 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1128 /// documentation for more.
1130 /// [`filter`]: trait.Iterator.html#method.filter
1131 /// [`Iterator`]: trait.Iterator.html
1132 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1133 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub struct Filter<I, P> {
1140 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1141 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1142 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1143 f.debug_struct("Filter")
1144 .field("iter", &self.iter)
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
1151 type Item = I::Item;
1154 fn next(&mut self) -> Option<I::Item> {
1155 for x in &mut self.iter {
1156 if (self.predicate)(&x) {
1164 fn size_hint(&self) -> (usize, Option<usize>) {
1165 let (_, upper) = self.iter.size_hint();
1166 (0, upper) // can't know a lower bound, due to the predicate
1169 // this special case allows the compiler to make `.filter(_).count()`
1170 // branchless. Barring perfect branch prediction (which is unattainable in
1171 // the general case), this will be much faster in >90% of cases (containing
1172 // virtually all real workloads) and only a tiny bit slower in the rest.
1174 // Having this specialization thus allows us to write `.filter(p).count()`
1175 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1176 // less readable and also less backwards-compatible to Rust before 1.10.
1178 // Using the branchless version will also simplify the LLVM byte code, thus
1179 // leaving more budget for LLVM optimizations.
1181 fn count(mut self) -> usize {
1183 for x in &mut self.iter {
1184 count += (self.predicate)(&x) as usize;
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1192 where P: FnMut(&I::Item) -> bool,
1195 fn next_back(&mut self) -> Option<I::Item> {
1196 for x in self.iter.by_ref().rev() {
1197 if (self.predicate)(&x) {
1205 #[unstable(feature = "fused", issue = "35602")]
1206 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1207 where P: FnMut(&I::Item) -> bool {}
1209 /// An iterator that uses `f` to both filter and map elements from `iter`.
1211 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1212 /// documentation for more.
1214 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1215 /// [`Iterator`]: trait.Iterator.html
1216 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1217 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub struct FilterMap<I, F> {
1224 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1225 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1227 f.debug_struct("FilterMap")
1228 .field("iter", &self.iter)
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1235 where F: FnMut(I::Item) -> Option<B>,
1240 fn next(&mut self) -> Option<B> {
1241 for x in self.iter.by_ref() {
1242 if let Some(y) = (self.f)(x) {
1250 fn size_hint(&self) -> (usize, Option<usize>) {
1251 let (_, upper) = self.iter.size_hint();
1252 (0, upper) // can't know a lower bound, due to the predicate
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1258 where F: FnMut(I::Item) -> Option<B>,
1261 fn next_back(&mut self) -> Option<B> {
1262 for x in self.iter.by_ref().rev() {
1263 if let Some(y) = (self.f)(x) {
1271 #[unstable(feature = "fused", issue = "35602")]
1272 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1273 where F: FnMut(I::Item) -> Option<B> {}
1275 /// An iterator that yields the current count and the element during iteration.
1277 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1278 /// documentation for more.
1280 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1281 /// [`Iterator`]: trait.Iterator.html
1282 #[derive(Clone, Debug)]
1283 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub struct Enumerate<I> {
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 impl<I> Iterator for Enumerate<I> where I: Iterator {
1292 type Item = (usize, <I as Iterator>::Item);
1294 /// # Overflow Behavior
1296 /// The method does no guarding against overflows, so enumerating more than
1297 /// `usize::MAX` elements either produces the wrong result or panics. If
1298 /// debug assertions are enabled, a panic is guaranteed.
1302 /// Might panic if the index of the element overflows a `usize`.
1304 #[rustc_inherit_overflow_checks]
1305 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1306 self.iter.next().map(|a| {
1307 let ret = (self.count, a);
1308 // Possible undefined overflow.
1315 fn size_hint(&self) -> (usize, Option<usize>) {
1316 self.iter.size_hint()
1320 #[rustc_inherit_overflow_checks]
1321 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1322 self.iter.nth(n).map(|a| {
1323 let i = self.count + n;
1330 fn count(self) -> usize {
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<I> DoubleEndedIterator for Enumerate<I> where
1337 I: ExactSizeIterator + DoubleEndedIterator
1340 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1341 self.iter.next_back().map(|a| {
1342 let len = self.iter.len();
1343 // Can safely add, `ExactSizeIterator` promises that the number of
1344 // elements fits into a `usize`.
1345 (self.count + len, a)
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1352 fn len(&self) -> usize {
1356 fn is_empty(&self) -> bool {
1357 self.iter.is_empty()
1362 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1363 where I: TrustedRandomAccess
1365 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1366 (self.count + i, self.iter.get_unchecked(i))
1369 fn may_have_side_effect() -> bool {
1370 I::may_have_side_effect()
1374 #[unstable(feature = "fused", issue = "35602")]
1375 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1377 #[unstable(feature = "trusted_len", issue = "37572")]
1378 unsafe impl<I> TrustedLen for Enumerate<I>
1379 where I: TrustedLen,
1383 /// An iterator with a `peek()` that returns an optional reference to the next
1386 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1387 /// documentation for more.
1389 /// [`peekable`]: trait.Iterator.html#method.peekable
1390 /// [`Iterator`]: trait.Iterator.html
1391 #[derive(Clone, Debug)]
1392 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 pub struct Peekable<I: Iterator> {
1396 /// Remember a peeked value, even if it was None.
1397 peeked: Option<Option<I::Item>>,
1400 // Peekable must remember if a None has been seen in the `.peek()` method.
1401 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1402 // underlying iterator at most once. This does not by itself make the iterator
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl<I: Iterator> Iterator for Peekable<I> {
1406 type Item = I::Item;
1409 fn next(&mut self) -> Option<I::Item> {
1410 match self.peeked.take() {
1412 None => self.iter.next(),
1417 #[rustc_inherit_overflow_checks]
1418 fn count(mut self) -> usize {
1419 match self.peeked.take() {
1421 Some(Some(_)) => 1 + self.iter.count(),
1422 None => self.iter.count(),
1427 fn nth(&mut self, n: usize) -> Option<I::Item> {
1428 match self.peeked.take() {
1429 // the .take() below is just to avoid "move into pattern guard"
1430 Some(ref mut v) if n == 0 => v.take(),
1432 Some(Some(_)) => self.iter.nth(n - 1),
1433 None => self.iter.nth(n),
1438 fn last(mut self) -> Option<I::Item> {
1439 let peek_opt = match self.peeked.take() {
1440 Some(None) => return None,
1444 self.iter.last().or(peek_opt)
1448 fn size_hint(&self) -> (usize, Option<usize>) {
1449 let peek_len = match self.peeked {
1450 Some(None) => return (0, Some(0)),
1454 let (lo, hi) = self.iter.size_hint();
1455 let lo = lo.saturating_add(peek_len);
1456 let hi = hi.and_then(|x| x.checked_add(peek_len));
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1464 #[unstable(feature = "fused", issue = "35602")]
1465 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1467 impl<I: Iterator> Peekable<I> {
1468 /// Returns a reference to the next() value without advancing the iterator.
1470 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1471 /// But if the iteration is over, `None` is returned.
1473 /// [`next`]: trait.Iterator.html#tymethod.next
1475 /// Because `peek()` returns a reference, and many iterators iterate over
1476 /// references, there can be a possibly confusing situation where the
1477 /// return value is a double reference. You can see this effect in the
1485 /// let xs = [1, 2, 3];
1487 /// let mut iter = xs.iter().peekable();
1489 /// // peek() lets us see into the future
1490 /// assert_eq!(iter.peek(), Some(&&1));
1491 /// assert_eq!(iter.next(), Some(&1));
1493 /// assert_eq!(iter.next(), Some(&2));
1495 /// // The iterator does not advance even if we `peek` multiple times
1496 /// assert_eq!(iter.peek(), Some(&&3));
1497 /// assert_eq!(iter.peek(), Some(&&3));
1499 /// assert_eq!(iter.next(), Some(&3));
1501 /// // After the iterator is finished, so is `peek()`
1502 /// assert_eq!(iter.peek(), None);
1503 /// assert_eq!(iter.next(), None);
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 pub fn peek(&mut self) -> Option<&I::Item> {
1508 if self.peeked.is_none() {
1509 self.peeked = Some(self.iter.next());
1512 Some(Some(ref value)) => Some(value),
1514 _ => unreachable!(),
1519 /// An iterator that rejects elements while `predicate` is true.
1521 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1522 /// documentation for more.
1524 /// [`skip_while`]: trait.Iterator.html#method.skip_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 SkipWhile<I, P> {
1535 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1536 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1538 f.debug_struct("SkipWhile")
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 SkipWhile<I, P>
1547 where P: FnMut(&I::Item) -> bool
1549 type Item = I::Item;
1552 fn next(&mut self) -> Option<I::Item> {
1553 for x in self.iter.by_ref() {
1554 if self.flag || !(self.predicate)(&x) {
1563 fn size_hint(&self) -> (usize, Option<usize>) {
1564 let (_, upper) = self.iter.size_hint();
1565 (0, upper) // can't know a lower bound, due to the predicate
1569 #[unstable(feature = "fused", issue = "35602")]
1570 impl<I, P> FusedIterator for SkipWhile<I, P>
1571 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1573 /// An iterator that only accepts elements while `predicate` is true.
1575 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
1576 /// documentation for more.
1578 /// [`take_while`]: trait.Iterator.html#method.take_while
1579 /// [`Iterator`]: trait.Iterator.html
1580 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1581 #[stable(feature = "rust1", since = "1.0.0")]
1583 pub struct TakeWhile<I, P> {
1589 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1590 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1591 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1592 f.debug_struct("TakeWhile")
1593 .field("iter", &self.iter)
1594 .field("flag", &self.flag)
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1601 where P: FnMut(&I::Item) -> bool
1603 type Item = I::Item;
1606 fn next(&mut self) -> Option<I::Item> {
1610 self.iter.next().and_then(|x| {
1611 if (self.predicate)(&x) {
1622 fn size_hint(&self) -> (usize, Option<usize>) {
1623 let (_, upper) = self.iter.size_hint();
1624 (0, upper) // can't know a lower bound, due to the predicate
1628 #[unstable(feature = "fused", issue = "35602")]
1629 impl<I, P> FusedIterator for TakeWhile<I, P>
1630 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1632 /// An iterator that skips over `n` elements of `iter`.
1634 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
1635 /// documentation for more.
1637 /// [`skip`]: trait.Iterator.html#method.skip
1638 /// [`Iterator`]: trait.Iterator.html
1639 #[derive(Clone, Debug)]
1640 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 pub struct Skip<I> {
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<I> Iterator for Skip<I> where I: Iterator {
1649 type Item = <I as Iterator>::Item;
1652 fn next(&mut self) -> Option<I::Item> {
1658 self.iter.nth(old_n)
1663 fn nth(&mut self, n: usize) -> Option<I::Item> {
1664 // Can't just add n + self.n due to overflow.
1668 let to_skip = self.n;
1671 if self.iter.nth(to_skip-1).is_none() {
1679 fn count(self) -> usize {
1680 self.iter.count().saturating_sub(self.n)
1684 fn last(mut self) -> Option<I::Item> {
1688 let next = self.next();
1690 // recurse. n should be 0.
1691 self.last().or(next)
1699 fn size_hint(&self) -> (usize, Option<usize>) {
1700 let (lower, upper) = self.iter.size_hint();
1702 let lower = lower.saturating_sub(self.n);
1703 let upper = upper.map(|x| x.saturating_sub(self.n));
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1712 #[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
1713 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1714 fn next_back(&mut self) -> Option<Self::Item> {
1716 self.iter.next_back()
1723 #[unstable(feature = "fused", issue = "35602")]
1724 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
1726 /// An iterator that only iterates over the first `n` iterations of `iter`.
1728 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
1729 /// documentation for more.
1731 /// [`take`]: trait.Iterator.html#method.take
1732 /// [`Iterator`]: trait.Iterator.html
1733 #[derive(Clone, Debug)]
1734 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 pub struct Take<I> {
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<I> Iterator for Take<I> where I: Iterator{
1743 type Item = <I as Iterator>::Item;
1746 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1756 fn nth(&mut self, n: usize) -> Option<I::Item> {
1762 self.iter.nth(self.n - 1);
1770 fn size_hint(&self) -> (usize, Option<usize>) {
1771 let (lower, upper) = self.iter.size_hint();
1773 let lower = cmp::min(lower, self.n);
1775 let upper = match upper {
1776 Some(x) if x < self.n => Some(x),
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1787 #[unstable(feature = "fused", issue = "35602")]
1788 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
1790 /// An iterator to maintain state while iterating another iterator.
1792 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
1793 /// documentation for more.
1795 /// [`scan`]: trait.Iterator.html#method.scan
1796 /// [`Iterator`]: trait.Iterator.html
1797 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1798 #[stable(feature = "rust1", since = "1.0.0")]
1800 pub struct Scan<I, St, F> {
1806 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1807 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1809 f.debug_struct("Scan")
1810 .field("iter", &self.iter)
1811 .field("state", &self.state)
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1819 F: FnMut(&mut St, I::Item) -> Option<B>,
1824 fn next(&mut self) -> Option<B> {
1825 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1829 fn size_hint(&self) -> (usize, Option<usize>) {
1830 let (_, upper) = self.iter.size_hint();
1831 (0, upper) // can't know a lower bound, due to the scan function
1835 #[unstable(feature = "fused", issue = "35602")]
1836 impl<B, I, St, F> FusedIterator for Scan<I, St, F>
1837 where I: FusedIterator, F: FnMut(&mut St, I::Item) -> Option<B> {}
1839 /// An iterator that maps each element to an iterator, and yields the elements
1840 /// of the produced iterators.
1842 /// This `struct` is created by the [`flat_map`] method on [`Iterator`]. See its
1843 /// documentation for more.
1845 /// [`flat_map`]: trait.Iterator.html#method.flat_map
1846 /// [`Iterator`]: trait.Iterator.html
1847 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1848 #[stable(feature = "rust1", since = "1.0.0")]
1850 pub struct FlatMap<I, U: IntoIterator, F> {
1853 frontiter: Option<U::IntoIter>,
1854 backiter: Option<U::IntoIter>,
1857 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1858 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1859 where U::IntoIter: fmt::Debug
1861 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1862 f.debug_struct("FlatMap")
1863 .field("iter", &self.iter)
1864 .field("frontiter", &self.frontiter)
1865 .field("backiter", &self.backiter)
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1872 where F: FnMut(I::Item) -> U,
1874 type Item = U::Item;
1877 fn next(&mut self) -> Option<U::Item> {
1879 if let Some(ref mut inner) = self.frontiter {
1880 if let Some(x) = inner.by_ref().next() {
1884 match self.iter.next().map(&mut self.f) {
1885 None => return self.backiter.as_mut().and_then(|it| it.next()),
1886 next => self.frontiter = next.map(IntoIterator::into_iter),
1892 fn size_hint(&self) -> (usize, Option<usize>) {
1893 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1894 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1895 let lo = flo.saturating_add(blo);
1896 match (self.iter.size_hint(), fhi, bhi) {
1897 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1905 F: FnMut(I::Item) -> U,
1907 U::IntoIter: DoubleEndedIterator
1910 fn next_back(&mut self) -> Option<U::Item> {
1912 if let Some(ref mut inner) = self.backiter {
1913 if let Some(y) = inner.next_back() {
1917 match self.iter.next_back().map(&mut self.f) {
1918 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1919 next => self.backiter = next.map(IntoIterator::into_iter),
1925 #[unstable(feature = "fused", issue = "35602")]
1926 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
1927 where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
1929 /// An iterator that yields `None` forever after the underlying iterator
1930 /// yields `None` once.
1932 /// This `struct` is created by the [`fuse`] method on [`Iterator`]. See its
1933 /// documentation for more.
1935 /// [`fuse`]: trait.Iterator.html#method.fuse
1936 /// [`Iterator`]: trait.Iterator.html
1937 #[derive(Clone, Debug)]
1938 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 pub struct Fuse<I> {
1945 #[unstable(feature = "fused", issue = "35602")]
1946 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl<I> Iterator for Fuse<I> where I: Iterator {
1950 type Item = <I as Iterator>::Item;
1953 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
1957 let next = self.iter.next();
1958 self.done = next.is_none();
1964 default fn nth(&mut self, n: usize) -> Option<I::Item> {
1968 let nth = self.iter.nth(n);
1969 self.done = nth.is_none();
1975 default fn last(self) -> Option<I::Item> {
1984 default fn count(self) -> usize {
1993 default fn size_hint(&self) -> (usize, Option<usize>) {
1997 self.iter.size_hint()
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2005 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2009 let next = self.iter.next_back();
2010 self.done = next.is_none();
2016 unsafe impl<I> TrustedRandomAccess for Fuse<I>
2017 where I: TrustedRandomAccess,
2019 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
2020 self.iter.get_unchecked(i)
2023 fn may_have_side_effect() -> bool {
2024 I::may_have_side_effect()
2028 #[unstable(feature = "fused", issue = "35602")]
2029 impl<I> Iterator for Fuse<I> where I: FusedIterator {
2031 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2036 fn nth(&mut self, n: usize) -> Option<I::Item> {
2041 fn last(self) -> Option<I::Item> {
2046 fn count(self) -> usize {
2051 fn size_hint(&self) -> (usize, Option<usize>) {
2052 self.iter.size_hint()
2056 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
2057 impl<I> DoubleEndedIterator for Fuse<I>
2058 where I: DoubleEndedIterator + FusedIterator
2061 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2062 self.iter.next_back()
2067 #[stable(feature = "rust1", since = "1.0.0")]
2068 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
2069 fn len(&self) -> usize {
2073 fn is_empty(&self) -> bool {
2074 self.iter.is_empty()
2078 /// An iterator that calls a function with a reference to each element before
2081 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2082 /// documentation for more.
2084 /// [`inspect`]: trait.Iterator.html#method.inspect
2085 /// [`Iterator`]: trait.Iterator.html
2086 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2087 #[stable(feature = "rust1", since = "1.0.0")]
2089 pub struct Inspect<I, F> {
2094 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2095 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2097 f.debug_struct("Inspect")
2098 .field("iter", &self.iter)
2103 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2105 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2106 if let Some(ref a) = elt {
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2116 type Item = I::Item;
2119 fn next(&mut self) -> Option<I::Item> {
2120 let next = self.iter.next();
2121 self.do_inspect(next)
2125 fn size_hint(&self) -> (usize, Option<usize>) {
2126 self.iter.size_hint()
2130 #[stable(feature = "rust1", since = "1.0.0")]
2131 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2132 where F: FnMut(&I::Item),
2135 fn next_back(&mut self) -> Option<I::Item> {
2136 let next = self.iter.next_back();
2137 self.do_inspect(next)
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2143 where F: FnMut(&I::Item)
2145 fn len(&self) -> usize {
2149 fn is_empty(&self) -> bool {
2150 self.iter.is_empty()
2154 #[unstable(feature = "fused", issue = "35602")]
2155 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
2156 where F: FnMut(&I::Item) {}