1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Composable external iteration.
13 //! If you've found yourself with a collection of some kind, and needed to
14 //! perform an operation on the elements of said collection, you'll quickly run
15 //! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
16 //! it's worth becoming familiar with them.
18 //! Before explaining more, let's talk about how this module is structured:
22 //! This module is largely organized by type:
24 //! * [Traits] are the core portion: these traits define what kind of iterators
25 //! exist and what you can do with them. The methods of these traits are worth
26 //! putting some extra study time into.
27 //! * [Functions] provide some helpful ways to create some basic iterators.
28 //! * [Structs] are often the return types of the various methods on this
29 //! module's traits. You'll usually want to look at the method that creates
30 //! the `struct`, rather than the `struct` itself. For more detail about why,
31 //! see '[Implementing Iterator](#implementing-iterator)'.
34 //! [Functions]: #functions
35 //! [Structs]: #structs
37 //! That's it! Let's dig into iterators.
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
47 //! fn next(&mut self) -> Option<Self::Item>;
51 //! An iterator has a method, [`next()`], which when called, returns an
52 //! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
53 //! are elements, and once they've all been exhausted, will return `None` to
54 //! indicate that iteration is finished. Individual iterators may choose to
55 //! resume iteration, and so calling [`next()`] again may or may not eventually
56 //! start returning `Some(Item)` again at some point.
58 //! [`Iterator`]'s full definition includes a number of other methods as well,
59 //! but they are default methods, built on top of [`next()`], and so you get
62 //! Iterators are also composable, and it's common to chain them together to do
63 //! more complex forms of processing. See the [Adapters](#adapters) section
64 //! below for more details.
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../../std/option/enum.Option.html
70 //! # The three forms of iteration
72 //! There are three common methods which can create iterators from a collection:
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
81 //! # Implementing Iterator
83 //! Creating an iterator of your own involves two steps: creating a `struct` to
84 //! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
85 //! `struct`. This is why there are so many `struct`s in this module: there is
86 //! one for each iterator and iterator adapter.
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
91 //! // First, the struct:
93 //! /// An iterator which counts from one to five
98 //! // we want our count to start at one, so let's add a new() method to help.
99 //! // This isn't strictly necessary, but is convenient. Note that we start
100 //! // `count` at zero, we'll see why in `next()`'s implementation below.
102 //! fn new() -> Counter {
103 //! Counter { count: 0 }
107 //! // Then, we implement `Iterator` for our `Counter`:
109 //! impl Iterator for Counter {
110 //! // we will be counting with usize
111 //! type Item = usize;
113 //! // next() is the only required method
114 //! fn next(&mut self) -> Option<usize> {
115 //! // increment our count. This is why we started at zero.
118 //! // check to see if we've finished counting or not.
119 //! if self.count < 6 {
127 //! // And now we can use it!
129 //! let mut counter = Counter::new();
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
147 //! This will print `1` through `5`, each on their own line.
149 //! Calling `next()` this way gets repetitive. Rust has a construct which can
150 //! call `next()` on your iterator, until it reaches `None`. Let's go over that
153 //! # for Loops and IntoIterator
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
159 //! let values = vec![1, 2, 3, 4, 5];
161 //! for x in values {
162 //! println!("{}", x);
166 //! This will print the numbers one through five, each on their own line. But
167 //! you'll notice something here: we never called anything on our vector to
168 //! produce an iterator. What gives?
170 //! There's a trait in the standard library for converting something into an
171 //! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
172 //! which converts the thing implementing [`IntoIterator`] into an iterator.
173 //! Let's take a look at that `for` loop again, and what the compiler converts
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
180 //! let values = vec![1, 2, 3, 4, 5];
182 //! for x in values {
183 //! println!("{}", x);
187 //! Rust de-sugars this into:
190 //! let values = vec![1, 2, 3, 4, 5];
192 //! let result = match IntoIterator::into_iter(values) {
193 //! mut iter => loop {
194 //! match iter.next() {
195 //! Some(x) => { println!("{}", x); },
204 //! First, we call `into_iter()` on the value. Then, we match on the iterator
205 //! that returns, calling [`next()`] over and over until we see a `None`. At
206 //! that point, we `break` out of the loop, and we're done iterating.
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
212 //! impl<I: Iterator> IntoIterator for I
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
218 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
219 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
220 //! will allow your collection to be used with the `for` loop.
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
237 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
238 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
239 //! until you call [`next()`]. This is sometimes a source of confusion when
240 //! creating an iterator solely for its side effects. For example, the [`map()`]
241 //! method calls a closure on each element it iterates over:
244 //! # #![allow(unused_must_use)]
245 //! let v = vec![1, 2, 3, 4, 5];
246 //! v.iter().map(|x| println!("{}", x));
249 //! This will not print any values, as we only created an iterator, rather than
250 //! using it. The compiler will warn us about this kind of behavior:
253 //! warning: unused result which must be used: iterator adaptors are lazy and
254 //! do nothing unless consumed
257 //! The idiomatic way to write a [`map()`] for its side effects is to use a
258 //! `for` loop instead:
261 //! let v = vec![1, 2, 3, 4, 5];
264 //! println!("{}", x);
268 //! [`map()`]: trait.Iterator.html#method.map
270 //! The two most common ways to evaluate an iterator are to use a `for` loop
271 //! like this, or using the [`collect()`] adapter to produce a new collection.
273 //! [`collect()`]: trait.Iterator.html#method.collect
277 //! Iterators do not have to be finite. As an example, an open-ended range is
278 //! an infinite iterator:
281 //! let numbers = 0..;
284 //! It is common to use the [`take()`] iterator adapter to turn an infinite
285 //! iterator into a finite one:
288 //! let numbers = 0..;
289 //! let five_numbers = numbers.take(5);
291 //! for number in five_numbers {
292 //! println!("{}", number);
296 //! This will print the numbers `0` through `4`, each on their own line.
298 //! [`take()`]: trait.Iterator.html#method.take
300 #![stable(feature = "rust1", since = "1.0.0")]
304 use default::Default;
306 use iter_private::TrustedRandomAccess;
308 use option::Option::{self, Some, None};
311 #[stable(feature = "rust1", since = "1.0.0")]
312 pub use self::iterator::Iterator;
314 #[unstable(feature = "step_trait",
315 reason = "likely to be replaced by finer-grained traits",
317 pub use self::range::Step;
318 #[unstable(feature = "step_by", reason = "recent addition",
320 pub use self::range::StepBy;
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub use self::sources::{Repeat, repeat};
324 #[stable(feature = "iter_empty", since = "1.2.0")]
325 pub use self::sources::{Empty, empty};
326 #[stable(feature = "iter_once", since = "1.2.0")]
327 pub use self::sources::{Once, once};
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend};
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub use self::traits::{ExactSizeIterator, Sum, Product};
333 #[unstable(feature = "fused", issue = "35602")]
334 pub use self::traits::FusedIterator;
341 /// An double-ended iterator with the direction inverted.
343 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
344 /// documentation for more.
346 /// [`rev()`]: trait.Iterator.html#method.rev
347 /// [`Iterator`]: trait.Iterator.html
348 #[derive(Clone, Debug)]
349 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
350 #[stable(feature = "rust1", since = "1.0.0")]
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
357 type Item = <I as Iterator>::Item;
360 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
362 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
368 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
371 #[stable(feature = "rust1", since = "1.0.0")]
372 impl<I> ExactSizeIterator for Rev<I>
373 where I: ExactSizeIterator + DoubleEndedIterator {}
375 #[unstable(feature = "fused", issue = "35602")]
376 impl<I> FusedIterator for Rev<I>
377 where I: FusedIterator + DoubleEndedIterator {}
379 /// An iterator that clones the elements of an underlying iterator.
381 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
382 /// documentation for more.
384 /// [`cloned()`]: trait.Iterator.html#method.cloned
385 /// [`Iterator`]: trait.Iterator.html
386 #[stable(feature = "iter_cloned", since = "1.1.0")]
387 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
388 #[derive(Clone, Debug)]
389 pub struct Cloned<I> {
393 #[stable(feature = "rust1", since = "1.0.0")]
394 impl<'a, I, T: 'a> Iterator for Cloned<I>
395 where I: Iterator<Item=&'a T>, T: Clone
399 fn next(&mut self) -> Option<T> {
400 self.it.next().cloned()
403 fn size_hint(&self) -> (usize, Option<usize>) {
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
410 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
412 fn next_back(&mut self) -> Option<T> {
413 self.it.next_back().cloned()
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
419 where I: ExactSizeIterator<Item=&'a T>, T: Clone
422 #[unstable(feature = "fused", issue = "35602")]
423 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
424 where I: FusedIterator<Item=&'a T>, T: Clone
427 /// An iterator that repeats endlessly.
429 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
430 /// documentation for more.
432 /// [`cycle()`]: trait.Iterator.html#method.cycle
433 /// [`Iterator`]: trait.Iterator.html
434 #[derive(Clone, Debug)]
435 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub struct Cycle<I> {
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
444 type Item = <I as Iterator>::Item;
447 fn next(&mut self) -> Option<<I as Iterator>::Item> {
448 match self.iter.next() {
449 None => { self.iter = self.orig.clone(); self.iter.next() }
455 fn size_hint(&self) -> (usize, Option<usize>) {
456 // the cycle iterator is either empty or infinite
457 match self.orig.size_hint() {
458 sz @ (0, Some(0)) => sz,
460 _ => (usize::MAX, None)
465 #[unstable(feature = "fused", issue = "35602")]
466 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
468 /// An iterator that strings two iterators together.
470 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
471 /// documentation for more.
473 /// [`chain()`]: trait.Iterator.html#method.chain
474 /// [`Iterator`]: trait.Iterator.html
475 #[derive(Clone, Debug)]
476 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub struct Chain<A, B> {
484 // The iterator protocol specifies that iteration ends with the return value
485 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
486 // further calls return. The chain adaptor must account for this since it uses
489 // It uses three states:
491 // - Both: `a` and `b` are remaining
492 // - Front: `a` remaining
493 // - Back: `b` remaining
495 // The fourth state (neither iterator is remaining) only occurs after Chain has
496 // returned None once, so we don't need to store this state.
497 #[derive(Clone, Debug)]
499 // both front and back iterator are remaining
501 // only front is remaining
503 // only back is remaining
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl<A, B> Iterator for Chain<A, B> where
510 B: Iterator<Item = A::Item>
515 fn next(&mut self) -> Option<A::Item> {
517 ChainState::Both => match self.a.next() {
518 elt @ Some(..) => elt,
520 self.state = ChainState::Back;
524 ChainState::Front => self.a.next(),
525 ChainState::Back => self.b.next(),
530 #[rustc_inherit_overflow_checks]
531 fn count(self) -> usize {
533 ChainState::Both => self.a.count() + self.b.count(),
534 ChainState::Front => self.a.count(),
535 ChainState::Back => self.b.count(),
540 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
542 ChainState::Both | ChainState::Front => {
543 for x in self.a.by_ref() {
549 if let ChainState::Both = self.state {
550 self.state = ChainState::Back;
553 ChainState::Back => {}
555 if let ChainState::Back = self.state {
563 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
564 P: FnMut(&Self::Item) -> bool,
567 ChainState::Both => match self.a.find(&mut predicate) {
569 self.state = ChainState::Back;
570 self.b.find(predicate)
574 ChainState::Front => self.a.find(predicate),
575 ChainState::Back => self.b.find(predicate),
580 fn last(self) -> Option<A::Item> {
582 ChainState::Both => {
583 // Must exhaust a before b.
584 let a_last = self.a.last();
585 let b_last = self.b.last();
588 ChainState::Front => self.a.last(),
589 ChainState::Back => self.b.last()
594 fn size_hint(&self) -> (usize, Option<usize>) {
595 let (a_lower, a_upper) = self.a.size_hint();
596 let (b_lower, b_upper) = self.b.size_hint();
598 let lower = a_lower.saturating_add(b_lower);
600 let upper = match (a_upper, b_upper) {
601 (Some(x), Some(y)) => x.checked_add(y),
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl<A, B> DoubleEndedIterator for Chain<A, B> where
611 A: DoubleEndedIterator,
612 B: DoubleEndedIterator<Item=A::Item>,
615 fn next_back(&mut self) -> Option<A::Item> {
617 ChainState::Both => match self.b.next_back() {
618 elt @ Some(..) => elt,
620 self.state = ChainState::Front;
624 ChainState::Front => self.a.next_back(),
625 ChainState::Back => self.b.next_back(),
630 // Note: *both* must be fused to handle double-ended iterators.
631 #[unstable(feature = "fused", issue = "35602")]
632 impl<A, B> FusedIterator for Chain<A, B>
633 where A: FusedIterator,
634 B: FusedIterator<Item=A::Item>,
637 /// An iterator that iterates two other iterators simultaneously.
639 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
640 /// documentation for more.
642 /// [`zip()`]: trait.Iterator.html#method.zip
643 /// [`Iterator`]: trait.Iterator.html
644 #[derive(Clone, Debug)]
645 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
646 #[stable(feature = "rust1", since = "1.0.0")]
647 pub struct Zip<A, B> {
650 spec: <(A, B) as ZipImplData>::Data,
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
656 type Item = (A::Item, B::Item);
659 fn next(&mut self) -> Option<Self::Item> {
664 fn size_hint(&self) -> (usize, Option<usize>) {
665 ZipImpl::size_hint(self)
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl<A, B> DoubleEndedIterator for Zip<A, B> where
671 A: DoubleEndedIterator + ExactSizeIterator,
672 B: DoubleEndedIterator + ExactSizeIterator,
675 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
676 ZipImpl::next_back(self)
680 // Zip specialization trait
682 trait ZipImpl<A, B> {
684 fn new(a: A, b: B) -> Self;
685 fn next(&mut self) -> Option<Self::Item>;
686 fn size_hint(&self) -> (usize, Option<usize>);
687 fn next_back(&mut self) -> Option<Self::Item>
688 where A: DoubleEndedIterator + ExactSizeIterator,
689 B: DoubleEndedIterator + ExactSizeIterator;
692 // Zip specialization data members
695 type Data: 'static + Clone + Default + fmt::Debug;
699 impl<T> ZipImplData for T {
700 default type Data = ();
705 impl<A, B> ZipImpl<A, B> for Zip<A, B>
706 where A: Iterator, B: Iterator
708 type Item = (A::Item, B::Item);
709 default fn new(a: A, b: B) -> Self {
713 spec: Default::default(), // unused
718 default fn next(&mut self) -> Option<(A::Item, B::Item)> {
719 self.a.next().and_then(|x| {
720 self.b.next().and_then(|y| {
727 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
728 where A: DoubleEndedIterator + ExactSizeIterator,
729 B: DoubleEndedIterator + ExactSizeIterator
731 let a_sz = self.a.len();
732 let b_sz = self.b.len();
734 // Adjust a, b to equal length
736 for _ in 0..a_sz - b_sz { self.a.next_back(); }
738 for _ in 0..b_sz - a_sz { self.b.next_back(); }
741 match (self.a.next_back(), self.b.next_back()) {
742 (Some(x), Some(y)) => Some((x, y)),
743 (None, None) => None,
749 default fn size_hint(&self) -> (usize, Option<usize>) {
750 let (a_lower, a_upper) = self.a.size_hint();
751 let (b_lower, b_upper) = self.b.size_hint();
753 let lower = cmp::min(a_lower, b_lower);
755 let upper = match (a_upper, b_upper) {
756 (Some(x), Some(y)) => Some(cmp::min(x,y)),
757 (Some(x), None) => Some(x),
758 (None, Some(y)) => Some(y),
767 #[derive(Default, Debug, Clone)]
768 struct ZipImplFields {
774 impl<A, B> ZipImplData for (A, B)
775 where A: TrustedRandomAccess, B: TrustedRandomAccess
777 type Data = ZipImplFields;
781 impl<A, B> ZipImpl<A, B> for Zip<A, B>
782 where A: TrustedRandomAccess, B: TrustedRandomAccess
784 fn new(a: A, b: B) -> Self {
785 let len = cmp::min(a.len(), b.len());
789 spec: ZipImplFields {
797 fn next(&mut self) -> Option<(A::Item, B::Item)> {
798 if self.spec.index < self.spec.len {
799 let i = self.spec.index;
800 self.spec.index += 1;
802 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
810 fn size_hint(&self) -> (usize, Option<usize>) {
811 let len = self.spec.len - self.spec.index;
816 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
817 where A: DoubleEndedIterator + ExactSizeIterator,
818 B: DoubleEndedIterator + ExactSizeIterator
820 if self.spec.index < self.spec.len {
822 let i = self.spec.len;
824 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<A, B> ExactSizeIterator for Zip<A, B>
834 where A: ExactSizeIterator, B: ExactSizeIterator {}
837 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
838 where A: TrustedRandomAccess,
839 B: TrustedRandomAccess,
841 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
842 (self.a.get_unchecked(i), self.b.get_unchecked(i))
847 #[unstable(feature = "fused", issue = "35602")]
848 impl<A, B> FusedIterator for Zip<A, B>
849 where A: FusedIterator, B: FusedIterator, {}
851 /// An iterator that maps the values of `iter` with `f`.
853 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
854 /// documentation for more.
856 /// [`map()`]: trait.Iterator.html#method.map
857 /// [`Iterator`]: trait.Iterator.html
859 /// # Notes about side effects
861 /// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
862 /// you can also [`map()`] backwards:
865 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
867 /// assert_eq!(v, [4, 3, 2]);
870 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
872 /// But if your closure has state, iterating backwards may act in a way you do
873 /// not expect. Let's go through an example. First, in the forward direction:
878 /// for pair in vec!['a', 'b', 'c'].into_iter()
879 /// .map(|letter| { c += 1; (letter, c) }) {
880 /// println!("{:?}", pair);
884 /// This will print "('a', 1), ('b', 2), ('c', 3)".
886 /// Now consider this twist where we add a call to `rev`. This version will
887 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
888 /// but the values of the counter still go in order. This is because `map()` is
889 /// still being called lazilly on each item, but we are popping items off the
890 /// back of the vector now, instead of shifting them from the front.
895 /// for pair in vec!['a', 'b', 'c'].into_iter()
896 /// .map(|letter| { c += 1; (letter, c) })
898 /// println!("{:?}", pair);
901 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
902 #[stable(feature = "rust1", since = "1.0.0")]
904 pub struct Map<I, F> {
909 #[stable(feature = "core_impl_debug", since = "1.9.0")]
910 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
911 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
912 f.debug_struct("Map")
913 .field("iter", &self.iter)
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
923 fn next(&mut self) -> Option<B> {
924 self.iter.next().map(&mut self.f)
928 fn size_hint(&self) -> (usize, Option<usize>) {
929 self.iter.size_hint()
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
935 F: FnMut(I::Item) -> B,
938 fn next_back(&mut self) -> Option<B> {
939 self.iter.next_back().map(&mut self.f)
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
945 where F: FnMut(I::Item) -> B {}
947 #[unstable(feature = "fused", issue = "35602")]
948 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
949 where F: FnMut(I::Item) -> B {}
951 /// An iterator that filters the elements of `iter` with `predicate`.
953 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
954 /// documentation for more.
956 /// [`filter()`]: trait.Iterator.html#method.filter
957 /// [`Iterator`]: trait.Iterator.html
958 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
959 #[stable(feature = "rust1", since = "1.0.0")]
961 pub struct Filter<I, P> {
966 #[stable(feature = "core_impl_debug", since = "1.9.0")]
967 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
968 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
969 f.debug_struct("Filter")
970 .field("iter", &self.iter)
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
980 fn next(&mut self) -> Option<I::Item> {
981 for x in self.iter.by_ref() {
982 if (self.predicate)(&x) {
990 fn size_hint(&self) -> (usize, Option<usize>) {
991 let (_, upper) = self.iter.size_hint();
992 (0, upper) // can't know a lower bound, due to the predicate
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
998 where P: FnMut(&I::Item) -> bool,
1001 fn next_back(&mut self) -> Option<I::Item> {
1002 for x in self.iter.by_ref().rev() {
1003 if (self.predicate)(&x) {
1011 #[unstable(feature = "fused", issue = "35602")]
1012 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1013 where P: FnMut(&I::Item) -> bool {}
1015 /// An iterator that uses `f` to both filter and map elements from `iter`.
1017 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
1018 /// documentation for more.
1020 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
1021 /// [`Iterator`]: trait.Iterator.html
1022 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1023 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub struct FilterMap<I, F> {
1030 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1031 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1032 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1033 f.debug_struct("FilterMap")
1034 .field("iter", &self.iter)
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1041 where F: FnMut(I::Item) -> Option<B>,
1046 fn next(&mut self) -> Option<B> {
1047 for x in self.iter.by_ref() {
1048 if let Some(y) = (self.f)(x) {
1056 fn size_hint(&self) -> (usize, Option<usize>) {
1057 let (_, upper) = self.iter.size_hint();
1058 (0, upper) // can't know a lower bound, due to the predicate
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1064 where F: FnMut(I::Item) -> Option<B>,
1067 fn next_back(&mut self) -> Option<B> {
1068 for x in self.iter.by_ref().rev() {
1069 if let Some(y) = (self.f)(x) {
1077 #[unstable(feature = "fused", issue = "35602")]
1078 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1079 where F: FnMut(I::Item) -> Option<B> {}
1081 /// An iterator that yields the current count and the element during iteration.
1083 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
1084 /// documentation for more.
1086 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
1087 /// [`Iterator`]: trait.Iterator.html
1088 #[derive(Clone, Debug)]
1089 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub struct Enumerate<I> {
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<I> Iterator for Enumerate<I> where I: Iterator {
1098 type Item = (usize, <I as Iterator>::Item);
1100 /// # Overflow Behavior
1102 /// The method does no guarding against overflows, so enumerating more than
1103 /// `usize::MAX` elements either produces the wrong result or panics. If
1104 /// debug assertions are enabled, a panic is guaranteed.
1108 /// Might panic if the index of the element overflows a `usize`.
1110 #[rustc_inherit_overflow_checks]
1111 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1112 self.iter.next().map(|a| {
1113 let ret = (self.count, a);
1114 // Possible undefined overflow.
1121 fn size_hint(&self) -> (usize, Option<usize>) {
1122 self.iter.size_hint()
1126 #[rustc_inherit_overflow_checks]
1127 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1128 self.iter.nth(n).map(|a| {
1129 let i = self.count + n;
1136 fn count(self) -> usize {
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 impl<I> DoubleEndedIterator for Enumerate<I> where
1143 I: ExactSizeIterator + DoubleEndedIterator
1146 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1147 self.iter.next_back().map(|a| {
1148 let len = self.iter.len();
1149 // Can safely add, `ExactSizeIterator` promises that the number of
1150 // elements fits into a `usize`.
1151 (self.count + len, a)
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1160 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1161 where I: TrustedRandomAccess
1163 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1164 (self.count + i, self.iter.get_unchecked(i))
1168 #[unstable(feature = "fused", issue = "35602")]
1169 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1171 /// An iterator with a `peek()` that returns an optional reference to the next
1174 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
1175 /// documentation for more.
1177 /// [`peekable()`]: trait.Iterator.html#method.peekable
1178 /// [`Iterator`]: trait.Iterator.html
1179 #[derive(Clone, Debug)]
1180 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub struct Peekable<I: Iterator> {
1184 peeked: Option<I::Item>,
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 impl<I: Iterator> Iterator for Peekable<I> {
1189 type Item = I::Item;
1192 fn next(&mut self) -> Option<I::Item> {
1194 Some(_) => self.peeked.take(),
1195 None => self.iter.next(),
1200 #[rustc_inherit_overflow_checks]
1201 fn count(self) -> usize {
1202 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
1206 fn nth(&mut self, n: usize) -> Option<I::Item> {
1208 Some(_) if n == 0 => self.peeked.take(),
1213 None => self.iter.nth(n)
1218 fn last(self) -> Option<I::Item> {
1219 self.iter.last().or(self.peeked)
1223 fn size_hint(&self) -> (usize, Option<usize>) {
1224 let (lo, hi) = self.iter.size_hint();
1225 if self.peeked.is_some() {
1226 let lo = lo.saturating_add(1);
1227 let hi = hi.and_then(|x| x.checked_add(1));
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1238 #[unstable(feature = "fused", issue = "35602")]
1239 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1241 impl<I: Iterator> Peekable<I> {
1242 /// Returns a reference to the next() value without advancing the iterator.
1244 /// Like [`next()`], if there is a value, it is wrapped in a `Some(T)`.
1245 /// But if the iteration is over, `None` is returned.
1247 /// [`next()`]: trait.Iterator.html#tymethod.next
1249 /// Because `peek()` returns a reference, and many iterators iterate over
1250 /// references, there can be a possibly confusing situation where the
1251 /// return value is a double reference. You can see this effect in the
1259 /// let xs = [1, 2, 3];
1261 /// let mut iter = xs.iter().peekable();
1263 /// // peek() lets us see into the future
1264 /// assert_eq!(iter.peek(), Some(&&1));
1265 /// assert_eq!(iter.next(), Some(&1));
1267 /// assert_eq!(iter.next(), Some(&2));
1269 /// // The iterator does not advance even if we `peek` multiple times
1270 /// assert_eq!(iter.peek(), Some(&&3));
1271 /// assert_eq!(iter.peek(), Some(&&3));
1273 /// assert_eq!(iter.next(), Some(&3));
1275 /// // After the iterator is finished, so is `peek()`
1276 /// assert_eq!(iter.peek(), None);
1277 /// assert_eq!(iter.next(), None);
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 pub fn peek(&mut self) -> Option<&I::Item> {
1282 if self.peeked.is_none() {
1283 self.peeked = self.iter.next();
1286 Some(ref value) => Some(value),
1292 /// An iterator that rejects elements while `predicate` is true.
1294 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
1295 /// documentation for more.
1297 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
1298 /// [`Iterator`]: trait.Iterator.html
1299 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1300 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub struct SkipWhile<I, P> {
1308 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1309 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1311 f.debug_struct("SkipWhile")
1312 .field("iter", &self.iter)
1313 .field("flag", &self.flag)
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1320 where P: FnMut(&I::Item) -> bool
1322 type Item = I::Item;
1325 fn next(&mut self) -> Option<I::Item> {
1326 for x in self.iter.by_ref() {
1327 if self.flag || !(self.predicate)(&x) {
1336 fn size_hint(&self) -> (usize, Option<usize>) {
1337 let (_, upper) = self.iter.size_hint();
1338 (0, upper) // can't know a lower bound, due to the predicate
1342 #[unstable(feature = "fused", issue = "35602")]
1343 impl<I, P> FusedIterator for SkipWhile<I, P>
1344 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1346 /// An iterator that only accepts elements while `predicate` is true.
1348 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
1349 /// documentation for more.
1351 /// [`take_while()`]: trait.Iterator.html#method.take_while
1352 /// [`Iterator`]: trait.Iterator.html
1353 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1354 #[stable(feature = "rust1", since = "1.0.0")]
1356 pub struct TakeWhile<I, P> {
1362 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1363 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
1364 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1365 f.debug_struct("TakeWhile")
1366 .field("iter", &self.iter)
1367 .field("flag", &self.flag)
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
1374 where P: FnMut(&I::Item) -> bool
1376 type Item = I::Item;
1379 fn next(&mut self) -> Option<I::Item> {
1383 self.iter.next().and_then(|x| {
1384 if (self.predicate)(&x) {
1395 fn size_hint(&self) -> (usize, Option<usize>) {
1396 let (_, upper) = self.iter.size_hint();
1397 (0, upper) // can't know a lower bound, due to the predicate
1401 #[unstable(feature = "fused", issue = "35602")]
1402 impl<I, P> FusedIterator for TakeWhile<I, P>
1403 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
1405 /// An iterator that skips over `n` elements of `iter`.
1407 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
1408 /// documentation for more.
1410 /// [`skip()`]: trait.Iterator.html#method.skip
1411 /// [`Iterator`]: trait.Iterator.html
1412 #[derive(Clone, Debug)]
1413 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 pub struct Skip<I> {
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<I> Iterator for Skip<I> where I: Iterator {
1422 type Item = <I as Iterator>::Item;
1425 fn next(&mut self) -> Option<I::Item> {
1431 self.iter.nth(old_n)
1436 fn nth(&mut self, n: usize) -> Option<I::Item> {
1437 // Can't just add n + self.n due to overflow.
1441 let to_skip = self.n;
1444 if self.iter.nth(to_skip-1).is_none() {
1452 fn count(self) -> usize {
1453 self.iter.count().saturating_sub(self.n)
1457 fn last(mut self) -> Option<I::Item> {
1461 let next = self.next();
1463 // recurse. n should be 0.
1464 self.last().or(next)
1472 fn size_hint(&self) -> (usize, Option<usize>) {
1473 let (lower, upper) = self.iter.size_hint();
1475 let lower = lower.saturating_sub(self.n);
1476 let upper = upper.map(|x| x.saturating_sub(self.n));
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
1485 #[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
1486 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
1487 fn next_back(&mut self) -> Option<Self::Item> {
1489 self.iter.next_back()
1496 #[unstable(feature = "fused", issue = "35602")]
1497 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
1499 /// An iterator that only iterates over the first `n` iterations of `iter`.
1501 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
1502 /// documentation for more.
1504 /// [`take()`]: trait.Iterator.html#method.take
1505 /// [`Iterator`]: trait.Iterator.html
1506 #[derive(Clone, Debug)]
1507 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub struct Take<I> {
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<I> Iterator for Take<I> where I: Iterator{
1516 type Item = <I as Iterator>::Item;
1519 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1529 fn nth(&mut self, n: usize) -> Option<I::Item> {
1535 self.iter.nth(self.n - 1);
1543 fn size_hint(&self) -> (usize, Option<usize>) {
1544 let (lower, upper) = self.iter.size_hint();
1546 let lower = cmp::min(lower, self.n);
1548 let upper = match upper {
1549 Some(x) if x < self.n => Some(x),
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
1560 #[unstable(feature = "fused", issue = "35602")]
1561 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
1563 /// An iterator to maintain state while iterating another iterator.
1565 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
1566 /// documentation for more.
1568 /// [`scan()`]: trait.Iterator.html#method.scan
1569 /// [`Iterator`]: trait.Iterator.html
1570 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1571 #[stable(feature = "rust1", since = "1.0.0")]
1573 pub struct Scan<I, St, F> {
1579 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1580 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
1581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1582 f.debug_struct("Scan")
1583 .field("iter", &self.iter)
1584 .field("state", &self.state)
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<B, I, St, F> Iterator for Scan<I, St, F> where
1592 F: FnMut(&mut St, I::Item) -> Option<B>,
1597 fn next(&mut self) -> Option<B> {
1598 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1602 fn size_hint(&self) -> (usize, Option<usize>) {
1603 let (_, upper) = self.iter.size_hint();
1604 (0, upper) // can't know a lower bound, due to the scan function
1608 #[unstable(feature = "fused", issue = "35602")]
1609 impl<B, I, St, F> FusedIterator for Scan<I, St, F>
1610 where I: FusedIterator, F: FnMut(&mut St, I::Item) -> Option<B> {}
1612 /// An iterator that maps each element to an iterator, and yields the elements
1613 /// of the produced iterators.
1615 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
1616 /// documentation for more.
1618 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
1619 /// [`Iterator`]: trait.Iterator.html
1620 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1621 #[stable(feature = "rust1", since = "1.0.0")]
1623 pub struct FlatMap<I, U: IntoIterator, F> {
1626 frontiter: Option<U::IntoIter>,
1627 backiter: Option<U::IntoIter>,
1630 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1631 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
1632 where U::IntoIter: fmt::Debug
1634 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1635 f.debug_struct("FlatMap")
1636 .field("iter", &self.iter)
1637 .field("frontiter", &self.frontiter)
1638 .field("backiter", &self.backiter)
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
1645 where F: FnMut(I::Item) -> U,
1647 type Item = U::Item;
1650 fn next(&mut self) -> Option<U::Item> {
1652 if let Some(ref mut inner) = self.frontiter {
1653 if let Some(x) = inner.by_ref().next() {
1657 match self.iter.next().map(&mut self.f) {
1658 None => return self.backiter.as_mut().and_then(|it| it.next()),
1659 next => self.frontiter = next.map(IntoIterator::into_iter),
1665 fn size_hint(&self) -> (usize, Option<usize>) {
1666 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1667 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1668 let lo = flo.saturating_add(blo);
1669 match (self.iter.size_hint(), fhi, bhi) {
1670 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
1678 F: FnMut(I::Item) -> U,
1680 U::IntoIter: DoubleEndedIterator
1683 fn next_back(&mut self) -> Option<U::Item> {
1685 if let Some(ref mut inner) = self.backiter {
1686 if let Some(y) = inner.next_back() {
1690 match self.iter.next_back().map(&mut self.f) {
1691 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1692 next => self.backiter = next.map(IntoIterator::into_iter),
1698 #[unstable(feature = "fused", issue = "35602")]
1699 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
1700 where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
1702 /// An iterator that yields `None` forever after the underlying iterator
1703 /// yields `None` once.
1705 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
1706 /// documentation for more.
1708 /// [`fuse()`]: trait.Iterator.html#method.fuse
1709 /// [`Iterator`]: trait.Iterator.html
1710 #[derive(Clone, Debug)]
1711 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 pub struct Fuse<I> {
1718 #[unstable(feature = "fused", issue = "35602")]
1719 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl<I> Iterator for Fuse<I> where I: Iterator {
1723 type Item = <I as Iterator>::Item;
1726 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
1730 let next = self.iter.next();
1731 self.done = next.is_none();
1737 default fn nth(&mut self, n: usize) -> Option<I::Item> {
1741 let nth = self.iter.nth(n);
1742 self.done = nth.is_none();
1748 default fn last(self) -> Option<I::Item> {
1757 default fn count(self) -> usize {
1766 default fn size_hint(&self) -> (usize, Option<usize>) {
1770 self.iter.size_hint()
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
1778 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1782 let next = self.iter.next_back();
1783 self.done = next.is_none();
1789 unsafe impl<I> TrustedRandomAccess for Fuse<I>
1790 where I: TrustedRandomAccess,
1792 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
1793 self.iter.get_unchecked(i)
1797 #[unstable(feature = "fused", issue = "35602")]
1798 impl<I> Iterator for Fuse<I> where I: FusedIterator {
1800 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1805 fn nth(&mut self, n: usize) -> Option<I::Item> {
1810 fn last(self) -> Option<I::Item> {
1815 fn count(self) -> usize {
1820 fn size_hint(&self) -> (usize, Option<usize>) {
1821 self.iter.size_hint()
1825 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
1826 impl<I> DoubleEndedIterator for Fuse<I>
1827 where I: DoubleEndedIterator + FusedIterator
1830 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
1831 self.iter.next_back()
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
1839 /// An iterator that calls a function with a reference to each element before
1842 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
1843 /// documentation for more.
1845 /// [`inspect()`]: trait.Iterator.html#method.inspect
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 Inspect<I, F> {
1855 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1856 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
1857 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1858 f.debug_struct("Inspect")
1859 .field("iter", &self.iter)
1864 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
1866 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
1867 if let Some(ref a) = elt {
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
1877 type Item = I::Item;
1880 fn next(&mut self) -> Option<I::Item> {
1881 let next = self.iter.next();
1882 self.do_inspect(next)
1886 fn size_hint(&self) -> (usize, Option<usize>) {
1887 self.iter.size_hint()
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
1893 where F: FnMut(&I::Item),
1896 fn next_back(&mut self) -> Option<I::Item> {
1897 let next = self.iter.next_back();
1898 self.do_inspect(next)
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
1904 where F: FnMut(&I::Item) {}
1906 #[unstable(feature = "fused", issue = "35602")]
1907 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
1908 where F: FnMut(&I::Item) {}