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 {
195 //! match iter.next() {
196 //! Some(val) => next = val,
200 //! let () = { println!("{}", x); };
207 //! First, we call `into_iter()` on the value. Then, we match on the iterator
208 //! that returns, calling [`next`] over and over until we see a `None`. At
209 //! that point, we `break` out of the loop, and we're done iterating.
211 //! There's one more subtle bit here: the standard library contains an
212 //! interesting implementation of [`IntoIterator`]:
214 //! ```ignore (only-for-syntax-highlight)
215 //! impl<I: Iterator> IntoIterator for I
218 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
219 //! returning themselves. This means two things:
221 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
222 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
223 //! will allow your collection to be used with the `for` loop.
227 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
228 //! often called 'iterator adapters', as they're a form of the 'adapter
231 //! Common iterator adapters include [`map`], [`take`], and [`filter`].
232 //! For more, see their documentation.
234 //! [`map`]: trait.Iterator.html#method.map
235 //! [`take`]: trait.Iterator.html#method.take
236 //! [`filter`]: trait.Iterator.html#method.filter
240 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
241 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
242 //! until you call [`next`]. This is sometimes a source of confusion when
243 //! creating an iterator solely for its side effects. For example, the [`map`]
244 //! method calls a closure on each element it iterates over:
247 //! # #![allow(unused_must_use)]
248 //! let v = vec![1, 2, 3, 4, 5];
249 //! v.iter().map(|x| println!("{}", x));
252 //! This will not print any values, as we only created an iterator, rather than
253 //! using it. The compiler will warn us about this kind of behavior:
256 //! warning: unused result which must be used: iterator adaptors are lazy and
257 //! do nothing unless consumed
260 //! The idiomatic way to write a [`map`] for its side effects is to use a
261 //! `for` loop instead:
264 //! let v = vec![1, 2, 3, 4, 5];
267 //! println!("{}", x);
271 //! [`map`]: trait.Iterator.html#method.map
273 //! The two most common ways to evaluate an iterator are to use a `for` loop
274 //! like this, or using the [`collect`] method to produce a new collection.
276 //! [`collect`]: trait.Iterator.html#method.collect
280 //! Iterators do not have to be finite. As an example, an open-ended range is
281 //! an infinite iterator:
284 //! let numbers = 0..;
287 //! It is common to use the [`take`] iterator adapter to turn an infinite
288 //! iterator into a finite one:
291 //! let numbers = 0..;
292 //! let five_numbers = numbers.take(5);
294 //! for number in five_numbers {
295 //! println!("{}", number);
299 //! This will print the numbers `0` through `4`, each on their own line.
301 //! Bear in mind that methods on infinite iterators, even those for which a
302 //! result can be determined mathematically in finite time, may not terminate.
303 //! Specifically, methods such as [`min`], which in the general case require
304 //! traversing every element in the iterator, are likely not to return
305 //! successfully for any infinite iterators.
308 //! let ones = std::iter::repeat(1);
309 //! let least = ones.min().unwrap(); // Oh no! An infinite loop!
310 //! // `ones.min()` causes an infinite loop, so we won't reach this point!
311 //! println!("The smallest number one is {}.", least);
314 //! [`take`]: trait.Iterator.html#method.take
315 //! [`min`]: trait.Iterator.html#method.min
317 #![stable(feature = "rust1", since = "1.0.0")]
321 use iter_private::TrustedRandomAccess;
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub use self::iterator::Iterator;
329 #[unstable(feature = "step_trait",
330 reason = "likely to be replaced by finer-grained traits",
332 pub use self::range::Step;
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub use self::sources::{Repeat, repeat};
336 #[unstable(feature = "iterator_repeat_with", issue = "0")]
337 pub use self::sources::{RepeatWith, repeat_with};
338 #[stable(feature = "iter_empty", since = "1.2.0")]
339 pub use self::sources::{Empty, empty};
340 #[stable(feature = "iter_once", since = "1.2.0")]
341 pub use self::sources::{Once, once};
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend};
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub use self::traits::{ExactSizeIterator, Sum, Product};
347 #[unstable(feature = "fused", issue = "35602")]
348 pub use self::traits::FusedIterator;
349 #[unstable(feature = "trusted_len", issue = "37572")]
350 pub use self::traits::TrustedLen;
357 /// Transparent newtype used to implement foo methods in terms of try_foo.
358 /// Important until #43278 is fixed; might be better as `Result<T, !>` later.
359 struct AlwaysOk<T>(pub T);
361 impl<T> Try for AlwaysOk<T> {
365 fn into_result(self) -> Result<Self::Ok, Self::Error> { Ok(self.0) }
367 fn from_error(v: Self::Error) -> Self { v }
369 fn from_ok(v: Self::Ok) -> Self { AlwaysOk(v) }
372 /// Used to make try_fold closures more like normal loops
374 enum LoopState<C, B> {
379 impl<C, B> Try for LoopState<C, B> {
383 fn into_result(self) -> Result<Self::Ok, Self::Error> {
385 LoopState::Continue(y) => Ok(y),
386 LoopState::Break(x) => Err(x),
390 fn from_error(v: Self::Error) -> Self { LoopState::Break(v) }
392 fn from_ok(v: Self::Ok) -> Self { LoopState::Continue(v) }
395 impl<C, B> LoopState<C, B> {
397 fn break_value(self) -> Option<B> {
399 LoopState::Continue(..) => None,
400 LoopState::Break(x) => Some(x),
405 impl<R: Try> LoopState<R::Ok, R> {
407 fn from_try(r: R) -> Self {
408 match Try::into_result(r) {
409 Ok(v) => LoopState::Continue(v),
410 Err(v) => LoopState::Break(Try::from_error(v)),
414 fn into_try(self) -> R {
416 LoopState::Continue(v) => Try::from_ok(v),
417 LoopState::Break(v) => v,
422 /// A double-ended iterator with the direction inverted.
424 /// This `struct` is created by the [`rev`] method on [`Iterator`]. See its
425 /// documentation for more.
427 /// [`rev`]: trait.Iterator.html#method.rev
428 /// [`Iterator`]: trait.Iterator.html
429 #[derive(Clone, Debug)]
430 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
431 #[stable(feature = "rust1", since = "1.0.0")]
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
438 type Item = <I as Iterator>::Item;
441 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
443 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
445 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where
446 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
448 self.iter.try_rfold(init, f)
451 fn fold<Acc, F>(self, init: Acc, f: F) -> Acc
452 where F: FnMut(Acc, Self::Item) -> Acc,
454 self.iter.rfold(init, f)
458 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
459 where P: FnMut(&Self::Item) -> bool
461 self.iter.rfind(predicate)
465 fn rposition<P>(&mut self, predicate: P) -> Option<usize> where
466 P: FnMut(Self::Item) -> bool
468 self.iter.position(predicate)
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
475 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
477 fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R where
478 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
480 self.iter.try_fold(init, f)
483 fn rfold<Acc, F>(self, init: Acc, f: F) -> Acc
484 where F: FnMut(Acc, Self::Item) -> Acc,
486 self.iter.fold(init, f)
489 fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
490 where P: FnMut(&Self::Item) -> bool
492 self.iter.find(predicate)
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl<I> ExactSizeIterator for Rev<I>
498 where I: ExactSizeIterator + DoubleEndedIterator
500 fn len(&self) -> usize {
504 fn is_empty(&self) -> bool {
509 #[unstable(feature = "fused", issue = "35602")]
510 impl<I> FusedIterator for Rev<I>
511 where I: FusedIterator + DoubleEndedIterator {}
513 #[unstable(feature = "trusted_len", issue = "37572")]
514 unsafe impl<I> TrustedLen for Rev<I>
515 where I: TrustedLen + DoubleEndedIterator {}
517 /// An iterator that clones the elements of an underlying iterator.
519 /// This `struct` is created by the [`cloned`] method on [`Iterator`]. See its
520 /// documentation for more.
522 /// [`cloned`]: trait.Iterator.html#method.cloned
523 /// [`Iterator`]: trait.Iterator.html
524 #[stable(feature = "iter_cloned", since = "1.1.0")]
525 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
526 #[derive(Clone, Debug)]
527 pub struct Cloned<I> {
531 #[stable(feature = "iter_cloned", since = "1.1.0")]
532 impl<'a, I, T: 'a> Iterator for Cloned<I>
533 where I: Iterator<Item=&'a T>, T: Clone
537 fn next(&mut self) -> Option<T> {
538 self.it.next().cloned()
541 fn size_hint(&self) -> (usize, Option<usize>) {
545 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
546 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
548 self.it.try_fold(init, move |acc, elt| f(acc, elt.clone()))
551 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
552 where F: FnMut(Acc, Self::Item) -> Acc,
554 self.it.fold(init, move |acc, elt| f(acc, elt.clone()))
558 #[stable(feature = "iter_cloned", since = "1.1.0")]
559 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
560 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
562 fn next_back(&mut self) -> Option<T> {
563 self.it.next_back().cloned()
566 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
567 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
569 self.it.try_rfold(init, move |acc, elt| f(acc, elt.clone()))
572 fn rfold<Acc, F>(self, init: Acc, mut f: F) -> Acc
573 where F: FnMut(Acc, Self::Item) -> Acc,
575 self.it.rfold(init, move |acc, elt| f(acc, elt.clone()))
579 #[stable(feature = "iter_cloned", since = "1.1.0")]
580 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
581 where I: ExactSizeIterator<Item=&'a T>, T: Clone
583 fn len(&self) -> usize {
587 fn is_empty(&self) -> bool {
592 #[unstable(feature = "fused", issue = "35602")]
593 impl<'a, I, T: 'a> FusedIterator for Cloned<I>
594 where I: FusedIterator<Item=&'a T>, T: Clone
598 default unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
599 where I: TrustedRandomAccess<Item=&'a T>, T: Clone
601 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
602 self.it.get_unchecked(i).clone()
606 fn may_have_side_effect() -> bool { true }
610 unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned<I>
611 where I: TrustedRandomAccess<Item=&'a T>, T: Copy
613 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
614 *self.it.get_unchecked(i)
618 fn may_have_side_effect() -> bool { false }
621 #[unstable(feature = "trusted_len", issue = "37572")]
622 unsafe impl<'a, I, T: 'a> TrustedLen for Cloned<I>
623 where I: TrustedLen<Item=&'a T>,
627 /// An iterator that repeats endlessly.
629 /// This `struct` is created by the [`cycle`] method on [`Iterator`]. See its
630 /// documentation for more.
632 /// [`cycle`]: trait.Iterator.html#method.cycle
633 /// [`Iterator`]: trait.Iterator.html
634 #[derive(Clone, Debug)]
635 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub struct Cycle<I> {
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
644 type Item = <I as Iterator>::Item;
647 fn next(&mut self) -> Option<<I as Iterator>::Item> {
648 match self.iter.next() {
649 None => { self.iter = self.orig.clone(); self.iter.next() }
655 fn size_hint(&self) -> (usize, Option<usize>) {
656 // the cycle iterator is either empty or infinite
657 match self.orig.size_hint() {
658 sz @ (0, Some(0)) => sz,
660 _ => (usize::MAX, None)
665 #[unstable(feature = "fused", issue = "35602")]
666 impl<I> FusedIterator for Cycle<I> where I: Clone + Iterator {}
668 /// An iterator for stepping iterators by a custom amount.
670 /// This `struct` is created by the [`step_by`] method on [`Iterator`]. See
671 /// its documentation for more.
673 /// [`step_by`]: trait.Iterator.html#method.step_by
674 /// [`Iterator`]: trait.Iterator.html
675 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
676 #[unstable(feature = "iterator_step_by",
677 reason = "unstable replacement of Range::step_by",
679 #[derive(Clone, Debug)]
680 pub struct StepBy<I> {
686 #[unstable(feature = "iterator_step_by",
687 reason = "unstable replacement of Range::step_by",
689 impl<I> Iterator for StepBy<I> where I: Iterator {
693 fn next(&mut self) -> Option<Self::Item> {
695 self.first_take = false;
698 self.iter.nth(self.step)
703 fn size_hint(&self) -> (usize, Option<usize>) {
704 let inner_hint = self.iter.size_hint();
707 let f = |n| if n == 0 { 0 } else { 1 + (n-1)/(self.step+1) };
708 (f(inner_hint.0), inner_hint.1.map(f))
710 let f = |n| n / (self.step+1);
711 (f(inner_hint.0), inner_hint.1.map(f))
716 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
718 self.first_take = false;
719 let first = self.iter.next();
725 // n and self.step are indices, we need to add 1 to get the amount of elements
726 // When calling `.nth`, we need to subtract 1 again to convert back to an index
727 // step + 1 can't overflow because `.step_by` sets `self.step` to `step - 1`
728 let mut step = self.step + 1;
729 // n + 1 could overflow
730 // thus, if n is usize::MAX, instead of adding one, we call .nth(step)
732 self.iter.nth(step - 1);
739 let mul = n.checked_mul(step);
740 if unsafe { intrinsics::likely(mul.is_some()) } {
741 return self.iter.nth(mul.unwrap() - 1);
743 let div_n = usize::MAX / n;
744 let div_step = usize::MAX / step;
745 let nth_n = div_n * n;
746 let nth_step = div_step * step;
747 let nth = if nth_n > nth_step {
754 self.iter.nth(nth - 1);
759 // StepBy can only make the iterator shorter, so the len will still fit.
760 #[unstable(feature = "iterator_step_by",
761 reason = "unstable replacement of Range::step_by",
763 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
765 /// An iterator that strings two iterators together.
767 /// This `struct` is created by the [`chain`] method on [`Iterator`]. See its
768 /// documentation for more.
770 /// [`chain`]: trait.Iterator.html#method.chain
771 /// [`Iterator`]: trait.Iterator.html
772 #[derive(Clone, Debug)]
773 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
774 #[stable(feature = "rust1", since = "1.0.0")]
775 pub struct Chain<A, B> {
781 // The iterator protocol specifies that iteration ends with the return value
782 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
783 // further calls return. The chain adaptor must account for this since it uses
786 // It uses three states:
788 // - Both: `a` and `b` are remaining
789 // - Front: `a` remaining
790 // - Back: `b` remaining
792 // The fourth state (neither iterator is remaining) only occurs after Chain has
793 // returned None once, so we don't need to store this state.
794 #[derive(Clone, Debug)]
796 // both front and back iterator are remaining
798 // only front is remaining
800 // only back is remaining
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl<A, B> Iterator for Chain<A, B> where
807 B: Iterator<Item = A::Item>
812 fn next(&mut self) -> Option<A::Item> {
814 ChainState::Both => match self.a.next() {
815 elt @ Some(..) => elt,
817 self.state = ChainState::Back;
821 ChainState::Front => self.a.next(),
822 ChainState::Back => self.b.next(),
827 #[rustc_inherit_overflow_checks]
828 fn count(self) -> usize {
830 ChainState::Both => self.a.count() + self.b.count(),
831 ChainState::Front => self.a.count(),
832 ChainState::Back => self.b.count(),
836 fn try_fold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
837 Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
839 let mut accum = init;
841 ChainState::Both | ChainState::Front => {
842 accum = self.a.try_fold(accum, &mut f)?;
843 if let ChainState::Both = self.state {
844 self.state = ChainState::Back;
849 if let ChainState::Back = self.state {
850 accum = self.b.try_fold(accum, &mut f)?;
855 fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
856 where F: FnMut(Acc, Self::Item) -> Acc,
858 let mut accum = init;
860 ChainState::Both | ChainState::Front => {
861 accum = self.a.fold(accum, &mut f);
866 ChainState::Both | ChainState::Back => {
867 accum = self.b.fold(accum, &mut f);
875 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
877 ChainState::Both | ChainState::Front => {
878 for x in self.a.by_ref() {
884 if let ChainState::Both = self.state {
885 self.state = ChainState::Back;
888 ChainState::Back => {}
890 if let ChainState::Back = self.state {
898 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
899 P: FnMut(&Self::Item) -> bool,
902 ChainState::Both => match self.a.find(&mut predicate) {
904 self.state = ChainState::Back;
905 self.b.find(predicate)
909 ChainState::Front => self.a.find(predicate),
910 ChainState::Back => self.b.find(predicate),
915 fn last(self) -> Option<A::Item> {
917 ChainState::Both => {
918 // Must exhaust a before b.
919 let a_last = self.a.last();
920 let b_last = self.b.last();
923 ChainState::Front => self.a.last(),
924 ChainState::Back => self.b.last()
929 fn size_hint(&self) -> (usize, Option<usize>) {
930 let (a_lower, a_upper) = self.a.size_hint();
931 let (b_lower, b_upper) = self.b.size_hint();
933 let lower = a_lower.saturating_add(b_lower);
935 let upper = match (a_upper, b_upper) {
936 (Some(x), Some(y)) => x.checked_add(y),
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl<A, B> DoubleEndedIterator for Chain<A, B> where
946 A: DoubleEndedIterator,
947 B: DoubleEndedIterator<Item=A::Item>,
950 fn next_back(&mut self) -> Option<A::Item> {
952 ChainState::Both => match self.b.next_back() {
953 elt @ Some(..) => elt,
955 self.state = ChainState::Front;
959 ChainState::Front => self.a.next_back(),
960 ChainState::Back => self.b.next_back(),
964 fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
965 Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
967 let mut accum = init;
969 ChainState::Both | ChainState::Back => {
970 accum = self.b.try_rfold(accum, &mut f)?;
971 if let ChainState::Both = self.state {
972 self.state = ChainState::Front;
977 if let ChainState::Front = self.state {
978 accum = self.a.try_rfold(accum, &mut f)?;
983 fn rfold<Acc, F>(self, init: Acc, mut f: F) -> Acc
984 where F: FnMut(Acc, Self::Item) -> Acc,
986 let mut accum = init;
988 ChainState::Both | ChainState::Back => {
989 accum = self.b.rfold(accum, &mut f);
994 ChainState::Both | ChainState::Front => {
995 accum = self.a.rfold(accum, &mut f);
1004 // Note: *both* must be fused to handle double-ended iterators.
1005 #[unstable(feature = "fused", issue = "35602")]
1006 impl<A, B> FusedIterator for Chain<A, B>
1007 where A: FusedIterator,
1008 B: FusedIterator<Item=A::Item>,
1011 #[unstable(feature = "trusted_len", issue = "37572")]
1012 unsafe impl<A, B> TrustedLen for Chain<A, B>
1013 where A: TrustedLen, B: TrustedLen<Item=A::Item>,
1016 /// An iterator that iterates two other iterators simultaneously.
1018 /// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
1019 /// documentation for more.
1021 /// [`zip`]: trait.Iterator.html#method.zip
1022 /// [`Iterator`]: trait.Iterator.html
1023 #[derive(Clone, Debug)]
1024 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub struct Zip<A, B> {
1029 // index and len are only used by the specialized version of zip
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
1037 type Item = (A::Item, B::Item);
1040 fn next(&mut self) -> Option<Self::Item> {
1045 fn size_hint(&self) -> (usize, Option<usize>) {
1046 ZipImpl::size_hint(self)
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<A, B> DoubleEndedIterator for Zip<A, B> where
1052 A: DoubleEndedIterator + ExactSizeIterator,
1053 B: DoubleEndedIterator + ExactSizeIterator,
1056 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
1057 ZipImpl::next_back(self)
1061 // Zip specialization trait
1063 trait ZipImpl<A, B> {
1065 fn new(a: A, b: B) -> Self;
1066 fn next(&mut self) -> Option<Self::Item>;
1067 fn size_hint(&self) -> (usize, Option<usize>);
1068 fn next_back(&mut self) -> Option<Self::Item>
1069 where A: DoubleEndedIterator + ExactSizeIterator,
1070 B: DoubleEndedIterator + ExactSizeIterator;
1075 impl<A, B> ZipImpl<A, B> for Zip<A, B>
1076 where A: Iterator, B: Iterator
1078 type Item = (A::Item, B::Item);
1079 default fn new(a: A, b: B) -> Self {
1089 default fn next(&mut self) -> Option<(A::Item, B::Item)> {
1090 self.a.next().and_then(|x| {
1091 self.b.next().and_then(|y| {
1098 default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
1099 where A: DoubleEndedIterator + ExactSizeIterator,
1100 B: DoubleEndedIterator + ExactSizeIterator
1102 let a_sz = self.a.len();
1103 let b_sz = self.b.len();
1105 // Adjust a, b to equal length
1107 for _ in 0..a_sz - b_sz { self.a.next_back(); }
1109 for _ in 0..b_sz - a_sz { self.b.next_back(); }
1112 match (self.a.next_back(), self.b.next_back()) {
1113 (Some(x), Some(y)) => Some((x, y)),
1114 (None, None) => None,
1115 _ => unreachable!(),
1120 default fn size_hint(&self) -> (usize, Option<usize>) {
1121 let (a_lower, a_upper) = self.a.size_hint();
1122 let (b_lower, b_upper) = self.b.size_hint();
1124 let lower = cmp::min(a_lower, b_lower);
1126 let upper = match (a_upper, b_upper) {
1127 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1128 (Some(x), None) => Some(x),
1129 (None, Some(y)) => Some(y),
1130 (None, None) => None
1138 impl<A, B> ZipImpl<A, B> for Zip<A, B>
1139 where A: TrustedRandomAccess, B: TrustedRandomAccess
1141 fn new(a: A, b: B) -> Self {
1142 let len = cmp::min(a.len(), b.len());
1152 fn next(&mut self) -> Option<(A::Item, B::Item)> {
1153 if self.index < self.len {
1157 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
1159 } else if A::may_have_side_effect() && self.index < self.a.len() {
1160 // match the base implementation's potential side effects
1162 self.a.get_unchecked(self.index);
1172 fn size_hint(&self) -> (usize, Option<usize>) {
1173 let len = self.len - self.index;
1178 fn next_back(&mut self) -> Option<(A::Item, B::Item)>
1179 where A: DoubleEndedIterator + ExactSizeIterator,
1180 B: DoubleEndedIterator + ExactSizeIterator
1182 // Adjust a, b to equal length
1183 if A::may_have_side_effect() {
1184 let sz = self.a.len();
1186 for _ in 0..sz - cmp::max(self.len, self.index) {
1191 if B::may_have_side_effect() {
1192 let sz = self.b.len();
1194 for _ in 0..sz - self.len {
1199 if self.index < self.len {
1203 Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 impl<A, B> ExactSizeIterator for Zip<A, B>
1213 where A: ExactSizeIterator, B: ExactSizeIterator {}
1216 unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
1217 where A: TrustedRandomAccess,
1218 B: TrustedRandomAccess,
1220 unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
1221 (self.a.get_unchecked(i), self.b.get_unchecked(i))
1224 fn may_have_side_effect() -> bool {
1225 A::may_have_side_effect() || B::may_have_side_effect()
1229 #[unstable(feature = "fused", issue = "35602")]
1230 impl<A, B> FusedIterator for Zip<A, B>
1231 where A: FusedIterator, B: FusedIterator, {}
1233 #[unstable(feature = "trusted_len", issue = "37572")]
1234 unsafe impl<A, B> TrustedLen for Zip<A, B>
1235 where A: TrustedLen, B: TrustedLen,
1238 /// An iterator that maps the values of `iter` with `f`.
1240 /// This `struct` is created by the [`map`] method on [`Iterator`]. See its
1241 /// documentation for more.
1243 /// [`map`]: trait.Iterator.html#method.map
1244 /// [`Iterator`]: trait.Iterator.html
1246 /// # Notes about side effects
1248 /// The [`map`] iterator implements [`DoubleEndedIterator`], meaning that
1249 /// you can also [`map`] backwards:
1252 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect();
1254 /// assert_eq!(v, [4, 3, 2]);
1257 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1259 /// But if your closure has state, iterating backwards may act in a way you do
1260 /// not expect. Let's go through an example. First, in the forward direction:
1265 /// for pair in vec!['a', 'b', 'c'].into_iter()
1266 /// .map(|letter| { c += 1; (letter, c) }) {
1267 /// println!("{:?}", pair);
1271 /// This will print "('a', 1), ('b', 2), ('c', 3)".
1273 /// Now consider this twist where we add a call to `rev`. This version will
1274 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
1275 /// but the values of the counter still go in order. This is because `map()` is
1276 /// still being called lazily on each item, but we are popping items off the
1277 /// back of the vector now, instead of shifting them from the front.
1282 /// for pair in vec!['a', 'b', 'c'].into_iter()
1283 /// .map(|letter| { c += 1; (letter, c) })
1285 /// println!("{:?}", pair);
1288 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1289 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub struct Map<I, F> {
1296 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1297 impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
1298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1299 f.debug_struct("Map")
1300 .field("iter", &self.iter)
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
1310 fn next(&mut self) -> Option<B> {
1311 self.iter.next().map(&mut self.f)
1315 fn size_hint(&self) -> (usize, Option<usize>) {
1316 self.iter.size_hint()
1319 fn try_fold<Acc, G, R>(&mut self, init: Acc, mut g: G) -> R where
1320 Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1322 let f = &mut self.f;
1323 self.iter.try_fold(init, move |acc, elt| g(acc, f(elt)))
1326 fn fold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1327 where G: FnMut(Acc, Self::Item) -> Acc,
1330 self.iter.fold(init, move |acc, elt| g(acc, f(elt)))
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
1336 F: FnMut(I::Item) -> B,
1339 fn next_back(&mut self) -> Option<B> {
1340 self.iter.next_back().map(&mut self.f)
1343 fn try_rfold<Acc, G, R>(&mut self, init: Acc, mut g: G) -> R where
1344 Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1346 let f = &mut self.f;
1347 self.iter.try_rfold(init, move |acc, elt| g(acc, f(elt)))
1350 fn rfold<Acc, G>(self, init: Acc, mut g: G) -> Acc
1351 where G: FnMut(Acc, Self::Item) -> Acc,
1354 self.iter.rfold(init, move |acc, elt| g(acc, f(elt)))
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
1360 where F: FnMut(I::Item) -> B
1362 fn len(&self) -> usize {
1366 fn is_empty(&self) -> bool {
1367 self.iter.is_empty()
1371 #[unstable(feature = "fused", issue = "35602")]
1372 impl<B, I: FusedIterator, F> FusedIterator for Map<I, F>
1373 where F: FnMut(I::Item) -> B {}
1375 #[unstable(feature = "trusted_len", issue = "37572")]
1376 unsafe impl<B, I, F> TrustedLen for Map<I, F>
1377 where I: TrustedLen,
1378 F: FnMut(I::Item) -> B {}
1381 unsafe impl<B, I, F> TrustedRandomAccess for Map<I, F>
1382 where I: TrustedRandomAccess,
1383 F: FnMut(I::Item) -> B,
1385 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
1386 (self.f)(self.iter.get_unchecked(i))
1389 fn may_have_side_effect() -> bool { true }
1392 /// An iterator that filters the elements of `iter` with `predicate`.
1394 /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its
1395 /// documentation for more.
1397 /// [`filter`]: trait.Iterator.html#method.filter
1398 /// [`Iterator`]: trait.Iterator.html
1399 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1400 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub struct Filter<I, P> {
1407 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1408 impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
1409 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1410 f.debug_struct("Filter")
1411 .field("iter", &self.iter)
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
1418 type Item = I::Item;
1421 fn next(&mut self) -> Option<I::Item> {
1422 for x in &mut self.iter {
1423 if (self.predicate)(&x) {
1431 fn size_hint(&self) -> (usize, Option<usize>) {
1432 let (_, upper) = self.iter.size_hint();
1433 (0, upper) // can't know a lower bound, due to the predicate
1436 // this special case allows the compiler to make `.filter(_).count()`
1437 // branchless. Barring perfect branch prediction (which is unattainable in
1438 // the general case), this will be much faster in >90% of cases (containing
1439 // virtually all real workloads) and only a tiny bit slower in the rest.
1441 // Having this specialization thus allows us to write `.filter(p).count()`
1442 // where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
1443 // less readable and also less backwards-compatible to Rust before 1.10.
1445 // Using the branchless version will also simplify the LLVM byte code, thus
1446 // leaving more budget for LLVM optimizations.
1448 fn count(mut self) -> usize {
1450 for x in &mut self.iter {
1451 count += (self.predicate)(&x) as usize;
1457 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1458 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1460 let predicate = &mut self.predicate;
1461 self.iter.try_fold(init, move |acc, item| if predicate(&item) {
1469 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1470 where Fold: FnMut(Acc, Self::Item) -> Acc,
1472 let mut predicate = self.predicate;
1473 self.iter.fold(init, move |acc, item| if predicate(&item) {
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
1483 where P: FnMut(&I::Item) -> bool,
1486 fn next_back(&mut self) -> Option<I::Item> {
1487 for x in self.iter.by_ref().rev() {
1488 if (self.predicate)(&x) {
1496 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1497 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1499 let predicate = &mut self.predicate;
1500 self.iter.try_rfold(init, move |acc, item| if predicate(&item) {
1508 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1509 where Fold: FnMut(Acc, Self::Item) -> Acc,
1511 let mut predicate = self.predicate;
1512 self.iter.rfold(init, move |acc, item| if predicate(&item) {
1520 #[unstable(feature = "fused", issue = "35602")]
1521 impl<I: FusedIterator, P> FusedIterator for Filter<I, P>
1522 where P: FnMut(&I::Item) -> bool {}
1524 /// An iterator that uses `f` to both filter and map elements from `iter`.
1526 /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its
1527 /// documentation for more.
1529 /// [`filter_map`]: trait.Iterator.html#method.filter_map
1530 /// [`Iterator`]: trait.Iterator.html
1531 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1532 #[stable(feature = "rust1", since = "1.0.0")]
1534 pub struct FilterMap<I, F> {
1539 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1540 impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
1541 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1542 f.debug_struct("FilterMap")
1543 .field("iter", &self.iter)
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
1550 where F: FnMut(I::Item) -> Option<B>,
1555 fn next(&mut self) -> Option<B> {
1556 for x in self.iter.by_ref() {
1557 if let Some(y) = (self.f)(x) {
1565 fn size_hint(&self) -> (usize, Option<usize>) {
1566 let (_, upper) = self.iter.size_hint();
1567 (0, upper) // can't know a lower bound, due to the predicate
1571 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1572 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1574 let f = &mut self.f;
1575 self.iter.try_fold(init, move |acc, item| match f(item) {
1576 Some(x) => fold(acc, x),
1577 None => Try::from_ok(acc),
1582 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1583 where Fold: FnMut(Acc, Self::Item) -> Acc,
1586 self.iter.fold(init, move |acc, item| match f(item) {
1587 Some(x) => fold(acc, x),
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
1595 where F: FnMut(I::Item) -> Option<B>,
1598 fn next_back(&mut self) -> Option<B> {
1599 for x in self.iter.by_ref().rev() {
1600 if let Some(y) = (self.f)(x) {
1608 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1609 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1611 let f = &mut self.f;
1612 self.iter.try_rfold(init, move |acc, item| match f(item) {
1613 Some(x) => fold(acc, x),
1614 None => Try::from_ok(acc),
1619 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1620 where Fold: FnMut(Acc, Self::Item) -> Acc,
1623 self.iter.rfold(init, move |acc, item| match f(item) {
1624 Some(x) => fold(acc, x),
1630 #[unstable(feature = "fused", issue = "35602")]
1631 impl<B, I: FusedIterator, F> FusedIterator for FilterMap<I, F>
1632 where F: FnMut(I::Item) -> Option<B> {}
1634 /// An iterator that yields the current count and the element during iteration.
1636 /// This `struct` is created by the [`enumerate`] method on [`Iterator`]. See its
1637 /// documentation for more.
1639 /// [`enumerate`]: trait.Iterator.html#method.enumerate
1640 /// [`Iterator`]: trait.Iterator.html
1641 #[derive(Clone, Debug)]
1642 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 pub struct Enumerate<I> {
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 impl<I> Iterator for Enumerate<I> where I: Iterator {
1651 type Item = (usize, <I as Iterator>::Item);
1653 /// # Overflow Behavior
1655 /// The method does no guarding against overflows, so enumerating more than
1656 /// `usize::MAX` elements either produces the wrong result or panics. If
1657 /// debug assertions are enabled, a panic is guaranteed.
1661 /// Might panic if the index of the element overflows a `usize`.
1663 #[rustc_inherit_overflow_checks]
1664 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1665 self.iter.next().map(|a| {
1666 let ret = (self.count, a);
1667 // Possible undefined overflow.
1674 fn size_hint(&self) -> (usize, Option<usize>) {
1675 self.iter.size_hint()
1679 #[rustc_inherit_overflow_checks]
1680 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
1681 self.iter.nth(n).map(|a| {
1682 let i = self.count + n;
1689 fn count(self) -> usize {
1694 #[rustc_inherit_overflow_checks]
1695 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1696 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1698 let count = &mut self.count;
1699 self.iter.try_fold(init, move |acc, item| {
1700 let acc = fold(acc, (*count, item));
1707 #[rustc_inherit_overflow_checks]
1708 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1709 where Fold: FnMut(Acc, Self::Item) -> Acc,
1711 let mut count = self.count;
1712 self.iter.fold(init, move |acc, item| {
1713 let acc = fold(acc, (count, item));
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 impl<I> DoubleEndedIterator for Enumerate<I> where
1722 I: ExactSizeIterator + DoubleEndedIterator
1725 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1726 self.iter.next_back().map(|a| {
1727 let len = self.iter.len();
1728 // Can safely add, `ExactSizeIterator` promises that the number of
1729 // elements fits into a `usize`.
1730 (self.count + len, a)
1735 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
1736 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
1738 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1739 // that the number of elements fits into a `usize`.
1740 let mut count = self.count + self.iter.len();
1741 self.iter.try_rfold(init, move |acc, item| {
1743 fold(acc, (count, item))
1748 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1749 where Fold: FnMut(Acc, Self::Item) -> Acc,
1751 // Can safely add and subtract the count, as `ExactSizeIterator` promises
1752 // that the number of elements fits into a `usize`.
1753 let mut count = self.count + self.iter.len();
1754 self.iter.rfold(init, move |acc, item| {
1756 fold(acc, (count, item))
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {
1763 fn len(&self) -> usize {
1767 fn is_empty(&self) -> bool {
1768 self.iter.is_empty()
1773 unsafe impl<I> TrustedRandomAccess for Enumerate<I>
1774 where I: TrustedRandomAccess
1776 unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) {
1777 (self.count + i, self.iter.get_unchecked(i))
1780 fn may_have_side_effect() -> bool {
1781 I::may_have_side_effect()
1785 #[unstable(feature = "fused", issue = "35602")]
1786 impl<I> FusedIterator for Enumerate<I> where I: FusedIterator {}
1788 #[unstable(feature = "trusted_len", issue = "37572")]
1789 unsafe impl<I> TrustedLen for Enumerate<I>
1790 where I: TrustedLen,
1794 /// An iterator with a `peek()` that returns an optional reference to the next
1797 /// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
1798 /// documentation for more.
1800 /// [`peekable`]: trait.Iterator.html#method.peekable
1801 /// [`Iterator`]: trait.Iterator.html
1802 #[derive(Clone, Debug)]
1803 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 pub struct Peekable<I: Iterator> {
1807 /// Remember a peeked value, even if it was None.
1808 peeked: Option<Option<I::Item>>,
1811 // Peekable must remember if a None has been seen in the `.peek()` method.
1812 // It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
1813 // underlying iterator at most once. This does not by itself make the iterator
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<I: Iterator> Iterator for Peekable<I> {
1817 type Item = I::Item;
1820 fn next(&mut self) -> Option<I::Item> {
1821 match self.peeked.take() {
1823 None => self.iter.next(),
1828 #[rustc_inherit_overflow_checks]
1829 fn count(mut self) -> usize {
1830 match self.peeked.take() {
1832 Some(Some(_)) => 1 + self.iter.count(),
1833 None => self.iter.count(),
1838 fn nth(&mut self, n: usize) -> Option<I::Item> {
1839 // FIXME(#6393): merge these when borrow-checking gets better.
1841 match self.peeked.take() {
1843 None => self.iter.nth(n),
1846 match self.peeked.take() {
1848 Some(Some(_)) => self.iter.nth(n - 1),
1849 None => self.iter.nth(n),
1855 fn last(mut self) -> Option<I::Item> {
1856 let peek_opt = match self.peeked.take() {
1857 Some(None) => return None,
1861 self.iter.last().or(peek_opt)
1865 fn size_hint(&self) -> (usize, Option<usize>) {
1866 let peek_len = match self.peeked {
1867 Some(None) => return (0, Some(0)),
1871 let (lo, hi) = self.iter.size_hint();
1872 let lo = lo.saturating_add(peek_len);
1873 let hi = hi.and_then(|x| x.checked_add(peek_len));
1878 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1879 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1881 let acc = match self.peeked.take() {
1882 Some(None) => return Try::from_ok(init),
1883 Some(Some(v)) => f(init, v)?,
1886 self.iter.try_fold(acc, f)
1890 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1891 where Fold: FnMut(Acc, Self::Item) -> Acc,
1893 let acc = match self.peeked {
1894 Some(None) => return init,
1895 Some(Some(v)) => fold(init, v),
1898 self.iter.fold(acc, fold)
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
1905 #[unstable(feature = "fused", issue = "35602")]
1906 impl<I: FusedIterator> FusedIterator for Peekable<I> {}
1908 impl<I: Iterator> Peekable<I> {
1909 /// Returns a reference to the next() value without advancing the iterator.
1911 /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
1912 /// But if the iteration is over, `None` is returned.
1914 /// [`next`]: trait.Iterator.html#tymethod.next
1916 /// Because `peek()` returns a reference, and many iterators iterate over
1917 /// references, there can be a possibly confusing situation where the
1918 /// return value is a double reference. You can see this effect in the
1926 /// let xs = [1, 2, 3];
1928 /// let mut iter = xs.iter().peekable();
1930 /// // peek() lets us see into the future
1931 /// assert_eq!(iter.peek(), Some(&&1));
1932 /// assert_eq!(iter.next(), Some(&1));
1934 /// assert_eq!(iter.next(), Some(&2));
1936 /// // The iterator does not advance even if we `peek` multiple times
1937 /// assert_eq!(iter.peek(), Some(&&3));
1938 /// assert_eq!(iter.peek(), Some(&&3));
1940 /// assert_eq!(iter.next(), Some(&3));
1942 /// // After the iterator is finished, so is `peek()`
1943 /// assert_eq!(iter.peek(), None);
1944 /// assert_eq!(iter.next(), None);
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 pub fn peek(&mut self) -> Option<&I::Item> {
1949 if self.peeked.is_none() {
1950 self.peeked = Some(self.iter.next());
1953 Some(Some(ref value)) => Some(value),
1955 _ => unreachable!(),
1960 /// An iterator that rejects elements while `predicate` is true.
1962 /// This `struct` is created by the [`skip_while`] method on [`Iterator`]. See its
1963 /// documentation for more.
1965 /// [`skip_while`]: trait.Iterator.html#method.skip_while
1966 /// [`Iterator`]: trait.Iterator.html
1967 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1968 #[stable(feature = "rust1", since = "1.0.0")]
1970 pub struct SkipWhile<I, P> {
1976 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1977 impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
1978 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1979 f.debug_struct("SkipWhile")
1980 .field("iter", &self.iter)
1981 .field("flag", &self.flag)
1986 #[stable(feature = "rust1", since = "1.0.0")]
1987 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
1988 where P: FnMut(&I::Item) -> bool
1990 type Item = I::Item;
1993 fn next(&mut self) -> Option<I::Item> {
1994 let flag = &mut self.flag;
1995 let pred = &mut self.predicate;
1996 self.iter.find(move |x| {
1997 if *flag || !pred(x) {
2007 fn size_hint(&self) -> (usize, Option<usize>) {
2008 let (_, upper) = self.iter.size_hint();
2009 (0, upper) // can't know a lower bound, due to the predicate
2013 fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
2014 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2018 Some(v) => init = fold(init, v)?,
2019 None => return Try::from_ok(init),
2022 self.iter.try_fold(init, fold)
2026 fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
2027 where Fold: FnMut(Acc, Self::Item) -> Acc,
2031 Some(v) => init = fold(init, v),
2032 None => return init,
2035 self.iter.fold(init, fold)
2039 #[unstable(feature = "fused", issue = "35602")]
2040 impl<I, P> FusedIterator for SkipWhile<I, P>
2041 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
2043 /// An iterator that only accepts elements while `predicate` is true.
2045 /// This `struct` is created by the [`take_while`] method on [`Iterator`]. See its
2046 /// documentation for more.
2048 /// [`take_while`]: trait.Iterator.html#method.take_while
2049 /// [`Iterator`]: trait.Iterator.html
2050 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2051 #[stable(feature = "rust1", since = "1.0.0")]
2053 pub struct TakeWhile<I, P> {
2059 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2060 impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
2061 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2062 f.debug_struct("TakeWhile")
2063 .field("iter", &self.iter)
2064 .field("flag", &self.flag)
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
2071 where P: FnMut(&I::Item) -> bool
2073 type Item = I::Item;
2076 fn next(&mut self) -> Option<I::Item> {
2080 self.iter.next().and_then(|x| {
2081 if (self.predicate)(&x) {
2092 fn size_hint(&self) -> (usize, Option<usize>) {
2093 let (_, upper) = self.iter.size_hint();
2094 (0, upper) // can't know a lower bound, due to the predicate
2098 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2099 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2104 let flag = &mut self.flag;
2105 let p = &mut self.predicate;
2106 self.iter.try_fold(init, move |acc, x|{
2108 LoopState::from_try(fold(acc, x))
2111 LoopState::Break(Try::from_ok(acc))
2118 #[unstable(feature = "fused", issue = "35602")]
2119 impl<I, P> FusedIterator for TakeWhile<I, P>
2120 where I: FusedIterator, P: FnMut(&I::Item) -> bool {}
2122 /// An iterator that skips over `n` elements of `iter`.
2124 /// This `struct` is created by the [`skip`] method on [`Iterator`]. See its
2125 /// documentation for more.
2127 /// [`skip`]: trait.Iterator.html#method.skip
2128 /// [`Iterator`]: trait.Iterator.html
2129 #[derive(Clone, Debug)]
2130 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 pub struct Skip<I> {
2137 #[stable(feature = "rust1", since = "1.0.0")]
2138 impl<I> Iterator for Skip<I> where I: Iterator {
2139 type Item = <I as Iterator>::Item;
2142 fn next(&mut self) -> Option<I::Item> {
2148 self.iter.nth(old_n)
2153 fn nth(&mut self, n: usize) -> Option<I::Item> {
2154 // Can't just add n + self.n due to overflow.
2158 let to_skip = self.n;
2161 if self.iter.nth(to_skip-1).is_none() {
2169 fn count(self) -> usize {
2170 self.iter.count().saturating_sub(self.n)
2174 fn last(mut self) -> Option<I::Item> {
2178 let next = self.next();
2180 // recurse. n should be 0.
2181 self.last().or(next)
2189 fn size_hint(&self) -> (usize, Option<usize>) {
2190 let (lower, upper) = self.iter.size_hint();
2192 let lower = lower.saturating_sub(self.n);
2193 let upper = upper.map(|x| x.saturating_sub(self.n));
2199 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2200 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2206 if self.iter.nth(n - 1).is_none() {
2207 return Try::from_ok(init);
2210 self.iter.try_fold(init, fold)
2214 fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2215 where Fold: FnMut(Acc, Self::Item) -> Acc,
2219 if self.iter.nth(self.n - 1).is_none() {
2223 self.iter.fold(init, fold)
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2230 #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")]
2231 impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
2232 fn next_back(&mut self) -> Option<Self::Item> {
2234 self.iter.next_back()
2240 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2241 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2243 let mut n = self.len();
2247 self.iter.try_rfold(init, move |acc, x| {
2249 let r = fold(acc, x);
2250 if n == 0 { LoopState::Break(r) }
2251 else { LoopState::from_try(r) }
2257 #[unstable(feature = "fused", issue = "35602")]
2258 impl<I> FusedIterator for Skip<I> where I: FusedIterator {}
2260 /// An iterator that only iterates over the first `n` iterations of `iter`.
2262 /// This `struct` is created by the [`take`] method on [`Iterator`]. See its
2263 /// documentation for more.
2265 /// [`take`]: trait.Iterator.html#method.take
2266 /// [`Iterator`]: trait.Iterator.html
2267 #[derive(Clone, Debug)]
2268 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 pub struct Take<I> {
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 impl<I> Iterator for Take<I> where I: Iterator{
2277 type Item = <I as Iterator>::Item;
2280 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2290 fn nth(&mut self, n: usize) -> Option<I::Item> {
2296 self.iter.nth(self.n - 1);
2304 fn size_hint(&self) -> (usize, Option<usize>) {
2305 let (lower, upper) = self.iter.size_hint();
2307 let lower = cmp::min(lower, self.n);
2309 let upper = match upper {
2310 Some(x) if x < self.n => Some(x),
2318 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2319 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2324 let n = &mut self.n;
2325 self.iter.try_fold(init, move |acc, x| {
2327 let r = fold(acc, x);
2328 if *n == 0 { LoopState::Break(r) }
2329 else { LoopState::from_try(r) }
2335 #[stable(feature = "rust1", since = "1.0.0")]
2336 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2338 #[unstable(feature = "fused", issue = "35602")]
2339 impl<I> FusedIterator for Take<I> where I: FusedIterator {}
2341 #[unstable(feature = "trusted_len", issue = "37572")]
2342 unsafe impl<I: TrustedLen> TrustedLen for Take<I> {}
2344 /// An iterator to maintain state while iterating another iterator.
2346 /// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
2347 /// documentation for more.
2349 /// [`scan`]: trait.Iterator.html#method.scan
2350 /// [`Iterator`]: trait.Iterator.html
2351 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2352 #[stable(feature = "rust1", since = "1.0.0")]
2354 pub struct Scan<I, St, F> {
2360 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2361 impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
2362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2363 f.debug_struct("Scan")
2364 .field("iter", &self.iter)
2365 .field("state", &self.state)
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 impl<B, I, St, F> Iterator for Scan<I, St, F> where
2373 F: FnMut(&mut St, I::Item) -> Option<B>,
2378 fn next(&mut self) -> Option<B> {
2379 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2383 fn size_hint(&self) -> (usize, Option<usize>) {
2384 let (_, upper) = self.iter.size_hint();
2385 (0, upper) // can't know a lower bound, due to the scan function
2389 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2390 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2392 let state = &mut self.state;
2393 let f = &mut self.f;
2394 self.iter.try_fold(init, move |acc, x| {
2396 None => LoopState::Break(Try::from_ok(acc)),
2397 Some(x) => LoopState::from_try(fold(acc, x)),
2403 /// An iterator that maps each element to an iterator, and yields the elements
2404 /// of the produced iterators.
2406 /// This `struct` is created by the [`flat_map`] method on [`Iterator`]. See its
2407 /// documentation for more.
2409 /// [`flat_map`]: trait.Iterator.html#method.flat_map
2410 /// [`Iterator`]: trait.Iterator.html
2411 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2412 #[stable(feature = "rust1", since = "1.0.0")]
2414 pub struct FlatMap<I, U: IntoIterator, F> {
2417 frontiter: Option<U::IntoIter>,
2418 backiter: Option<U::IntoIter>,
2421 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2422 impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
2423 where U::IntoIter: fmt::Debug
2425 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2426 f.debug_struct("FlatMap")
2427 .field("iter", &self.iter)
2428 .field("frontiter", &self.frontiter)
2429 .field("backiter", &self.backiter)
2434 #[stable(feature = "rust1", since = "1.0.0")]
2435 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
2436 where F: FnMut(I::Item) -> U,
2438 type Item = U::Item;
2441 fn next(&mut self) -> Option<U::Item> {
2443 if let Some(ref mut inner) = self.frontiter {
2444 if let Some(x) = inner.by_ref().next() {
2448 match self.iter.next().map(&mut self.f) {
2449 None => return self.backiter.as_mut().and_then(|it| it.next()),
2450 next => self.frontiter = next.map(IntoIterator::into_iter),
2456 fn size_hint(&self) -> (usize, Option<usize>) {
2457 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2458 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2459 let lo = flo.saturating_add(blo);
2460 match (self.iter.size_hint(), fhi, bhi) {
2461 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2467 fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
2468 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2470 if let Some(ref mut front) = self.frontiter {
2471 init = front.try_fold(init, &mut fold)?;
2473 self.frontiter = None;
2476 let f = &mut self.f;
2477 let frontiter = &mut self.frontiter;
2478 init = self.iter.try_fold(init, |acc, x| {
2479 let mut mid = f(x).into_iter();
2480 let r = mid.try_fold(acc, &mut fold);
2481 *frontiter = Some(mid);
2485 self.frontiter = None;
2487 if let Some(ref mut back) = self.backiter {
2488 init = back.try_fold(init, &mut fold)?;
2490 self.backiter = None;
2496 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
2497 where Fold: FnMut(Acc, Self::Item) -> Acc,
2499 self.frontiter.into_iter()
2500 .chain(self.iter.map(self.f).map(U::into_iter))
2501 .chain(self.backiter)
2502 .fold(init, |acc, iter| iter.fold(acc, &mut fold))
2506 #[stable(feature = "rust1", since = "1.0.0")]
2507 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
2508 F: FnMut(I::Item) -> U,
2510 U::IntoIter: DoubleEndedIterator
2513 fn next_back(&mut self) -> Option<U::Item> {
2515 if let Some(ref mut inner) = self.backiter {
2516 if let Some(y) = inner.next_back() {
2520 match self.iter.next_back().map(&mut self.f) {
2521 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2522 next => self.backiter = next.map(IntoIterator::into_iter),
2528 fn try_rfold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
2529 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2531 if let Some(ref mut back) = self.backiter {
2532 init = back.try_rfold(init, &mut fold)?;
2534 self.backiter = None;
2537 let f = &mut self.f;
2538 let backiter = &mut self.backiter;
2539 init = self.iter.try_rfold(init, |acc, x| {
2540 let mut mid = f(x).into_iter();
2541 let r = mid.try_rfold(acc, &mut fold);
2542 *backiter = Some(mid);
2546 self.backiter = None;
2548 if let Some(ref mut front) = self.frontiter {
2549 init = front.try_rfold(init, &mut fold)?;
2551 self.frontiter = None;
2557 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
2558 where Fold: FnMut(Acc, Self::Item) -> Acc,
2560 self.frontiter.into_iter()
2561 .chain(self.iter.map(self.f).map(U::into_iter))
2562 .chain(self.backiter)
2563 .rfold(init, |acc, iter| iter.rfold(acc, &mut fold))
2567 #[unstable(feature = "fused", issue = "35602")]
2568 impl<I, U, F> FusedIterator for FlatMap<I, U, F>
2569 where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
2571 /// An iterator that yields `None` forever after the underlying iterator
2572 /// yields `None` once.
2574 /// This `struct` is created by the [`fuse`] method on [`Iterator`]. See its
2575 /// documentation for more.
2577 /// [`fuse`]: trait.Iterator.html#method.fuse
2578 /// [`Iterator`]: trait.Iterator.html
2579 #[derive(Clone, Debug)]
2580 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2581 #[stable(feature = "rust1", since = "1.0.0")]
2582 pub struct Fuse<I> {
2587 #[unstable(feature = "fused", issue = "35602")]
2588 impl<I> FusedIterator for Fuse<I> where I: Iterator {}
2590 #[stable(feature = "rust1", since = "1.0.0")]
2591 impl<I> Iterator for Fuse<I> where I: Iterator {
2592 type Item = <I as Iterator>::Item;
2595 default fn next(&mut self) -> Option<<I as Iterator>::Item> {
2599 let next = self.iter.next();
2600 self.done = next.is_none();
2606 default fn nth(&mut self, n: usize) -> Option<I::Item> {
2610 let nth = self.iter.nth(n);
2611 self.done = nth.is_none();
2617 default fn last(self) -> Option<I::Item> {
2626 default fn count(self) -> usize {
2635 default fn size_hint(&self) -> (usize, Option<usize>) {
2639 self.iter.size_hint()
2644 default fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2645 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2650 let acc = self.iter.try_fold(init, fold)?;
2657 default fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2658 where Fold: FnMut(Acc, Self::Item) -> Acc,
2663 self.iter.fold(init, fold)
2668 #[stable(feature = "rust1", since = "1.0.0")]
2669 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2671 default fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2675 let next = self.iter.next_back();
2676 self.done = next.is_none();
2682 default fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2683 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2688 let acc = self.iter.try_rfold(init, fold)?;
2695 default fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2696 where Fold: FnMut(Acc, Self::Item) -> Acc,
2701 self.iter.rfold(init, fold)
2706 unsafe impl<I> TrustedRandomAccess for Fuse<I>
2707 where I: TrustedRandomAccess,
2709 unsafe fn get_unchecked(&mut self, i: usize) -> I::Item {
2710 self.iter.get_unchecked(i)
2713 fn may_have_side_effect() -> bool {
2714 I::may_have_side_effect()
2718 #[unstable(feature = "fused", issue = "35602")]
2719 impl<I> Iterator for Fuse<I> where I: FusedIterator {
2721 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2726 fn nth(&mut self, n: usize) -> Option<I::Item> {
2731 fn last(self) -> Option<I::Item> {
2736 fn count(self) -> usize {
2741 fn size_hint(&self) -> (usize, Option<usize>) {
2742 self.iter.size_hint()
2746 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2747 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2749 self.iter.try_fold(init, fold)
2753 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2754 where Fold: FnMut(Acc, Self::Item) -> Acc,
2756 self.iter.fold(init, fold)
2760 #[unstable(feature = "fused", reason = "recently added", issue = "35602")]
2761 impl<I> DoubleEndedIterator for Fuse<I>
2762 where I: DoubleEndedIterator + FusedIterator
2765 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2766 self.iter.next_back()
2770 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
2771 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2773 self.iter.try_rfold(init, fold)
2777 fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
2778 where Fold: FnMut(Acc, Self::Item) -> Acc,
2780 self.iter.rfold(init, fold)
2785 #[stable(feature = "rust1", since = "1.0.0")]
2786 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {
2787 fn len(&self) -> usize {
2791 fn is_empty(&self) -> bool {
2792 self.iter.is_empty()
2796 /// An iterator that calls a function with a reference to each element before
2799 /// This `struct` is created by the [`inspect`] method on [`Iterator`]. See its
2800 /// documentation for more.
2802 /// [`inspect`]: trait.Iterator.html#method.inspect
2803 /// [`Iterator`]: trait.Iterator.html
2804 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2805 #[stable(feature = "rust1", since = "1.0.0")]
2807 pub struct Inspect<I, F> {
2812 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2813 impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
2814 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2815 f.debug_struct("Inspect")
2816 .field("iter", &self.iter)
2821 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
2823 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
2824 if let Some(ref a) = elt {
2832 #[stable(feature = "rust1", since = "1.0.0")]
2833 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
2834 type Item = I::Item;
2837 fn next(&mut self) -> Option<I::Item> {
2838 let next = self.iter.next();
2839 self.do_inspect(next)
2843 fn size_hint(&self) -> (usize, Option<usize>) {
2844 self.iter.size_hint()
2848 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2849 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2851 let f = &mut self.f;
2852 self.iter.try_fold(init, move |acc, item| { f(&item); fold(acc, item) })
2856 fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
2857 where Fold: FnMut(Acc, Self::Item) -> Acc,
2860 self.iter.fold(init, move |acc, item| { f(&item); fold(acc, item) })
2864 #[stable(feature = "rust1", since = "1.0.0")]
2865 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
2866 where F: FnMut(&I::Item),
2869 fn next_back(&mut self) -> Option<I::Item> {
2870 let next = self.iter.next_back();
2871 self.do_inspect(next)
2875 fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, mut fold: Fold) -> R where
2876 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
2878 let f = &mut self.f;
2879 self.iter.try_rfold(init, move |acc, item| { f(&item); fold(acc, item) })
2883 fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
2884 where Fold: FnMut(Acc, Self::Item) -> Acc,
2887 self.iter.rfold(init, move |acc, item| { f(&item); fold(acc, item) })
2891 #[stable(feature = "rust1", since = "1.0.0")]
2892 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
2893 where F: FnMut(&I::Item)
2895 fn len(&self) -> usize {
2899 fn is_empty(&self) -> bool {
2900 self.iter.is_empty()
2904 #[unstable(feature = "fused", issue = "35602")]
2905 impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
2906 where F: FnMut(&I::Item) {}