1 // Copyright 2013-2014 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`]: ../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 values.into_iter() {
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 cmp::{Ord, PartialOrd, PartialEq, Ordering};
305 use default::Default;
308 use num::{Zero, One};
309 use ops::{self, Add, Sub, FnMut, Mul};
310 use option::Option::{self, Some, None};
314 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
316 /// An interface for dealing with iterators.
318 /// This is the main iterator trait. For more about the concept of iterators
319 /// generally, please see the [module-level documentation]. In particular, you
320 /// may want to know how to [implement `Iterator`][impl].
322 /// [module-level documentation]: index.html
323 /// [impl]: index.html#implementing-iterator
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
326 `.iter()` or a similar method"]
328 /// The type of the elements being iterated over.
329 #[stable(feature = "rust1", since = "1.0.0")]
332 /// Advances the iterator and returns the next value.
334 /// Returns `None` when iteration is finished. Individual iterator
335 /// implementations may choose to resume iteration, and so calling `next()`
336 /// again may or may not eventually start returning `Some(Item)` again at some
344 /// let a = [1, 2, 3];
346 /// let mut iter = a.iter();
348 /// // A call to next() returns the next value...
349 /// assert_eq!(Some(&1), iter.next());
350 /// assert_eq!(Some(&2), iter.next());
351 /// assert_eq!(Some(&3), iter.next());
353 /// // ... and then None once it's over.
354 /// assert_eq!(None, iter.next());
356 /// // More calls may or may not return None. Here, they always will.
357 /// assert_eq!(None, iter.next());
358 /// assert_eq!(None, iter.next());
360 #[stable(feature = "rust1", since = "1.0.0")]
361 fn next(&mut self) -> Option<Self::Item>;
363 /// Returns the bounds on the remaining length of the iterator.
365 /// Specifically, `size_hint()` returns a tuple where the first element
366 /// is the lower bound, and the second element is the upper bound.
368 /// The second half of the tuple that is returned is an `Option<usize>`. A
369 /// `None` here means that either there is no known upper bound, or the
370 /// upper bound is larger than `usize`.
372 /// # Implementation notes
374 /// It is not enforced that an iterator implementation yields the declared
375 /// number of elements. A buggy iterator may yield less than the lower bound
376 /// or more than the upper bound of elements.
378 /// `size_hint()` is primarily intended to be used for optimizations such as
379 /// reserving space for the elements of the iterator, but must not be
380 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
381 /// implementation of `size_hint()` should not lead to memory safety
384 /// That said, the implementation should provide a correct estimation,
385 /// because otherwise it would be a violation of the trait's protocol.
387 /// The default implementation returns `(0, None)` which is correct for any
395 /// let a = [1, 2, 3];
396 /// let iter = a.iter();
398 /// assert_eq!((3, Some(3)), iter.size_hint());
401 /// A more complex example:
404 /// // The even numbers from zero to ten.
405 /// let iter = (0..10).filter(|x| x % 2 == 0);
407 /// // We might iterate from zero to ten times. Knowing that it's five
408 /// // exactly wouldn't be possible without executing filter().
409 /// assert_eq!((0, Some(10)), iter.size_hint());
411 /// // Let's add one five more numbers with chain()
412 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
414 /// // now both bounds are increased by five
415 /// assert_eq!((5, Some(15)), iter.size_hint());
418 /// Returning `None` for an upper bound:
421 /// // an infinite iterator has no upper bound
424 /// assert_eq!((0, None), iter.size_hint());
427 #[stable(feature = "rust1", since = "1.0.0")]
428 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
430 /// Consumes the iterator, counting the number of iterations and returning it.
432 /// This method will evaluate the iterator until its [`next()`] returns
433 /// `None`. Once `None` is encountered, `count()` returns the number of
434 /// times it called [`next()`].
436 /// [`next()`]: #method.next
438 /// # Overflow Behavior
440 /// The method does no guarding against overflows, so counting elements of
441 /// an iterator with more than `usize::MAX` elements either produces the
442 /// wrong result or panics. If debug assertions are enabled, a panic is
447 /// This function might panic if the iterator has more than `usize::MAX`
455 /// let a = [1, 2, 3];
456 /// assert_eq!(a.iter().count(), 3);
458 /// let a = [1, 2, 3, 4, 5];
459 /// assert_eq!(a.iter().count(), 5);
462 #[stable(feature = "rust1", since = "1.0.0")]
463 fn count(self) -> usize where Self: Sized {
465 self.fold(0, |cnt, _| cnt + 1)
468 /// Consumes the iterator, returning the last element.
470 /// This method will evaluate the iterator until it returns `None`. While
471 /// doing so, it keeps track of the current element. After `None` is
472 /// returned, `last()` will then return the last element it saw.
479 /// let a = [1, 2, 3];
480 /// assert_eq!(a.iter().last(), Some(&3));
482 /// let a = [1, 2, 3, 4, 5];
483 /// assert_eq!(a.iter().last(), Some(&5));
486 #[stable(feature = "rust1", since = "1.0.0")]
487 fn last(self) -> Option<Self::Item> where Self: Sized {
489 for x in self { last = Some(x); }
493 /// Consumes the `n` first elements of the iterator, then returns the
496 /// This method will evaluate the iterator `n` times, discarding those elements.
497 /// After it does so, it will call [`next()`] and return its value.
499 /// [`next()`]: #method.next
501 /// Like most indexing operations, the count starts from zero, so `nth(0)`
502 /// returns the first value, `nth(1)` the second, and so on.
504 /// `nth()` will return `None` if `n` is larger than the length of the
512 /// let a = [1, 2, 3];
513 /// assert_eq!(a.iter().nth(1), Some(&2));
516 /// Calling `nth()` multiple times doesn't rewind the iterator:
519 /// let a = [1, 2, 3];
521 /// let mut iter = a.iter();
523 /// assert_eq!(iter.nth(1), Some(&2));
524 /// assert_eq!(iter.nth(1), None);
527 /// Returning `None` if there are less than `n` elements:
530 /// let a = [1, 2, 3];
531 /// assert_eq!(a.iter().nth(10), None);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
537 if n == 0 { return Some(x) }
543 /// Takes two iterators and creates a new iterator over both in sequence.
545 /// `chain()` will return a new iterator which will first iterate over
546 /// values from the first iterator and then over values from the second
549 /// In other words, it links two iterators together, in a chain. 🔗
556 /// let a1 = [1, 2, 3];
557 /// let a2 = [4, 5, 6];
559 /// let mut iter = a1.iter().chain(a2.iter());
561 /// assert_eq!(iter.next(), Some(&1));
562 /// assert_eq!(iter.next(), Some(&2));
563 /// assert_eq!(iter.next(), Some(&3));
564 /// assert_eq!(iter.next(), Some(&4));
565 /// assert_eq!(iter.next(), Some(&5));
566 /// assert_eq!(iter.next(), Some(&6));
567 /// assert_eq!(iter.next(), None);
570 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
571 /// anything that can be converted into an [`Iterator`], not just an
572 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
573 /// [`IntoIterator`], and so can be passed to `chain()` directly:
575 /// [`IntoIterator`]: trait.IntoIterator.html
576 /// [`Iterator`]: trait.Iterator.html
579 /// let s1 = &[1, 2, 3];
580 /// let s2 = &[4, 5, 6];
582 /// let mut iter = s1.iter().chain(s2);
584 /// assert_eq!(iter.next(), Some(&1));
585 /// assert_eq!(iter.next(), Some(&2));
586 /// assert_eq!(iter.next(), Some(&3));
587 /// assert_eq!(iter.next(), Some(&4));
588 /// assert_eq!(iter.next(), Some(&5));
589 /// assert_eq!(iter.next(), Some(&6));
590 /// assert_eq!(iter.next(), None);
593 #[stable(feature = "rust1", since = "1.0.0")]
594 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
595 Self: Sized, U: IntoIterator<Item=Self::Item>,
597 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
600 /// 'Zips up' two iterators into a single iterator of pairs.
602 /// `zip()` returns a new iterator that will iterate over two other
603 /// iterators, returning a tuple where the first element comes from the
604 /// first iterator, and the second element comes from the second iterator.
606 /// In other words, it zips two iterators together, into a single one.
608 /// When either iterator returns `None`, all further calls to `next()`
609 /// will return `None`.
616 /// let a1 = [1, 2, 3];
617 /// let a2 = [4, 5, 6];
619 /// let mut iter = a1.iter().zip(a2.iter());
621 /// assert_eq!(iter.next(), Some((&1, &4)));
622 /// assert_eq!(iter.next(), Some((&2, &5)));
623 /// assert_eq!(iter.next(), Some((&3, &6)));
624 /// assert_eq!(iter.next(), None);
627 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
628 /// anything that can be converted into an [`Iterator`], not just an
629 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
630 /// [`IntoIterator`], and so can be passed to `zip()` directly:
632 /// [`IntoIterator`]: trait.IntoIterator.html
633 /// [`Iterator`]: trait.Iterator.html
636 /// let s1 = &[1, 2, 3];
637 /// let s2 = &[4, 5, 6];
639 /// let mut iter = s1.iter().zip(s2);
641 /// assert_eq!(iter.next(), Some((&1, &4)));
642 /// assert_eq!(iter.next(), Some((&2, &5)));
643 /// assert_eq!(iter.next(), Some((&3, &6)));
644 /// assert_eq!(iter.next(), None);
647 /// `zip()` is often used to zip an infinite iterator to a finite one.
648 /// This works because the finite iterator will eventually return `None`,
649 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
652 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
654 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
656 /// assert_eq!((0, 'f'), enumerate[0]);
657 /// assert_eq!((0, 'f'), zipper[0]);
659 /// assert_eq!((1, 'o'), enumerate[1]);
660 /// assert_eq!((1, 'o'), zipper[1]);
662 /// assert_eq!((2, 'o'), enumerate[2]);
663 /// assert_eq!((2, 'o'), zipper[2]);
666 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
670 Self: Sized, U: IntoIterator
672 Zip{a: self, b: other.into_iter()}
675 /// Takes a closure and creates an iterator which calls that closure on each
678 /// `map()` transforms one iterator into another, by means of its argument:
679 /// something that implements `FnMut`. It produces a new iterator which
680 /// calls this closure on each element of the original iterator.
682 /// If you are good at thinking in types, you can think of `map()` like this:
683 /// If you have an iterator that gives you elements of some type `A`, and
684 /// you want an iterator of some other type `B`, you can use `map()`,
685 /// passing a closure that takes an `A` and returns a `B`.
687 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
688 /// lazy, it is best used when you're already working with other iterators.
689 /// If you're doing some sort of looping for a side effect, it's considered
690 /// more idiomatic to use [`for`] than `map()`.
692 /// [`for`]: ../../book/loops.html#for
699 /// let a = [1, 2, 3];
701 /// let mut iter = a.into_iter().map(|x| 2 * x);
703 /// assert_eq!(iter.next(), Some(2));
704 /// assert_eq!(iter.next(), Some(4));
705 /// assert_eq!(iter.next(), Some(6));
706 /// assert_eq!(iter.next(), None);
709 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
712 /// # #![allow(unused_must_use)]
713 /// // don't do this:
714 /// (0..5).map(|x| println!("{}", x));
716 /// // it won't even execute, as it is lazy. Rust will warn you about this.
718 /// // Instead, use for:
720 /// println!("{}", x);
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn map<B, F>(self, f: F) -> Map<Self, F> where
726 Self: Sized, F: FnMut(Self::Item) -> B,
728 Map{iter: self, f: f}
731 /// Creates an iterator which uses a closure to determine if an element
732 /// should be yielded.
734 /// The closure must return `true` or `false`. `filter()` creates an
735 /// iterator which calls this closure on each element. If the closure
736 /// returns `true`, then the element is returned. If the closure returns
737 /// `false`, it will try again, and call the closure on the next element,
738 /// seeing if it passes the test.
745 /// let a = [0i32, 1, 2];
747 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
749 /// assert_eq!(iter.next(), Some(&1));
750 /// assert_eq!(iter.next(), Some(&2));
751 /// assert_eq!(iter.next(), None);
754 /// Because the closure passed to `filter()` takes a reference, and many
755 /// iterators iterate over references, this leads to a possibly confusing
756 /// situation, where the type of the closure is a double reference:
759 /// let a = [0, 1, 2];
761 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
763 /// assert_eq!(iter.next(), Some(&2));
764 /// assert_eq!(iter.next(), None);
767 /// It's common to instead use destructuring on the argument to strip away
771 /// let a = [0, 1, 2];
773 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
775 /// assert_eq!(iter.next(), Some(&2));
776 /// assert_eq!(iter.next(), None);
782 /// let a = [0, 1, 2];
784 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
786 /// assert_eq!(iter.next(), Some(&2));
787 /// assert_eq!(iter.next(), None);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
794 Self: Sized, P: FnMut(&Self::Item) -> bool,
796 Filter{iter: self, predicate: predicate}
799 /// Creates an iterator that both filters and maps.
801 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
802 /// iterator which calls this closure on each element. If the closure
803 /// returns `Some(element)`, then that element is returned. If the
804 /// closure returns `None`, it will try again, and call the closure on the
805 /// next element, seeing if it will return `Some`.
807 /// [`Option<T>`]: ../option/enum.Option.html
809 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
812 /// [`filter()`]: #method.filter
813 /// [`map()`]: #method.map
815 /// > If the closure returns `Some(element)`, then that element is returned.
817 /// In other words, it removes the [`Option<T>`] layer automatically. If your
818 /// mapping is already returning an [`Option<T>`] and you want to skip over
819 /// `None`s, then `filter_map()` is much, much nicer to use.
826 /// let a = ["1", "2", "lol"];
828 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
830 /// assert_eq!(iter.next(), Some(1));
831 /// assert_eq!(iter.next(), Some(2));
832 /// assert_eq!(iter.next(), None);
835 /// Here's the same example, but with [`filter()`] and [`map()`]:
838 /// let a = ["1", "2", "lol"];
840 /// let mut iter = a.iter()
841 /// .map(|s| s.parse().ok())
842 /// .filter(|s| s.is_some());
844 /// assert_eq!(iter.next(), Some(Some(1)));
845 /// assert_eq!(iter.next(), Some(Some(2)));
846 /// assert_eq!(iter.next(), None);
849 /// There's an extra layer of `Some` in there.
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
853 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
855 FilterMap { iter: self, f: f }
858 /// Creates an iterator which gives the current iteration count as well as
861 /// The iterator returned yields pairs `(i, val)`, where `i` is the
862 /// current index of iteration and `val` is the value returned by the
865 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
866 /// different sized integer, the [`zip()`] function provides similar
869 /// [`usize`]: ../primitive.usize.html
870 /// [`zip()`]: #method.zip
872 /// # Overflow Behavior
874 /// The method does no guarding against overflows, so enumerating more than
875 /// [`usize::MAX`] elements either produces the wrong result or panics. If
876 /// debug assertions are enabled, a panic is guaranteed.
878 /// [`usize::MAX`]: ../usize/constant.MAX.html
882 /// The returned iterator might panic if the to-be-returned index would
883 /// overflow a `usize`.
888 /// let a = [1, 2, 3];
890 /// let mut iter = a.iter().enumerate();
892 /// assert_eq!(iter.next(), Some((0, &1)));
893 /// assert_eq!(iter.next(), Some((1, &2)));
894 /// assert_eq!(iter.next(), Some((2, &3)));
895 /// assert_eq!(iter.next(), None);
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
900 Enumerate { iter: self, count: 0 }
903 /// Creates an iterator which can look at the `next()` element without
906 /// Adds a [`peek()`] method to an iterator. See its documentation for
907 /// more information.
909 /// [`peek()`]: struct.Peekable.html#method.peek
916 /// let xs = [1, 2, 3];
918 /// let mut iter = xs.iter().peekable();
920 /// // peek() lets us see into the future
921 /// assert_eq!(iter.peek(), Some(&&1));
922 /// assert_eq!(iter.next(), Some(&1));
924 /// assert_eq!(iter.next(), Some(&2));
926 /// // we can peek() multiple times, the iterator won't advance
927 /// assert_eq!(iter.peek(), Some(&&3));
928 /// assert_eq!(iter.peek(), Some(&&3));
930 /// assert_eq!(iter.next(), Some(&3));
932 /// // after the iterator is finished, so is peek()
933 /// assert_eq!(iter.peek(), None);
934 /// assert_eq!(iter.next(), None);
937 #[stable(feature = "rust1", since = "1.0.0")]
938 fn peekable(self) -> Peekable<Self> where Self: Sized {
939 Peekable{iter: self, peeked: None}
942 /// Creates an iterator that [`skip()`]s elements based on a predicate.
944 /// [`skip()`]: #method.skip
946 /// `skip_while()` takes a closure as an argument. It will call this
947 /// closure on each element of the iterator, and ignore elements
948 /// until it returns `false`.
950 /// After `false` is returned, `skip_while()`'s job is over, and the
951 /// rest of the elements are yielded.
958 /// let a = [-1i32, 0, 1];
960 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
962 /// assert_eq!(iter.next(), Some(&0));
963 /// assert_eq!(iter.next(), Some(&1));
964 /// assert_eq!(iter.next(), None);
967 /// Because the closure passed to `skip_while()` takes a reference, and many
968 /// iterators iterate over references, this leads to a possibly confusing
969 /// situation, where the type of the closure is a double reference:
972 /// let a = [-1, 0, 1];
974 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
976 /// assert_eq!(iter.next(), Some(&0));
977 /// assert_eq!(iter.next(), Some(&1));
978 /// assert_eq!(iter.next(), None);
981 /// Stopping after an initial `false`:
984 /// let a = [-1, 0, 1, -2];
986 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
988 /// assert_eq!(iter.next(), Some(&0));
989 /// assert_eq!(iter.next(), Some(&1));
991 /// // while this would have been false, since we already got a false,
992 /// // skip_while() isn't used any more
993 /// assert_eq!(iter.next(), Some(&-2));
995 /// assert_eq!(iter.next(), None);
998 #[stable(feature = "rust1", since = "1.0.0")]
999 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
1000 Self: Sized, P: FnMut(&Self::Item) -> bool,
1002 SkipWhile{iter: self, flag: false, predicate: predicate}
1005 /// Creates an iterator that yields elements based on a predicate.
1007 /// `take_while()` takes a closure as an argument. It will call this
1008 /// closure on each element of the iterator, and yield elements
1009 /// while it returns `true`.
1011 /// After `false` is returned, `take_while()`'s job is over, and the
1012 /// rest of the elements are ignored.
1019 /// let a = [-1i32, 0, 1];
1021 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1023 /// assert_eq!(iter.next(), Some(&-1));
1024 /// assert_eq!(iter.next(), None);
1027 /// Because the closure passed to `take_while()` takes a reference, and many
1028 /// iterators iterate over references, this leads to a possibly confusing
1029 /// situation, where the type of the closure is a double reference:
1032 /// let a = [-1, 0, 1];
1034 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1036 /// assert_eq!(iter.next(), Some(&-1));
1037 /// assert_eq!(iter.next(), None);
1040 /// Stopping after an initial `false`:
1043 /// let a = [-1, 0, 1, -2];
1045 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1047 /// assert_eq!(iter.next(), Some(&-1));
1049 /// // We have more elements that are less than zero, but since we already
1050 /// // got a false, take_while() isn't used any more
1051 /// assert_eq!(iter.next(), None);
1054 /// Because `take_while()` needs to look at the value in order to see if it
1055 /// should be included or not, consuming iterators will see that it is
1059 /// let a = [1, 2, 3, 4];
1060 /// let mut iter = a.into_iter();
1062 /// let result: Vec<i32> = iter.by_ref()
1063 /// .take_while(|n| **n != 3)
1067 /// assert_eq!(result, &[1, 2]);
1069 /// let result: Vec<i32> = iter.cloned().collect();
1071 /// assert_eq!(result, &[4]);
1074 /// The `3` is no longer there, because it was consumed in order to see if
1075 /// the iteration should stop, but wasn't placed back into the iterator or
1076 /// some similar thing.
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1080 Self: Sized, P: FnMut(&Self::Item) -> bool,
1082 TakeWhile{iter: self, flag: false, predicate: predicate}
1085 /// Creates an iterator that skips the first `n` elements.
1087 /// After they have been consumed, the rest of the elements are yielded.
1094 /// let a = [1, 2, 3];
1096 /// let mut iter = a.iter().skip(2);
1098 /// assert_eq!(iter.next(), Some(&3));
1099 /// assert_eq!(iter.next(), None);
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1104 Skip{iter: self, n: n}
1107 /// Creates an iterator that yields its first `n` elements.
1114 /// let a = [1, 2, 3];
1116 /// let mut iter = a.iter().take(2);
1118 /// assert_eq!(iter.next(), Some(&1));
1119 /// assert_eq!(iter.next(), Some(&2));
1120 /// assert_eq!(iter.next(), None);
1123 /// `take()` is often used with an infinite iterator, to make it finite:
1126 /// let mut iter = (0..).take(3);
1128 /// assert_eq!(iter.next(), Some(0));
1129 /// assert_eq!(iter.next(), Some(1));
1130 /// assert_eq!(iter.next(), Some(2));
1131 /// assert_eq!(iter.next(), None);
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1136 Take{iter: self, n: n}
1139 /// An iterator adaptor similar to [`fold()`] that holds internal state and
1140 /// produces a new iterator.
1142 /// [`fold()`]: #method.fold
1144 /// `scan()` takes two arguments: an initial value which seeds the internal
1145 /// state, and a closure with two arguments, the first being a mutable
1146 /// reference to the internal state and the second an iterator element.
1147 /// The closure can assign to the internal state to share state between
1150 /// On iteration, the closure will be applied to each element of the
1151 /// iterator and the return value from the closure, an [`Option`], is
1152 /// yielded by the iterator.
1154 /// [`Option`]: ../option/enum.Option.html
1161 /// let a = [1, 2, 3];
1163 /// let mut iter = a.iter().scan(1, |state, &x| {
1164 /// // each iteration, we'll multiply the state by the element
1165 /// *state = *state * x;
1167 /// // the value passed on to the next iteration
1171 /// assert_eq!(iter.next(), Some(1));
1172 /// assert_eq!(iter.next(), Some(2));
1173 /// assert_eq!(iter.next(), Some(6));
1174 /// assert_eq!(iter.next(), None);
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1179 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1181 Scan{iter: self, f: f, state: initial_state}
1184 /// Creates an iterator that works like map, but flattens nested structure.
1186 /// The [`map()`] adapter is very useful, but only when the closure
1187 /// argument produces values. If it produces an iterator instead, there's
1188 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1191 /// [`map()`]: #method.map
1193 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1194 /// one item for each element, and `flat_map()`'s closure returns an
1195 /// iterator for each element.
1202 /// let words = ["alpha", "beta", "gamma"];
1204 /// // chars() returns an iterator
1205 /// let merged: String = words.iter()
1206 /// .flat_map(|s| s.chars())
1208 /// assert_eq!(merged, "alphabetagamma");
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1213 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1215 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1218 /// Creates an iterator which ends after the first `None`.
1220 /// After an iterator returns `None`, future calls may or may not yield
1221 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1222 /// `None` is given, it will always return `None` forever.
1229 /// // an iterator which alternates between Some and None
1230 /// struct Alternate {
1234 /// impl Iterator for Alternate {
1235 /// type Item = i32;
1237 /// fn next(&mut self) -> Option<i32> {
1238 /// let val = self.state;
1239 /// self.state = self.state + 1;
1241 /// // if it's even, Some(i32), else None
1242 /// if val % 2 == 0 {
1250 /// let mut iter = Alternate { state: 0 };
1252 /// // we can see our iterator going back and forth
1253 /// assert_eq!(iter.next(), Some(0));
1254 /// assert_eq!(iter.next(), None);
1255 /// assert_eq!(iter.next(), Some(2));
1256 /// assert_eq!(iter.next(), None);
1258 /// // however, once we fuse it...
1259 /// let mut iter = iter.fuse();
1261 /// assert_eq!(iter.next(), Some(4));
1262 /// assert_eq!(iter.next(), None);
1264 /// // it will always return None after the first time.
1265 /// assert_eq!(iter.next(), None);
1266 /// assert_eq!(iter.next(), None);
1267 /// assert_eq!(iter.next(), None);
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 fn fuse(self) -> Fuse<Self> where Self: Sized {
1272 Fuse{iter: self, done: false}
1275 /// Do something with each element of an iterator, passing the value on.
1277 /// When using iterators, you'll often chain several of them together.
1278 /// While working on such code, you might want to check out what's
1279 /// happening at various parts in the pipeline. To do that, insert
1280 /// a call to `inspect()`.
1282 /// It's much more common for `inspect()` to be used as a debugging tool
1283 /// than to exist in your final code, but never say never.
1290 /// let a = [1, 4, 2, 3];
1292 /// // this iterator sequence is complex.
1293 /// let sum = a.iter()
1295 /// .filter(|&x| x % 2 == 0)
1296 /// .fold(0, |sum, i| sum + i);
1298 /// println!("{}", sum);
1300 /// // let's add some inspect() calls to investigate what's happening
1301 /// let sum = a.iter()
1303 /// .inspect(|x| println!("about to filter: {}", x))
1304 /// .filter(|&x| x % 2 == 0)
1305 /// .inspect(|x| println!("made it through filter: {}", x))
1306 /// .fold(0, |sum, i| sum + i);
1308 /// println!("{}", sum);
1311 /// This will print:
1314 /// about to filter: 1
1315 /// about to filter: 4
1316 /// made it through filter: 4
1317 /// about to filter: 2
1318 /// made it through filter: 2
1319 /// about to filter: 3
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1325 Self: Sized, F: FnMut(&Self::Item),
1327 Inspect{iter: self, f: f}
1330 /// Borrows an iterator, rather than consuming it.
1332 /// This is useful to allow applying iterator adaptors while still
1333 /// retaining ownership of the original iterator.
1340 /// let a = [1, 2, 3];
1342 /// let iter = a.into_iter();
1344 /// let sum: i32 = iter.take(5)
1345 /// .fold(0, |acc, &i| acc + i );
1347 /// assert_eq!(sum, 6);
1349 /// // if we try to use iter again, it won't work. The following line
1350 /// // gives "error: use of moved value: `iter`
1351 /// // assert_eq!(iter.next(), None);
1353 /// // let's try that again
1354 /// let a = [1, 2, 3];
1356 /// let mut iter = a.into_iter();
1358 /// // instead, we add in a .by_ref()
1359 /// let sum: i32 = iter.by_ref()
1361 /// .fold(0, |acc, &i| acc + i );
1363 /// assert_eq!(sum, 3);
1365 /// // now this is just fine:
1366 /// assert_eq!(iter.next(), Some(&3));
1367 /// assert_eq!(iter.next(), None);
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1372 /// Transforms an iterator into a collection.
1374 /// `collect()` can take anything iterable, and turn it into a relevant
1375 /// collection. This is one of the more powerful methods in the standard
1376 /// library, used in a variety of contexts.
1378 /// The most basic pattern in which `collect()` is used is to turn one
1379 /// collection into another. You take a collection, call `iter()` on it,
1380 /// do a bunch of transformations, and then `collect()` at the end.
1382 /// One of the keys to `collect()`'s power is that many things you might
1383 /// not think of as 'collections' actually are. For example, a [`String`]
1384 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1385 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1388 /// [`String`]: ../string/struct.String.html
1389 /// [`Result<T, E>`]: ../result/enum.Result.html
1390 /// [`char`]: ../primitive.char.html
1392 /// Because `collect()` is so general, it can cause problems with type
1393 /// inference. As such, `collect()` is one of the few times you'll see
1394 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1395 /// helps the inference algorithm understand specifically which collection
1396 /// you're trying to collect into.
1403 /// let a = [1, 2, 3];
1405 /// let doubled: Vec<i32> = a.iter()
1406 /// .map(|&x| x * 2)
1409 /// assert_eq!(vec![2, 4, 6], doubled);
1412 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1413 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1415 /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1418 /// use std::collections::VecDeque;
1420 /// let a = [1, 2, 3];
1422 /// let doubled: VecDeque<i32> = a.iter()
1423 /// .map(|&x| x * 2)
1426 /// assert_eq!(2, doubled[0]);
1427 /// assert_eq!(4, doubled[1]);
1428 /// assert_eq!(6, doubled[2]);
1431 /// Using the 'turbofish' instead of annotating `doubled`:
1434 /// let a = [1, 2, 3];
1436 /// let doubled = a.iter()
1437 /// .map(|&x| x * 2)
1438 /// .collect::<Vec<i32>>();
1440 /// assert_eq!(vec![2, 4, 6], doubled);
1443 /// Because `collect()` cares about what you're collecting into, you can
1444 /// still use a partial type hint, `_`, with the turbofish:
1447 /// let a = [1, 2, 3];
1449 /// let doubled = a.iter()
1450 /// .map(|&x| x * 2)
1451 /// .collect::<Vec<_>>();
1453 /// assert_eq!(vec![2, 4, 6], doubled);
1456 /// Using `collect()` to make a [`String`]:
1459 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1461 /// let hello: String = chars.iter()
1462 /// .map(|&x| x as u8)
1463 /// .map(|x| (x + 1) as char)
1466 /// assert_eq!("hello", hello);
1469 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1470 /// see if any of them failed:
1473 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1475 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1477 /// // gives us the first error
1478 /// assert_eq!(Err("nope"), result);
1480 /// let results = [Ok(1), Ok(3)];
1482 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1484 /// // gives us the list of answers
1485 /// assert_eq!(Ok(vec![1, 3]), result);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1490 FromIterator::from_iter(self)
1493 /// Consumes an iterator, creating two collections from it.
1495 /// The predicate passed to `partition()` can return `true`, or `false`.
1496 /// `partition()` returns a pair, all of the elements for which it returned
1497 /// `true`, and all of the elements for which it returned `false`.
1504 /// let a = [1, 2, 3];
1506 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1507 /// .partition(|&n| n % 2 == 0);
1509 /// assert_eq!(even, vec![2]);
1510 /// assert_eq!(odd, vec![1, 3]);
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 fn partition<B, F>(self, mut f: F) -> (B, B) where
1515 B: Default + Extend<Self::Item>,
1516 F: FnMut(&Self::Item) -> bool
1518 let mut left: B = Default::default();
1519 let mut right: B = Default::default();
1523 left.extend(Some(x))
1525 right.extend(Some(x))
1532 /// An iterator adaptor that applies a function, producing a single, final value.
1534 /// `fold()` takes two arguments: an initial value, and a closure with two
1535 /// arguments: an 'accumulator', and an element. It returns the value that
1536 /// the accumulator should have for the next iteration.
1538 /// The initial value is the value the accumulator will have on the first
1541 /// After applying this closure to every element of the iterator, `fold()`
1542 /// returns the accumulator.
1544 /// This operation is sometimes called 'reduce' or 'inject'.
1546 /// Folding is useful whenever you have a collection of something, and want
1547 /// to produce a single value from it.
1554 /// let a = [1, 2, 3];
1556 /// // the sum of all of the elements of a
1557 /// let sum = a.iter()
1558 /// .fold(0, |acc, &x| acc + x);
1560 /// assert_eq!(sum, 6);
1563 /// Let's walk through each step of the iteration here:
1565 /// | element | acc | x | result |
1566 /// |---------|-----|---|--------|
1568 /// | 1 | 0 | 1 | 1 |
1569 /// | 2 | 1 | 2 | 3 |
1570 /// | 3 | 3 | 3 | 6 |
1572 /// And so, our final result, `6`.
1574 /// It's common for people who haven't used iterators a lot to
1575 /// use a `for` loop with a list of things to build up a result. Those
1576 /// can be turned into `fold()`s:
1579 /// let numbers = [1, 2, 3, 4, 5];
1581 /// let mut result = 0;
1584 /// for i in &numbers {
1585 /// result = result + i;
1589 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1591 /// // they're the same
1592 /// assert_eq!(result, result2);
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 fn fold<B, F>(self, init: B, mut f: F) -> B where
1597 Self: Sized, F: FnMut(B, Self::Item) -> B,
1599 let mut accum = init;
1601 accum = f(accum, x);
1606 /// Tests if every element of the iterator matches a predicate.
1608 /// `all()` takes a closure that returns `true` or `false`. It applies
1609 /// this closure to each element of the iterator, and if they all return
1610 /// `true`, then so does `all()`. If any of them return `false`, it
1611 /// returns `false`.
1613 /// `all()` is short-circuiting; in other words, it will stop processing
1614 /// as soon as it finds a `false`, given that no matter what else happens,
1615 /// the result will also be `false`.
1617 /// An empty iterator returns `true`.
1624 /// let a = [1, 2, 3];
1626 /// assert!(a.iter().all(|&x| x > 0));
1628 /// assert!(!a.iter().all(|&x| x > 2));
1631 /// Stopping at the first `false`:
1634 /// let a = [1, 2, 3];
1636 /// let mut iter = a.iter();
1638 /// assert!(!iter.all(|&x| x != 2));
1640 /// // we can still use `iter`, as there are more elements.
1641 /// assert_eq!(iter.next(), Some(&3));
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 fn all<F>(&mut self, mut f: F) -> bool where
1646 Self: Sized, F: FnMut(Self::Item) -> bool
1656 /// Tests if any element of the iterator matches a predicate.
1658 /// `any()` takes a closure that returns `true` or `false`. It applies
1659 /// this closure to each element of the iterator, and if any of them return
1660 /// `true`, then so does `any()`. If they all return `false`, it
1661 /// returns `false`.
1663 /// `any()` is short-circuiting; in other words, it will stop processing
1664 /// as soon as it finds a `true`, given that no matter what else happens,
1665 /// the result will also be `true`.
1667 /// An empty iterator returns `false`.
1674 /// let a = [1, 2, 3];
1676 /// assert!(a.iter().any(|&x| x > 0));
1678 /// assert!(!a.iter().any(|&x| x > 5));
1681 /// Stopping at the first `true`:
1684 /// let a = [1, 2, 3];
1686 /// let mut iter = a.iter();
1688 /// assert!(iter.any(|&x| x != 2));
1690 /// // we can still use `iter`, as there are more elements.
1691 /// assert_eq!(iter.next(), Some(&2));
1694 #[stable(feature = "rust1", since = "1.0.0")]
1695 fn any<F>(&mut self, mut f: F) -> bool where
1697 F: FnMut(Self::Item) -> bool
1707 /// Searches for an element of an iterator that satisfies a predicate.
1709 /// `find()` takes a closure that returns `true` or `false`. It applies
1710 /// this closure to each element of the iterator, and if any of them return
1711 /// `true`, then `find()` returns `Some(element)`. If they all return
1712 /// `false`, it returns `None`.
1714 /// `find()` is short-circuiting; in other words, it will stop processing
1715 /// as soon as the closure returns `true`.
1717 /// Because `find()` takes a reference, and many iterators iterate over
1718 /// references, this leads to a possibly confusing situation where the
1719 /// argument is a double reference. You can see this effect in the
1720 /// examples below, with `&&x`.
1727 /// let a = [1, 2, 3];
1729 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1731 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1734 /// Stopping at the first `true`:
1737 /// let a = [1, 2, 3];
1739 /// let mut iter = a.iter();
1741 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1743 /// // we can still use `iter`, as there are more elements.
1744 /// assert_eq!(iter.next(), Some(&3));
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1750 P: FnMut(&Self::Item) -> bool,
1753 if predicate(&x) { return Some(x) }
1758 /// Searches for an element in an iterator, returning its index.
1760 /// `position()` takes a closure that returns `true` or `false`. It applies
1761 /// this closure to each element of the iterator, and if one of them
1762 /// returns `true`, then `position()` returns `Some(index)`. If all of
1763 /// them return `false`, it returns `None`.
1765 /// `position()` is short-circuiting; in other words, it will stop
1766 /// processing as soon as it finds a `true`.
1768 /// # Overflow Behavior
1770 /// The method does no guarding against overflows, so if there are more
1771 /// than `usize::MAX` non-matching elements, it either produces the wrong
1772 /// result or panics. If debug assertions are enabled, a panic is
1777 /// This function might panic if the iterator has more than `usize::MAX`
1778 /// non-matching elements.
1785 /// let a = [1, 2, 3];
1787 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1789 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1792 /// Stopping at the first `true`:
1795 /// let a = [1, 2, 3];
1797 /// let mut iter = a.iter();
1799 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1801 /// // we can still use `iter`, as there are more elements.
1802 /// assert_eq!(iter.next(), Some(&3));
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1808 P: FnMut(Self::Item) -> bool,
1810 // `enumerate` might overflow.
1811 for (i, x) in self.enumerate() {
1819 /// Searches for an element in an iterator from the right, returning its
1822 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1823 /// this closure to each element of the iterator, starting from the end,
1824 /// and if one of them returns `true`, then `rposition()` returns
1825 /// `Some(index)`. If all of them return `false`, it returns `None`.
1827 /// `rposition()` is short-circuiting; in other words, it will stop
1828 /// processing as soon as it finds a `true`.
1835 /// let a = [1, 2, 3];
1837 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1839 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1842 /// Stopping at the first `true`:
1845 /// let a = [1, 2, 3];
1847 /// let mut iter = a.iter();
1849 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1851 /// // we can still use `iter`, as there are more elements.
1852 /// assert_eq!(iter.next(), Some(&1));
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1857 P: FnMut(Self::Item) -> bool,
1858 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1860 let mut i = self.len();
1862 while let Some(v) = self.next_back() {
1866 // No need for an overflow check here, because `ExactSizeIterator`
1867 // implies that the number of elements fits into a `usize`.
1873 /// Returns the maximum element of an iterator.
1875 /// If the two elements are equally maximum, the latest element is
1883 /// let a = [1, 2, 3];
1885 /// assert_eq!(a.iter().max(), Some(&3));
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1893 // switch to y even if it is only equal, to preserve
1895 |_, x, _, y| *x <= *y)
1899 /// Returns the minimum element of an iterator.
1901 /// If the two elements are equally minimum, the first element is
1909 /// let a = [1, 2, 3];
1911 /// assert_eq!(a.iter().min(), Some(&1));
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1919 // only switch to y if it is strictly smaller, to
1920 // preserve stability.
1921 |_, x, _, y| *x > *y)
1925 #[allow(missing_docs)]
1927 #[unstable(feature = "iter_cmp",
1928 reason = "may want to produce an Ordering directly; see #15311",
1930 #[rustc_deprecated(reason = "renamed to max_by_key", since = "1.6.0")]
1931 fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1933 F: FnMut(&Self::Item) -> B,
1938 /// Returns the element that gives the maximum value from the
1939 /// specified function.
1941 /// Returns the rightmost element if the comparison determines two elements
1942 /// to be equally maximum.
1947 /// let a = [-3_i32, 0, 1, 5, -10];
1948 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1951 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1952 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1953 where Self: Sized, F: FnMut(&Self::Item) -> B,
1957 // switch to y even if it is only equal, to preserve
1959 |x_p, _, y_p, _| x_p <= y_p)
1964 #[allow(missing_docs)]
1965 #[unstable(feature = "iter_cmp",
1966 reason = "may want to produce an Ordering directly; see #15311",
1968 #[rustc_deprecated(reason = "renamed to min_by_key", since = "1.6.0")]
1969 fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1971 F: FnMut(&Self::Item) -> B,
1976 /// Returns the element that gives the minimum value from the
1977 /// specified function.
1979 /// Returns the latest element if the comparison determines two elements
1980 /// to be equally minimum.
1985 /// let a = [-3_i32, 0, 1, 5, -10];
1986 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1988 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1989 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1990 where Self: Sized, F: FnMut(&Self::Item) -> B,
1994 // only switch to y if it is strictly smaller, to
1995 // preserve stability.
1996 |x_p, _, y_p, _| x_p > y_p)
2000 /// Reverses an iterator's direction.
2002 /// Usually, iterators iterate from left to right. After using `rev()`,
2003 /// an iterator will instead iterate from right to left.
2005 /// This is only possible if the iterator has an end, so `rev()` only
2006 /// works on [`DoubleEndedIterator`]s.
2008 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
2013 /// let a = [1, 2, 3];
2015 /// let mut iter = a.iter().rev();
2017 /// assert_eq!(iter.next(), Some(&3));
2018 /// assert_eq!(iter.next(), Some(&2));
2019 /// assert_eq!(iter.next(), Some(&1));
2021 /// assert_eq!(iter.next(), None);
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2029 /// Converts an iterator of pairs into a pair of containers.
2031 /// `unzip()` consumes an entire iterator of pairs, producing two
2032 /// collections: one from the left elements of the pairs, and one
2033 /// from the right elements.
2035 /// This function is, in some sense, the opposite of [`zip()`].
2037 /// [`zip()`]: #method.zip
2044 /// let a = [(1, 2), (3, 4)];
2046 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2048 /// assert_eq!(left, [1, 3]);
2049 /// assert_eq!(right, [2, 4]);
2051 #[stable(feature = "rust1", since = "1.0.0")]
2052 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2053 FromA: Default + Extend<A>,
2054 FromB: Default + Extend<B>,
2055 Self: Sized + Iterator<Item=(A, B)>,
2057 struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
2058 impl<A> Iterator for SizeHint<A> {
2061 fn next(&mut self) -> Option<A> { None }
2062 fn size_hint(&self) -> (usize, Option<usize>) {
2067 let (lo, hi) = self.size_hint();
2068 let mut ts: FromA = Default::default();
2069 let mut us: FromB = Default::default();
2071 ts.extend(SizeHint(lo, hi, marker::PhantomData));
2072 us.extend(SizeHint(lo, hi, marker::PhantomData));
2074 for (t, u) in self {
2082 /// Creates an iterator which `clone()`s all of its elements.
2084 /// This is useful when you have an iterator over `&T`, but you need an
2085 /// iterator over `T`.
2092 /// let a = [1, 2, 3];
2094 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2096 /// // cloned is the same as .map(|&x| x), for integers
2097 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2099 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2100 /// assert_eq!(v_map, vec![1, 2, 3]);
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2104 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2109 /// Repeats an iterator endlessly.
2111 /// Instead of stopping at `None`, the iterator will instead start again,
2112 /// from the beginning. After iterating again, it will start at the
2113 /// beginning again. And again. And again. Forever.
2120 /// let a = [1, 2, 3];
2122 /// let mut it = a.iter().cycle();
2124 /// assert_eq!(it.next(), Some(&1));
2125 /// assert_eq!(it.next(), Some(&2));
2126 /// assert_eq!(it.next(), Some(&3));
2127 /// assert_eq!(it.next(), Some(&1));
2128 /// assert_eq!(it.next(), Some(&2));
2129 /// assert_eq!(it.next(), Some(&3));
2130 /// assert_eq!(it.next(), Some(&1));
2132 #[stable(feature = "rust1", since = "1.0.0")]
2134 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2135 Cycle{orig: self.clone(), iter: self}
2138 /// Sums the elements of an iterator.
2140 /// Takes each element, adds them together, and returns the result.
2142 /// An empty iterator returns the zero value of the type.
2149 /// #![feature(iter_arith)]
2151 /// let a = [1, 2, 3];
2152 /// let sum: i32 = a.iter().sum();
2154 /// assert_eq!(sum, 6);
2156 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2158 fn sum<S>(self) -> S where
2159 S: Add<Self::Item, Output=S> + Zero,
2162 self.fold(Zero::zero(), |s, e| s + e)
2165 /// Iterates over the entire iterator, multiplying all the elements
2167 /// An empty iterator returns the one value of the type.
2172 /// #![feature(iter_arith)]
2174 /// fn factorial(n: u32) -> u32 {
2175 /// (1..).take_while(|&i| i <= n).product()
2177 /// assert_eq!(factorial(0), 1);
2178 /// assert_eq!(factorial(1), 1);
2179 /// assert_eq!(factorial(5), 120);
2181 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2183 fn product<P>(self) -> P where
2184 P: Mul<Self::Item, Output=P> + One,
2187 self.fold(One::one(), |p, e| p * e)
2190 /// Lexicographically compares the elements of this `Iterator` with those
2192 #[stable(feature = "iter_order", since = "1.5.0")]
2193 fn cmp<I>(mut self, other: I) -> Ordering where
2194 I: IntoIterator<Item = Self::Item>,
2198 let mut other = other.into_iter();
2201 match (self.next(), other.next()) {
2202 (None, None) => return Ordering::Equal,
2203 (None, _ ) => return Ordering::Less,
2204 (_ , None) => return Ordering::Greater,
2205 (Some(x), Some(y)) => match x.cmp(&y) {
2206 Ordering::Equal => (),
2207 non_eq => return non_eq,
2213 /// Lexicographically compares the elements of this `Iterator` with those
2215 #[stable(feature = "iter_order", since = "1.5.0")]
2216 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2218 Self::Item: PartialOrd<I::Item>,
2221 let mut other = other.into_iter();
2224 match (self.next(), other.next()) {
2225 (None, None) => return Some(Ordering::Equal),
2226 (None, _ ) => return Some(Ordering::Less),
2227 (_ , None) => return Some(Ordering::Greater),
2228 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2229 Some(Ordering::Equal) => (),
2230 non_eq => return non_eq,
2236 /// Determines if the elements of this `Iterator` are equal to those of
2238 #[stable(feature = "iter_order", since = "1.5.0")]
2239 fn eq<I>(mut self, other: I) -> bool where
2241 Self::Item: PartialEq<I::Item>,
2244 let mut other = other.into_iter();
2247 match (self.next(), other.next()) {
2248 (None, None) => return true,
2249 (None, _) | (_, None) => return false,
2250 (Some(x), Some(y)) => if x != y { return false },
2255 /// Determines if the elements of this `Iterator` are unequal to those of
2257 #[stable(feature = "iter_order", since = "1.5.0")]
2258 fn ne<I>(mut self, other: I) -> bool where
2260 Self::Item: PartialEq<I::Item>,
2263 let mut other = other.into_iter();
2266 match (self.next(), other.next()) {
2267 (None, None) => return false,
2268 (None, _) | (_, None) => return true,
2269 (Some(x), Some(y)) => if x.ne(&y) { return true },
2274 /// Determines if the elements of this `Iterator` are lexicographically
2275 /// less than those of another.
2276 #[stable(feature = "iter_order", since = "1.5.0")]
2277 fn lt<I>(mut self, other: I) -> bool where
2279 Self::Item: PartialOrd<I::Item>,
2282 let mut other = other.into_iter();
2285 match (self.next(), other.next()) {
2286 (None, None) => return false,
2287 (None, _ ) => return true,
2288 (_ , None) => return false,
2289 (Some(x), Some(y)) => {
2290 match x.partial_cmp(&y) {
2291 Some(Ordering::Less) => return true,
2292 Some(Ordering::Equal) => {}
2293 Some(Ordering::Greater) => return false,
2294 None => return false,
2301 /// Determines if the elements of this `Iterator` are lexicographically
2302 /// less or equal to those of another.
2303 #[stable(feature = "iter_order", since = "1.5.0")]
2304 fn le<I>(mut self, other: I) -> bool where
2306 Self::Item: PartialOrd<I::Item>,
2309 let mut other = other.into_iter();
2312 match (self.next(), other.next()) {
2313 (None, None) => return true,
2314 (None, _ ) => return true,
2315 (_ , None) => return false,
2316 (Some(x), Some(y)) => {
2317 match x.partial_cmp(&y) {
2318 Some(Ordering::Less) => return true,
2319 Some(Ordering::Equal) => {}
2320 Some(Ordering::Greater) => return false,
2321 None => return false,
2328 /// Determines if the elements of this `Iterator` are lexicographically
2329 /// greater than those of another.
2330 #[stable(feature = "iter_order", since = "1.5.0")]
2331 fn gt<I>(mut self, other: I) -> bool where
2333 Self::Item: PartialOrd<I::Item>,
2336 let mut other = other.into_iter();
2339 match (self.next(), other.next()) {
2340 (None, None) => return false,
2341 (None, _ ) => return false,
2342 (_ , None) => return true,
2343 (Some(x), Some(y)) => {
2344 match x.partial_cmp(&y) {
2345 Some(Ordering::Less) => return false,
2346 Some(Ordering::Equal) => {}
2347 Some(Ordering::Greater) => return true,
2348 None => return false,
2355 /// Determines if the elements of this `Iterator` are lexicographically
2356 /// greater than or equal to those of another.
2357 #[stable(feature = "iter_order", since = "1.5.0")]
2358 fn ge<I>(mut self, other: I) -> bool where
2360 Self::Item: PartialOrd<I::Item>,
2363 let mut other = other.into_iter();
2366 match (self.next(), other.next()) {
2367 (None, None) => return true,
2368 (None, _ ) => return false,
2369 (_ , None) => return true,
2370 (Some(x), Some(y)) => {
2371 match x.partial_cmp(&y) {
2372 Some(Ordering::Less) => return false,
2373 Some(Ordering::Equal) => {}
2374 Some(Ordering::Greater) => return true,
2375 None => return false,
2383 /// Select an element from an iterator based on the given projection
2384 /// and "comparison" function.
2386 /// This is an idiosyncratic helper to try to factor out the
2387 /// commonalities of {max,min}{,_by}. In particular, this avoids
2388 /// having to implement optimizations several times.
2390 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2392 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2394 FProj: FnMut(&I::Item) -> B,
2395 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2397 // start with the first element as our selection. This avoids
2398 // having to use `Option`s inside the loop, translating to a
2399 // sizeable performance gain (6x in one case).
2400 it.next().map(|mut sel| {
2401 let mut sel_p = f_proj(&sel);
2404 let x_p = f_proj(&x);
2405 if f_cmp(&sel_p, &sel, &x_p, &x) {
2414 #[stable(feature = "rust1", since = "1.0.0")]
2415 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2416 type Item = I::Item;
2417 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2418 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2421 /// Conversion from an `Iterator`.
2423 /// By implementing `FromIterator` for a type, you define how it will be
2424 /// created from an iterator. This is common for types which describe a
2425 /// collection of some kind.
2427 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
2428 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
2429 /// documentation for more examples.
2431 /// [`from_iter()`]: #tymethod.from_iter
2432 /// [`Iterator`]: trait.Iterator.html
2433 /// [`collect()`]: trait.Iterator.html#method.collect
2435 /// See also: [`IntoIterator`].
2437 /// [`IntoIterator`]: trait.IntoIterator.html
2444 /// use std::iter::FromIterator;
2446 /// let five_fives = std::iter::repeat(5).take(5);
2448 /// let v = Vec::from_iter(five_fives);
2450 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2453 /// Using [`collect()`] to implicitly use `FromIterator`:
2456 /// let five_fives = std::iter::repeat(5).take(5);
2458 /// let v: Vec<i32> = five_fives.collect();
2460 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2463 /// Implementing `FromIterator` for your type:
2466 /// use std::iter::FromIterator;
2468 /// // A sample collection, that's just a wrapper over Vec<T>
2469 /// #[derive(Debug)]
2470 /// struct MyCollection(Vec<i32>);
2472 /// // Let's give it some methods so we can create one and add things
2474 /// impl MyCollection {
2475 /// fn new() -> MyCollection {
2476 /// MyCollection(Vec::new())
2479 /// fn add(&mut self, elem: i32) {
2480 /// self.0.push(elem);
2484 /// // and we'll implement FromIterator
2485 /// impl FromIterator<i32> for MyCollection {
2486 /// fn from_iter<I: IntoIterator<Item=i32>>(iterator: I) -> Self {
2487 /// let mut c = MyCollection::new();
2489 /// for i in iterator {
2497 /// // Now we can make a new iterator...
2498 /// let iter = (0..5).into_iter();
2500 /// // ... and make a MyCollection out of it
2501 /// let c = MyCollection::from_iter(iter);
2503 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2505 /// // collect works too!
2507 /// let iter = (0..5).into_iter();
2508 /// let c: MyCollection = iter.collect();
2510 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2514 built from an iterator over elements of type `{A}`"]
2515 pub trait FromIterator<A>: Sized {
2516 /// Creates a value from an iterator.
2518 /// See the [module-level documentation] for more.
2520 /// [module-level documentation]: trait.FromIterator.html
2527 /// use std::iter::FromIterator;
2529 /// let five_fives = std::iter::repeat(5).take(5);
2531 /// let v = Vec::from_iter(five_fives);
2533 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
2539 /// Conversion into an `Iterator`.
2541 /// By implementing `IntoIterator` for a type, you define how it will be
2542 /// converted to an iterator. This is common for types which describe a
2543 /// collection of some kind.
2545 /// One benefit of implementing `IntoIterator` is that your type will [work
2546 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2548 /// See also: [`FromIterator`].
2550 /// [`FromIterator`]: trait.FromIterator.html
2557 /// let v = vec![1, 2, 3];
2559 /// let mut iter = v.into_iter();
2561 /// let n = iter.next();
2562 /// assert_eq!(Some(1), n);
2564 /// let n = iter.next();
2565 /// assert_eq!(Some(2), n);
2567 /// let n = iter.next();
2568 /// assert_eq!(Some(3), n);
2570 /// let n = iter.next();
2571 /// assert_eq!(None, n);
2574 /// Implementing `IntoIterator` for your type:
2577 /// // A sample collection, that's just a wrapper over Vec<T>
2578 /// #[derive(Debug)]
2579 /// struct MyCollection(Vec<i32>);
2581 /// // Let's give it some methods so we can create one and add things
2583 /// impl MyCollection {
2584 /// fn new() -> MyCollection {
2585 /// MyCollection(Vec::new())
2588 /// fn add(&mut self, elem: i32) {
2589 /// self.0.push(elem);
2593 /// // and we'll implement IntoIterator
2594 /// impl IntoIterator for MyCollection {
2595 /// type Item = i32;
2596 /// type IntoIter = ::std::vec::IntoIter<i32>;
2598 /// fn into_iter(self) -> Self::IntoIter {
2599 /// self.0.into_iter()
2603 /// // Now we can make a new collection...
2604 /// let mut c = MyCollection::new();
2606 /// // ... add some stuff to it ...
2611 /// // ... and then turn it into an Iterator:
2612 /// for (i, n) in c.into_iter().enumerate() {
2613 /// assert_eq!(i as i32, n);
2616 #[stable(feature = "rust1", since = "1.0.0")]
2617 pub trait IntoIterator {
2618 /// The type of the elements being iterated over.
2619 #[stable(feature = "rust1", since = "1.0.0")]
2622 /// Which kind of iterator are we turning this into?
2623 #[stable(feature = "rust1", since = "1.0.0")]
2624 type IntoIter: Iterator<Item=Self::Item>;
2626 /// Creates an iterator from a value.
2628 /// See the [module-level documentation] for more.
2630 /// [module-level documentation]: trait.IntoIterator.html
2637 /// let v = vec![1, 2, 3];
2639 /// let mut iter = v.into_iter();
2641 /// let n = iter.next();
2642 /// assert_eq!(Some(1), n);
2644 /// let n = iter.next();
2645 /// assert_eq!(Some(2), n);
2647 /// let n = iter.next();
2648 /// assert_eq!(Some(3), n);
2650 /// let n = iter.next();
2651 /// assert_eq!(None, n);
2653 #[stable(feature = "rust1", since = "1.0.0")]
2654 fn into_iter(self) -> Self::IntoIter;
2657 #[stable(feature = "rust1", since = "1.0.0")]
2658 impl<I: Iterator> IntoIterator for I {
2659 type Item = I::Item;
2662 fn into_iter(self) -> I {
2667 /// Extend a collection with the contents of an iterator.
2669 /// Iterators produce a series of values, and collections can also be thought
2670 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2671 /// to extend a collection by including the contents of that iterator.
2678 /// // You can extend a String with some chars:
2679 /// let mut message = String::from("The first three letters are: ");
2681 /// message.extend(&['a', 'b', 'c']);
2683 /// assert_eq!("abc", &message[29..32]);
2686 /// Implementing `Extend`:
2689 /// // A sample collection, that's just a wrapper over Vec<T>
2690 /// #[derive(Debug)]
2691 /// struct MyCollection(Vec<i32>);
2693 /// // Let's give it some methods so we can create one and add things
2695 /// impl MyCollection {
2696 /// fn new() -> MyCollection {
2697 /// MyCollection(Vec::new())
2700 /// fn add(&mut self, elem: i32) {
2701 /// self.0.push(elem);
2705 /// // since MyCollection has a list of i32s, we implement Extend for i32
2706 /// impl Extend<i32> for MyCollection {
2708 /// // This is a bit simpler with the concrete type signature: we can call
2709 /// // extend on anything which can be turned into an Iterator which gives
2710 /// // us i32s. Because we need i32s to put into MyCollection.
2711 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2713 /// // The implementation is very straightforward: loop through the
2714 /// // iterator, and add() each element to ourselves.
2715 /// for elem in iterable {
2721 /// let mut c = MyCollection::new();
2727 /// // let's extend our collection with three more numbers
2728 /// c.extend(vec![1, 2, 3]);
2730 /// // we've added these elements onto the end
2731 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2733 #[stable(feature = "rust1", since = "1.0.0")]
2734 pub trait Extend<A> {
2735 /// Extends a collection with the contents of an iterator.
2737 /// As this is the only method for this trait, the [trait-level] docs
2738 /// contain more details.
2740 /// [trait-level]: trait.Extend.html
2747 /// // You can extend a String with some chars:
2748 /// let mut message = String::from("abc");
2750 /// message.extend(['d', 'e', 'f'].iter());
2752 /// assert_eq!("abcdef", &message);
2754 #[stable(feature = "rust1", since = "1.0.0")]
2755 fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
2758 /// An iterator able to yield elements from both ends.
2760 /// Something that implements `DoubleEndedIterator` has one extra capability
2761 /// over something that implements [`Iterator`]: the ability to also take
2762 /// `Item`s from the back, as well as the front.
2764 /// It is important to note that both back and forth work on the same range,
2765 /// and do not cross: iteration is over when they meet in the middle.
2767 /// In a similar fashion to the [`Iterator`] protocol, once a
2768 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
2769 /// may or may not ever return `Some` again. `next()` and `next_back()` are
2770 /// interchangable for this purpose.
2772 /// [`Iterator`]: trait.Iterator.html
2779 /// let numbers = vec![1, 2, 3];
2781 /// let mut iter = numbers.iter();
2783 /// assert_eq!(Some(&1), iter.next());
2784 /// assert_eq!(Some(&3), iter.next_back());
2785 /// assert_eq!(Some(&2), iter.next_back());
2786 /// assert_eq!(None, iter.next());
2787 /// assert_eq!(None, iter.next_back());
2789 #[stable(feature = "rust1", since = "1.0.0")]
2790 pub trait DoubleEndedIterator: Iterator {
2791 /// An iterator able to yield elements from both ends.
2793 /// As this is the only method for this trait, the [trait-level] docs
2794 /// contain more details.
2796 /// [trait-level]: trait.DoubleEndedIterator.html
2803 /// let numbers = vec![1, 2, 3];
2805 /// let mut iter = numbers.iter();
2807 /// assert_eq!(Some(&1), iter.next());
2808 /// assert_eq!(Some(&3), iter.next_back());
2809 /// assert_eq!(Some(&2), iter.next_back());
2810 /// assert_eq!(None, iter.next());
2811 /// assert_eq!(None, iter.next_back());
2813 #[stable(feature = "rust1", since = "1.0.0")]
2814 fn next_back(&mut self) -> Option<Self::Item>;
2817 #[stable(feature = "rust1", since = "1.0.0")]
2818 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2819 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2822 /// An iterator that knows its exact length.
2824 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2825 /// If an iterator knows how many times it can iterate, providing access to
2826 /// that information can be useful. For example, if you want to iterate
2827 /// backwards, a good start is to know where the end is.
2829 /// When implementing an `ExactSizeIterator`, You must also implement
2830 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2831 /// return the exact size of the iterator.
2833 /// [`Iterator`]: trait.Iterator.html
2834 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2836 /// The [`len()`] method has a default implementation, so you usually shouldn't
2837 /// implement it. However, you may be able to provide a more performant
2838 /// implementation than the default, so overriding it in this case makes sense.
2840 /// [`len()`]: #method.len
2847 /// // a finite range knows exactly how many times it will iterate
2848 /// let five = 0..5;
2850 /// assert_eq!(5, five.len());
2853 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2854 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2856 /// [moddocs]: index.html
2859 /// # struct Counter {
2862 /// # impl Counter {
2863 /// # fn new() -> Counter {
2864 /// # Counter { count: 0 }
2867 /// # impl Iterator for Counter {
2868 /// # type Item = usize;
2869 /// # fn next(&mut self) -> Option<usize> {
2870 /// # self.count += 1;
2871 /// # if self.count < 6 {
2872 /// # Some(self.count)
2878 /// impl ExactSizeIterator for Counter {
2879 /// // We already have the number of iterations, so we can use it directly.
2880 /// fn len(&self) -> usize {
2885 /// // And now we can use it!
2887 /// let counter = Counter::new();
2889 /// assert_eq!(0, counter.len());
2891 #[stable(feature = "rust1", since = "1.0.0")]
2892 pub trait ExactSizeIterator: Iterator {
2894 #[stable(feature = "rust1", since = "1.0.0")]
2895 /// Returns the exact number of times the iterator will iterate.
2897 /// This method has a default implementation, so you usually should not
2898 /// implement it directly. However, if you can provide a more efficient
2899 /// implementation, you can do so. See the [trait-level] docs for an
2902 /// This function has the same safety guarantees as the [`size_hint()`]
2905 /// [trait-level]: trait.ExactSizeIterator.html
2906 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2913 /// // a finite range knows exactly how many times it will iterate
2914 /// let five = 0..5;
2916 /// assert_eq!(5, five.len());
2918 fn len(&self) -> usize {
2919 let (lower, upper) = self.size_hint();
2920 // Note: This assertion is overly defensive, but it checks the invariant
2921 // guaranteed by the trait. If this trait were rust-internal,
2922 // we could use debug_assert!; assert_eq! will check all Rust user
2923 // implementations too.
2924 assert_eq!(upper, Some(lower));
2929 #[stable(feature = "rust1", since = "1.0.0")]
2930 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2932 // All adaptors that preserve the size of the wrapped iterator are fine
2933 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2934 #[stable(feature = "rust1", since = "1.0.0")]
2935 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2936 #[stable(feature = "rust1", since = "1.0.0")]
2937 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2940 #[stable(feature = "rust1", since = "1.0.0")]
2941 impl<I> ExactSizeIterator for Rev<I>
2942 where I: ExactSizeIterator + DoubleEndedIterator {}
2943 #[stable(feature = "rust1", since = "1.0.0")]
2944 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2945 F: FnMut(I::Item) -> B,
2947 #[stable(feature = "rust1", since = "1.0.0")]
2948 impl<A, B> ExactSizeIterator for Zip<A, B>
2949 where A: ExactSizeIterator, B: ExactSizeIterator {}
2951 /// An double-ended iterator with the direction inverted.
2953 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2954 /// documentation for more.
2956 /// [`rev()`]: trait.Iterator.html#method.rev
2957 /// [`Iterator`]: trait.Iterator.html
2959 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2960 #[stable(feature = "rust1", since = "1.0.0")]
2965 #[stable(feature = "rust1", since = "1.0.0")]
2966 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2967 type Item = <I as Iterator>::Item;
2970 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2972 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2975 #[stable(feature = "rust1", since = "1.0.0")]
2976 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2978 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2981 /// An iterator that clones the elements of an underlying iterator.
2983 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2984 /// documentation for more.
2986 /// [`cloned()`]: trait.Iterator.html#method.cloned
2987 /// [`Iterator`]: trait.Iterator.html
2988 #[stable(feature = "iter_cloned", since = "1.1.0")]
2989 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2991 pub struct Cloned<I> {
2995 #[stable(feature = "rust1", since = "1.0.0")]
2996 impl<'a, I, T: 'a> Iterator for Cloned<I>
2997 where I: Iterator<Item=&'a T>, T: Clone
3001 fn next(&mut self) -> Option<T> {
3002 self.it.next().cloned()
3005 fn size_hint(&self) -> (usize, Option<usize>) {
3010 #[stable(feature = "rust1", since = "1.0.0")]
3011 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
3012 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
3014 fn next_back(&mut self) -> Option<T> {
3015 self.it.next_back().cloned()
3019 #[stable(feature = "rust1", since = "1.0.0")]
3020 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
3021 where I: ExactSizeIterator<Item=&'a T>, T: Clone
3024 /// An iterator that repeats endlessly.
3026 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
3027 /// documentation for more.
3029 /// [`cycle()`]: trait.Iterator.html#method.cycle
3030 /// [`Iterator`]: trait.Iterator.html
3032 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3033 #[stable(feature = "rust1", since = "1.0.0")]
3034 pub struct Cycle<I> {
3039 #[stable(feature = "rust1", since = "1.0.0")]
3040 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
3041 type Item = <I as Iterator>::Item;
3044 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3045 match self.iter.next() {
3046 None => { self.iter = self.orig.clone(); self.iter.next() }
3052 fn size_hint(&self) -> (usize, Option<usize>) {
3053 // the cycle iterator is either empty or infinite
3054 match self.orig.size_hint() {
3055 sz @ (0, Some(0)) => sz,
3056 (0, _) => (0, None),
3057 _ => (usize::MAX, None)
3062 /// An iterator that strings two iterators together.
3064 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
3065 /// documentation for more.
3067 /// [`chain()`]: trait.Iterator.html#method.chain
3068 /// [`Iterator`]: trait.Iterator.html
3070 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3071 #[stable(feature = "rust1", since = "1.0.0")]
3072 pub struct Chain<A, B> {
3078 // The iterator protocol specifies that iteration ends with the return value
3079 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
3080 // further calls return. The chain adaptor must account for this since it uses
3081 // two subiterators.
3083 // It uses three states:
3085 // - Both: `a` and `b` are remaining
3086 // - Front: `a` remaining
3087 // - Back: `b` remaining
3089 // The fourth state (neither iterator is remaining) only occurs after Chain has
3090 // returned None once, so we don't need to store this state.
3093 // both front and back iterator are remaining
3095 // only front is remaining
3097 // only back is remaining
3101 #[stable(feature = "rust1", since = "1.0.0")]
3102 impl<A, B> Iterator for Chain<A, B> where
3104 B: Iterator<Item = A::Item>
3106 type Item = A::Item;
3109 fn next(&mut self) -> Option<A::Item> {
3111 ChainState::Both => match self.a.next() {
3112 elt @ Some(..) => elt,
3114 self.state = ChainState::Back;
3118 ChainState::Front => self.a.next(),
3119 ChainState::Back => self.b.next(),
3124 fn count(self) -> usize {
3126 ChainState::Both => self.a.count() + self.b.count(),
3127 ChainState::Front => self.a.count(),
3128 ChainState::Back => self.b.count(),
3133 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
3135 ChainState::Both | ChainState::Front => {
3136 for x in self.a.by_ref() {
3142 if let ChainState::Both = self.state {
3143 self.state = ChainState::Back;
3146 ChainState::Back => {}
3148 if let ChainState::Back = self.state {
3156 fn last(self) -> Option<A::Item> {
3158 ChainState::Both => {
3159 // Must exhaust a before b.
3160 let a_last = self.a.last();
3161 let b_last = self.b.last();
3164 ChainState::Front => self.a.last(),
3165 ChainState::Back => self.b.last()
3170 fn size_hint(&self) -> (usize, Option<usize>) {
3171 let (a_lower, a_upper) = self.a.size_hint();
3172 let (b_lower, b_upper) = self.b.size_hint();
3174 let lower = a_lower.saturating_add(b_lower);
3176 let upper = match (a_upper, b_upper) {
3177 (Some(x), Some(y)) => x.checked_add(y),
3185 #[stable(feature = "rust1", since = "1.0.0")]
3186 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3187 A: DoubleEndedIterator,
3188 B: DoubleEndedIterator<Item=A::Item>,
3191 fn next_back(&mut self) -> Option<A::Item> {
3193 ChainState::Both => match self.b.next_back() {
3194 elt @ Some(..) => elt,
3196 self.state = ChainState::Front;
3200 ChainState::Front => self.a.next_back(),
3201 ChainState::Back => self.b.next_back(),
3206 /// An iterator that iterates two other iterators simultaneously.
3208 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3209 /// documentation for more.
3211 /// [`zip()`]: trait.Iterator.html#method.zip
3212 /// [`Iterator`]: trait.Iterator.html
3214 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3215 #[stable(feature = "rust1", since = "1.0.0")]
3216 pub struct Zip<A, B> {
3221 #[stable(feature = "rust1", since = "1.0.0")]
3222 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3224 type Item = (A::Item, B::Item);
3227 fn next(&mut self) -> Option<(A::Item, B::Item)> {
3228 self.a.next().and_then(|x| {
3229 self.b.next().and_then(|y| {
3236 fn size_hint(&self) -> (usize, Option<usize>) {
3237 let (a_lower, a_upper) = self.a.size_hint();
3238 let (b_lower, b_upper) = self.b.size_hint();
3240 let lower = cmp::min(a_lower, b_lower);
3242 let upper = match (a_upper, b_upper) {
3243 (Some(x), Some(y)) => Some(cmp::min(x,y)),
3244 (Some(x), None) => Some(x),
3245 (None, Some(y)) => Some(y),
3246 (None, None) => None
3253 #[stable(feature = "rust1", since = "1.0.0")]
3254 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3255 A: DoubleEndedIterator + ExactSizeIterator,
3256 B: DoubleEndedIterator + ExactSizeIterator,
3259 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3260 let a_sz = self.a.len();
3261 let b_sz = self.b.len();
3263 // Adjust a, b to equal length
3265 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3267 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3270 match (self.a.next_back(), self.b.next_back()) {
3271 (Some(x), Some(y)) => Some((x, y)),
3272 (None, None) => None,
3273 _ => unreachable!(),
3278 /// An iterator that maps the values of `iter` with `f`.
3280 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3281 /// documentation for more.
3283 /// [`map()`]: trait.Iterator.html#method.map
3284 /// [`Iterator`]: trait.Iterator.html
3286 /// # Notes about side effects
3288 /// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
3289 /// you can also [`map()`] backwards:
3292 /// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
3294 /// assert_eq!(v, [4, 3, 2]);
3297 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
3299 /// But if your closure has state, iterating backwards may act in a way you do
3300 /// not expect. Let's go through an example. First, in the forward direction:
3305 /// for pair in vec!['a', 'b', 'c'].into_iter()
3306 /// .map(|letter| { c += 1; (letter, c) }) {
3307 /// println!("{:?}", pair);
3311 /// This will print "('a', 1), ('b', 2), ('c', 3)".
3313 /// Now consider this twist where we add a call to `rev`. This version will
3314 /// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
3315 /// but the values of the counter still go in order. This is because `map()` is
3316 /// still being called lazilly on each item, but we are popping items off the
3317 /// back of the vector now, instead of shifting them from the front.
3322 /// for pair in vec!['a', 'b', 'c'].into_iter()
3323 /// .map(|letter| { c += 1; (letter, c) })
3325 /// println!("{:?}", pair);
3328 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3329 #[stable(feature = "rust1", since = "1.0.0")]
3331 pub struct Map<I, F> {
3336 #[stable(feature = "rust1", since = "1.0.0")]
3337 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3341 fn next(&mut self) -> Option<B> {
3342 self.iter.next().map(&mut self.f)
3346 fn size_hint(&self) -> (usize, Option<usize>) {
3347 self.iter.size_hint()
3351 #[stable(feature = "rust1", since = "1.0.0")]
3352 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3353 F: FnMut(I::Item) -> B,
3356 fn next_back(&mut self) -> Option<B> {
3357 self.iter.next_back().map(&mut self.f)
3361 /// An iterator that filters the elements of `iter` with `predicate`.
3363 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3364 /// documentation for more.
3366 /// [`filter()`]: trait.Iterator.html#method.filter
3367 /// [`Iterator`]: trait.Iterator.html
3368 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3369 #[stable(feature = "rust1", since = "1.0.0")]
3371 pub struct Filter<I, P> {
3376 #[stable(feature = "rust1", since = "1.0.0")]
3377 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3378 type Item = I::Item;
3381 fn next(&mut self) -> Option<I::Item> {
3382 for x in self.iter.by_ref() {
3383 if (self.predicate)(&x) {
3391 fn size_hint(&self) -> (usize, Option<usize>) {
3392 let (_, upper) = self.iter.size_hint();
3393 (0, upper) // can't know a lower bound, due to the predicate
3397 #[stable(feature = "rust1", since = "1.0.0")]
3398 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3399 where P: FnMut(&I::Item) -> bool,
3402 fn next_back(&mut self) -> Option<I::Item> {
3403 for x in self.iter.by_ref().rev() {
3404 if (self.predicate)(&x) {
3412 /// An iterator that uses `f` to both filter and map elements from `iter`.
3414 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3415 /// documentation for more.
3417 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3418 /// [`Iterator`]: trait.Iterator.html
3419 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3420 #[stable(feature = "rust1", since = "1.0.0")]
3422 pub struct FilterMap<I, F> {
3427 #[stable(feature = "rust1", since = "1.0.0")]
3428 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3429 where F: FnMut(I::Item) -> Option<B>,
3434 fn next(&mut self) -> Option<B> {
3435 for x in self.iter.by_ref() {
3436 if let Some(y) = (self.f)(x) {
3444 fn size_hint(&self) -> (usize, Option<usize>) {
3445 let (_, upper) = self.iter.size_hint();
3446 (0, upper) // can't know a lower bound, due to the predicate
3450 #[stable(feature = "rust1", since = "1.0.0")]
3451 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3452 where F: FnMut(I::Item) -> Option<B>,
3455 fn next_back(&mut self) -> Option<B> {
3456 for x in self.iter.by_ref().rev() {
3457 if let Some(y) = (self.f)(x) {
3465 /// An iterator that yields the current count and the element during iteration.
3467 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3468 /// documentation for more.
3470 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3471 /// [`Iterator`]: trait.Iterator.html
3473 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3474 #[stable(feature = "rust1", since = "1.0.0")]
3475 pub struct Enumerate<I> {
3480 #[stable(feature = "rust1", since = "1.0.0")]
3481 impl<I> Iterator for Enumerate<I> where I: Iterator {
3482 type Item = (usize, <I as Iterator>::Item);
3484 /// # Overflow Behavior
3486 /// The method does no guarding against overflows, so enumerating more than
3487 /// `usize::MAX` elements either produces the wrong result or panics. If
3488 /// debug assertions are enabled, a panic is guaranteed.
3492 /// Might panic if the index of the element overflows a `usize`.
3494 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3495 self.iter.next().map(|a| {
3496 let ret = (self.count, a);
3497 // Possible undefined overflow.
3504 fn size_hint(&self) -> (usize, Option<usize>) {
3505 self.iter.size_hint()
3509 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3510 self.iter.nth(n).map(|a| {
3511 let i = self.count + n;
3518 fn count(self) -> usize {
3523 #[stable(feature = "rust1", since = "1.0.0")]
3524 impl<I> DoubleEndedIterator for Enumerate<I> where
3525 I: ExactSizeIterator + DoubleEndedIterator
3528 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3529 self.iter.next_back().map(|a| {
3530 let len = self.iter.len();
3531 // Can safely add, `ExactSizeIterator` promises that the number of
3532 // elements fits into a `usize`.
3533 (self.count + len, a)
3538 /// An iterator with a `peek()` that returns an optional reference to the next
3541 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3542 /// documentation for more.
3544 /// [`peekable()`]: trait.Iterator.html#method.peekable
3545 /// [`Iterator`]: trait.Iterator.html
3547 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3548 #[stable(feature = "rust1", since = "1.0.0")]
3549 pub struct Peekable<I: Iterator> {
3551 peeked: Option<I::Item>,
3554 #[stable(feature = "rust1", since = "1.0.0")]
3555 impl<I: Iterator> Iterator for Peekable<I> {
3556 type Item = I::Item;
3559 fn next(&mut self) -> Option<I::Item> {
3561 Some(_) => self.peeked.take(),
3562 None => self.iter.next(),
3567 fn count(self) -> usize {
3568 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3572 fn nth(&mut self, n: usize) -> Option<I::Item> {
3574 Some(_) if n == 0 => self.peeked.take(),
3579 None => self.iter.nth(n)
3584 fn last(self) -> Option<I::Item> {
3585 self.iter.last().or(self.peeked)
3589 fn size_hint(&self) -> (usize, Option<usize>) {
3590 let (lo, hi) = self.iter.size_hint();
3591 if self.peeked.is_some() {
3592 let lo = lo.saturating_add(1);
3593 let hi = hi.and_then(|x| x.checked_add(1));
3601 #[stable(feature = "rust1", since = "1.0.0")]
3602 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3604 impl<I: Iterator> Peekable<I> {
3605 /// Returns a reference to the next() value without advancing the iterator.
3607 /// The `peek()` method will return the value that a call to [`next()`] would
3608 /// return, but does not advance the iterator. Like [`next()`], if there is
3609 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3610 /// will return `None`.
3612 /// [`next()`]: trait.Iterator.html#tymethod.next
3614 /// Because `peek()` returns reference, and many iterators iterate over
3615 /// references, this leads to a possibly confusing situation where the
3616 /// return value is a double reference. You can see this effect in the
3617 /// examples below, with `&&i32`.
3624 /// let xs = [1, 2, 3];
3626 /// let mut iter = xs.iter().peekable();
3628 /// // peek() lets us see into the future
3629 /// assert_eq!(iter.peek(), Some(&&1));
3630 /// assert_eq!(iter.next(), Some(&1));
3632 /// assert_eq!(iter.next(), Some(&2));
3634 /// // we can peek() multiple times, the iterator won't advance
3635 /// assert_eq!(iter.peek(), Some(&&3));
3636 /// assert_eq!(iter.peek(), Some(&&3));
3638 /// assert_eq!(iter.next(), Some(&3));
3640 /// // after the iterator is finished, so is peek()
3641 /// assert_eq!(iter.peek(), None);
3642 /// assert_eq!(iter.next(), None);
3645 #[stable(feature = "rust1", since = "1.0.0")]
3646 pub fn peek(&mut self) -> Option<&I::Item> {
3647 if self.peeked.is_none() {
3648 self.peeked = self.iter.next();
3651 Some(ref value) => Some(value),
3656 /// Checks if the iterator has finished iterating.
3658 /// Returns `true` if there are no more elements in the iterator, and
3659 /// `false` if there are.
3666 /// #![feature(peekable_is_empty)]
3668 /// let xs = [1, 2, 3];
3670 /// let mut iter = xs.iter().peekable();
3672 /// // there are still elements to iterate over
3673 /// assert_eq!(iter.is_empty(), false);
3675 /// // let's consume the iterator
3680 /// assert_eq!(iter.is_empty(), true);
3682 #[unstable(feature = "peekable_is_empty", issue = "27701")]
3684 pub fn is_empty(&mut self) -> bool {
3685 self.peek().is_none()
3689 /// An iterator that rejects elements while `predicate` is true.
3691 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3692 /// documentation for more.
3694 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3695 /// [`Iterator`]: trait.Iterator.html
3696 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3697 #[stable(feature = "rust1", since = "1.0.0")]
3699 pub struct SkipWhile<I, P> {
3705 #[stable(feature = "rust1", since = "1.0.0")]
3706 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3707 where P: FnMut(&I::Item) -> bool
3709 type Item = I::Item;
3712 fn next(&mut self) -> Option<I::Item> {
3713 for x in self.iter.by_ref() {
3714 if self.flag || !(self.predicate)(&x) {
3723 fn size_hint(&self) -> (usize, Option<usize>) {
3724 let (_, upper) = self.iter.size_hint();
3725 (0, upper) // can't know a lower bound, due to the predicate
3729 /// An iterator that only accepts elements while `predicate` is true.
3731 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3732 /// documentation for more.
3734 /// [`take_while()`]: trait.Iterator.html#method.take_while
3735 /// [`Iterator`]: trait.Iterator.html
3736 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3737 #[stable(feature = "rust1", since = "1.0.0")]
3739 pub struct TakeWhile<I, P> {
3745 #[stable(feature = "rust1", since = "1.0.0")]
3746 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3747 where P: FnMut(&I::Item) -> bool
3749 type Item = I::Item;
3752 fn next(&mut self) -> Option<I::Item> {
3756 self.iter.next().and_then(|x| {
3757 if (self.predicate)(&x) {
3768 fn size_hint(&self) -> (usize, Option<usize>) {
3769 let (_, upper) = self.iter.size_hint();
3770 (0, upper) // can't know a lower bound, due to the predicate
3774 /// An iterator that skips over `n` elements of `iter`.
3776 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3777 /// documentation for more.
3779 /// [`skip()`]: trait.Iterator.html#method.skip
3780 /// [`Iterator`]: trait.Iterator.html
3782 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3783 #[stable(feature = "rust1", since = "1.0.0")]
3784 pub struct Skip<I> {
3789 #[stable(feature = "rust1", since = "1.0.0")]
3790 impl<I> Iterator for Skip<I> where I: Iterator {
3791 type Item = <I as Iterator>::Item;
3794 fn next(&mut self) -> Option<I::Item> {
3800 self.iter.nth(old_n)
3805 fn nth(&mut self, n: usize) -> Option<I::Item> {
3806 // Can't just add n + self.n due to overflow.
3810 let to_skip = self.n;
3813 if self.iter.nth(to_skip-1).is_none() {
3821 fn count(self) -> usize {
3822 self.iter.count().saturating_sub(self.n)
3826 fn last(mut self) -> Option<I::Item> {
3830 let next = self.next();
3832 // recurse. n should be 0.
3833 self.last().or(next)
3841 fn size_hint(&self) -> (usize, Option<usize>) {
3842 let (lower, upper) = self.iter.size_hint();
3844 let lower = lower.saturating_sub(self.n);
3845 let upper = upper.map(|x| x.saturating_sub(self.n));
3851 #[stable(feature = "rust1", since = "1.0.0")]
3852 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3854 /// An iterator that only iterates over the first `n` iterations of `iter`.
3856 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3857 /// documentation for more.
3859 /// [`take()`]: trait.Iterator.html#method.take
3860 /// [`Iterator`]: trait.Iterator.html
3862 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3863 #[stable(feature = "rust1", since = "1.0.0")]
3864 pub struct Take<I> {
3869 #[stable(feature = "rust1", since = "1.0.0")]
3870 impl<I> Iterator for Take<I> where I: Iterator{
3871 type Item = <I as Iterator>::Item;
3874 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3884 fn nth(&mut self, n: usize) -> Option<I::Item> {
3890 self.iter.nth(self.n - 1);
3898 fn size_hint(&self) -> (usize, Option<usize>) {
3899 let (lower, upper) = self.iter.size_hint();
3901 let lower = cmp::min(lower, self.n);
3903 let upper = match upper {
3904 Some(x) if x < self.n => Some(x),
3912 #[stable(feature = "rust1", since = "1.0.0")]
3913 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3916 /// An iterator to maintain state while iterating another iterator.
3918 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3919 /// documentation for more.
3921 /// [`scan()`]: trait.Iterator.html#method.scan
3922 /// [`Iterator`]: trait.Iterator.html
3923 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3924 #[stable(feature = "rust1", since = "1.0.0")]
3926 pub struct Scan<I, St, F> {
3932 #[stable(feature = "rust1", since = "1.0.0")]
3933 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3935 F: FnMut(&mut St, I::Item) -> Option<B>,
3940 fn next(&mut self) -> Option<B> {
3941 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3945 fn size_hint(&self) -> (usize, Option<usize>) {
3946 let (_, upper) = self.iter.size_hint();
3947 (0, upper) // can't know a lower bound, due to the scan function
3951 /// An iterator that maps each element to an iterator, and yields the elements
3952 /// of the produced iterators.
3954 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3955 /// documentation for more.
3957 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
3958 /// [`Iterator`]: trait.Iterator.html
3959 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3960 #[stable(feature = "rust1", since = "1.0.0")]
3962 pub struct FlatMap<I, U: IntoIterator, F> {
3965 frontiter: Option<U::IntoIter>,
3966 backiter: Option<U::IntoIter>,
3969 #[stable(feature = "rust1", since = "1.0.0")]
3970 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
3971 where F: FnMut(I::Item) -> U,
3973 type Item = U::Item;
3976 fn next(&mut self) -> Option<U::Item> {
3978 if let Some(ref mut inner) = self.frontiter {
3979 if let Some(x) = inner.by_ref().next() {
3983 match self.iter.next().map(&mut self.f) {
3984 None => return self.backiter.as_mut().and_then(|it| it.next()),
3985 next => self.frontiter = next.map(IntoIterator::into_iter),
3991 fn size_hint(&self) -> (usize, Option<usize>) {
3992 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3993 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3994 let lo = flo.saturating_add(blo);
3995 match (self.iter.size_hint(), fhi, bhi) {
3996 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
4002 #[stable(feature = "rust1", since = "1.0.0")]
4003 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
4004 F: FnMut(I::Item) -> U,
4006 U::IntoIter: DoubleEndedIterator
4009 fn next_back(&mut self) -> Option<U::Item> {
4011 if let Some(ref mut inner) = self.backiter {
4012 if let Some(y) = inner.next_back() {
4016 match self.iter.next_back().map(&mut self.f) {
4017 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
4018 next => self.backiter = next.map(IntoIterator::into_iter),
4024 /// An iterator that yields `None` forever after the underlying iterator
4025 /// yields `None` once.
4027 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
4028 /// documentation for more.
4030 /// [`fuse()`]: trait.Iterator.html#method.fuse
4031 /// [`Iterator`]: trait.Iterator.html
4033 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4034 #[stable(feature = "rust1", since = "1.0.0")]
4035 pub struct Fuse<I> {
4040 #[stable(feature = "rust1", since = "1.0.0")]
4041 impl<I> Iterator for Fuse<I> where I: Iterator {
4042 type Item = <I as Iterator>::Item;
4045 fn next(&mut self) -> Option<<I as Iterator>::Item> {
4049 let next = self.iter.next();
4050 self.done = next.is_none();
4056 fn nth(&mut self, n: usize) -> Option<I::Item> {
4060 let nth = self.iter.nth(n);
4061 self.done = nth.is_none();
4067 fn last(self) -> Option<I::Item> {
4076 fn count(self) -> usize {
4085 fn size_hint(&self) -> (usize, Option<usize>) {
4089 self.iter.size_hint()
4094 #[stable(feature = "rust1", since = "1.0.0")]
4095 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
4097 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
4101 let next = self.iter.next_back();
4102 self.done = next.is_none();
4108 #[stable(feature = "rust1", since = "1.0.0")]
4109 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
4111 /// An iterator that calls a function with a reference to each element before
4114 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
4115 /// documentation for more.
4117 /// [`inspect()`]: trait.Iterator.html#method.inspect
4118 /// [`Iterator`]: trait.Iterator.html
4119 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4120 #[stable(feature = "rust1", since = "1.0.0")]
4122 pub struct Inspect<I, F> {
4127 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
4129 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
4130 if let Some(ref a) = elt {
4138 #[stable(feature = "rust1", since = "1.0.0")]
4139 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
4140 type Item = I::Item;
4143 fn next(&mut self) -> Option<I::Item> {
4144 let next = self.iter.next();
4145 self.do_inspect(next)
4149 fn size_hint(&self) -> (usize, Option<usize>) {
4150 self.iter.size_hint()
4154 #[stable(feature = "rust1", since = "1.0.0")]
4155 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
4156 where F: FnMut(&I::Item),
4159 fn next_back(&mut self) -> Option<I::Item> {
4160 let next = self.iter.next_back();
4161 self.do_inspect(next)
4165 /// Objects that can be stepped over in both directions.
4167 /// The `steps_between` function provides a way to efficiently compare
4168 /// two `Step` objects.
4169 #[unstable(feature = "step_trait",
4170 reason = "likely to be replaced by finer-grained traits",
4172 pub trait Step: PartialOrd + Sized {
4173 /// Steps `self` if possible.
4174 fn step(&self, by: &Self) -> Option<Self>;
4176 /// Returns the number of steps between two step objects. The count is
4177 /// inclusive of `start` and exclusive of `end`.
4179 /// Returns `None` if it is not possible to calculate `steps_between`
4180 /// without overflow.
4181 fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
4184 macro_rules! step_impl_unsigned {
4186 #[unstable(feature = "step_trait",
4187 reason = "likely to be replaced by finer-grained traits",
4191 fn step(&self, by: &$t) -> Option<$t> {
4192 (*self).checked_add(*by)
4195 #[allow(trivial_numeric_casts)]
4196 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4197 if *by == 0 { return None; }
4199 // Note: We assume $t <= usize here
4200 let diff = (*end - *start) as usize;
4201 let by = *by as usize;
4214 macro_rules! step_impl_signed {
4216 #[unstable(feature = "step_trait",
4217 reason = "likely to be replaced by finer-grained traits",
4221 fn step(&self, by: &$t) -> Option<$t> {
4222 (*self).checked_add(*by)
4225 #[allow(trivial_numeric_casts)]
4226 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4227 if *by == 0 { return None; }
4234 // Note: We assume $t <= isize here
4235 // Use .wrapping_sub and cast to usize to compute the
4236 // difference that may not fit inside the range of isize.
4237 diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4238 by_u = *by as usize;
4243 diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4244 by_u = (*by as isize).wrapping_mul(-1) as usize;
4246 if diff % by_u > 0 {
4247 Some(diff / by_u + 1)
4256 macro_rules! step_impl_no_between {
4258 #[unstable(feature = "step_trait",
4259 reason = "likely to be replaced by finer-grained traits",
4263 fn step(&self, by: &$t) -> Option<$t> {
4264 (*self).checked_add(*by)
4267 fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4274 step_impl_unsigned!(usize u8 u16 u32);
4275 step_impl_signed!(isize i8 i16 i32);
4276 #[cfg(target_pointer_width = "64")]
4277 step_impl_unsigned!(u64);
4278 #[cfg(target_pointer_width = "64")]
4279 step_impl_signed!(i64);
4280 // If the target pointer width is not 64-bits, we
4281 // assume here that it is less than 64-bits.
4282 #[cfg(not(target_pointer_width = "64"))]
4283 step_impl_no_between!(u64 i64);
4285 /// An adapter for stepping range iterators by a custom amount.
4287 /// The resulting iterator handles overflow by stopping. The `A`
4288 /// parameter is the type being iterated over, while `R` is the range
4289 /// type (usually one of `std::ops::{Range, RangeFrom, RangeInclusive}`.
4291 #[unstable(feature = "step_by", reason = "recent addition",
4293 pub struct StepBy<A, R> {
4298 impl<A: Step> ops::RangeFrom<A> {
4299 /// Creates an iterator starting at the same point, but stepping by
4300 /// the given amount at each iteration.
4305 /// # #![feature(step_by)]
4307 /// for i in (0u8..).step_by(2).take(10) {
4308 /// println!("{}", i);
4312 /// This prints the first ten even natural integers (0 to 18).
4313 #[unstable(feature = "step_by", reason = "recent addition",
4315 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4323 impl<A: Step> ops::Range<A> {
4324 /// Creates an iterator with the same range, but stepping by the
4325 /// given amount at each iteration.
4327 /// The resulting iterator handles overflow by stopping.
4332 /// #![feature(step_by)]
4334 /// for i in (0..10).step_by(2) {
4335 /// println!("{}", i);
4348 #[unstable(feature = "step_by", reason = "recent addition",
4350 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4358 impl<A: Step> ops::RangeInclusive<A> {
4359 /// Creates an iterator with the same range, but stepping by the
4360 /// given amount at each iteration.
4362 /// The resulting iterator handles overflow by stopping.
4367 /// #![feature(step_by, inclusive_range_syntax)]
4369 /// for i in (0...10).step_by(2) {
4370 /// println!("{}", i);
4384 #[unstable(feature = "step_by", reason = "recent addition",
4386 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4394 #[stable(feature = "rust1", since = "1.0.0")]
4395 impl<A> Iterator for StepBy<A, ops::RangeFrom<A>> where
4397 for<'a> &'a A: Add<&'a A, Output = A>
4402 fn next(&mut self) -> Option<A> {
4403 let mut n = &self.range.start + &self.step_by;
4404 mem::swap(&mut n, &mut self.range.start);
4409 fn size_hint(&self) -> (usize, Option<usize>) {
4410 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4414 #[stable(feature = "rust1", since = "1.0.0")]
4415 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4419 fn next(&mut self) -> Option<A> {
4420 let rev = self.step_by < A::zero();
4421 if (rev && self.range.start > self.range.end) ||
4422 (!rev && self.range.start < self.range.end)
4424 match self.range.start.step(&self.step_by) {
4426 mem::swap(&mut self.range.start, &mut n);
4430 let mut n = self.range.end.clone();
4431 mem::swap(&mut self.range.start, &mut n);
4441 fn size_hint(&self) -> (usize, Option<usize>) {
4442 match Step::steps_between(&self.range.start,
4445 Some(hint) => (hint, Some(hint)),
4451 #[unstable(feature = "inclusive_range",
4452 reason = "recently added, follows RFC",
4454 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::RangeInclusive<A>> {
4458 fn next(&mut self) -> Option<A> {
4459 use ops::RangeInclusive::*;
4461 // this function has a sort of odd structure due to borrowck issues
4462 // we may need to replace self.range, so borrows of start and end need to end early
4464 let (finishing, n) = match self.range {
4465 Empty { .. } => return None, // empty iterators yield no values
4467 NonEmpty { ref mut start, ref mut end } => {
4468 let zero = A::zero();
4469 let rev = self.step_by < zero;
4471 // march start towards (maybe past!) end and yield the old value
4472 if (rev && start >= end) ||
4473 (!rev && start <= end)
4475 match start.step(&self.step_by) {
4477 mem::swap(start, &mut n);
4478 (None, Some(n)) // yield old value, remain non-empty
4481 let mut n = end.clone();
4482 mem::swap(start, &mut n);
4483 (None, Some(n)) // yield old value, remain non-empty
4487 // found range in inconsistent state (start at or past end), so become empty
4488 (Some(mem::replace(end, zero)), None)
4493 // turn into an empty iterator if we've reached the end
4494 if let Some(end) = finishing {
4495 self.range = Empty { at: end };
4502 fn size_hint(&self) -> (usize, Option<usize>) {
4503 use ops::RangeInclusive::*;
4506 Empty { .. } => (0, Some(0)),
4508 NonEmpty { ref start, ref end } =>
4509 match Step::steps_between(start,
4512 Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
4519 macro_rules! range_exact_iter_impl {
4521 #[stable(feature = "rust1", since = "1.0.0")]
4522 impl ExactSizeIterator for ops::Range<$t> { }
4524 #[unstable(feature = "inclusive_range",
4525 reason = "recently added, follows RFC",
4527 impl ExactSizeIterator for ops::RangeInclusive<$t> { }
4531 #[stable(feature = "rust1", since = "1.0.0")]
4532 impl<A: Step + One> Iterator for ops::Range<A> where
4533 for<'a> &'a A: Add<&'a A, Output = A>
4538 fn next(&mut self) -> Option<A> {
4539 if self.start < self.end {
4540 let mut n = &self.start + &A::one();
4541 mem::swap(&mut n, &mut self.start);
4549 fn size_hint(&self) -> (usize, Option<usize>) {
4550 match Step::steps_between(&self.start, &self.end, &A::one()) {
4551 Some(hint) => (hint, Some(hint)),
4557 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4558 // a length <= usize::MAX, which is required by ExactSizeIterator.
4559 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4561 #[stable(feature = "rust1", since = "1.0.0")]
4562 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4563 for<'a> &'a A: Add<&'a A, Output = A>,
4564 for<'a> &'a A: Sub<&'a A, Output = A>
4567 fn next_back(&mut self) -> Option<A> {
4568 if self.start < self.end {
4569 self.end = &self.end - &A::one();
4570 Some(self.end.clone())
4577 #[stable(feature = "rust1", since = "1.0.0")]
4578 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4579 for<'a> &'a A: Add<&'a A, Output = A>
4584 fn next(&mut self) -> Option<A> {
4585 let mut n = &self.start + &A::one();
4586 mem::swap(&mut n, &mut self.start);
4591 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
4592 impl<A: Step + One> Iterator for ops::RangeInclusive<A> where
4593 for<'a> &'a A: Add<&'a A, Output = A>
4598 fn next(&mut self) -> Option<A> {
4599 use ops::RangeInclusive::*;
4601 // this function has a sort of odd structure due to borrowck issues
4602 // we may need to replace self, so borrows of self.start and self.end need to end early
4604 let (finishing, n) = match *self {
4605 Empty { .. } => (None, None), // empty iterators yield no values
4607 NonEmpty { ref mut start, ref mut end } => {
4610 let mut n = &*start + &one;
4611 mem::swap(&mut n, start);
4613 // if the iterator is done iterating, it will change from NonEmpty to Empty
4614 // to avoid unnecessary drops or clones, we'll reuse either start or end
4615 // (they are equal now, so it doesn't matter which)
4616 // to pull out end, we need to swap something back in -- use the previously
4617 // created A::one() as a dummy value
4619 (if n == *end { Some(mem::replace(end, one)) } else { None },
4620 // ^ are we done yet?
4621 Some(n)) // < the value to output
4623 (Some(mem::replace(start, one)), None)
4628 // turn into an empty iterator if this is the last value
4629 if let Some(end) = finishing {
4630 *self = Empty { at: end };
4637 fn size_hint(&self) -> (usize, Option<usize>) {
4638 use ops::RangeInclusive::*;
4641 Empty { .. } => (0, Some(0)),
4643 NonEmpty { ref start, ref end } =>
4644 match Step::steps_between(start, end, &A::one()) {
4645 Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
4652 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
4653 impl<A: Step + One> DoubleEndedIterator for ops::RangeInclusive<A> where
4654 for<'a> &'a A: Add<&'a A, Output = A>,
4655 for<'a> &'a A: Sub<&'a A, Output = A>
4658 fn next_back(&mut self) -> Option<A> {
4659 use ops::RangeInclusive::*;
4661 // see Iterator::next for comments
4663 let (finishing, n) = match *self {
4664 Empty { .. } => return None,
4666 NonEmpty { ref mut start, ref mut end } => {
4669 let mut n = &*end - &one;
4670 mem::swap(&mut n, end);
4672 (if n == *start { Some(mem::replace(start, one)) } else { None },
4675 (Some(mem::replace(end, one)), None)
4680 if let Some(start) = finishing {
4681 *self = Empty { at: start };
4688 /// An iterator that repeats an element endlessly.
4690 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4692 /// [`repeat()`]: fn.repeat.html
4694 #[stable(feature = "rust1", since = "1.0.0")]
4695 pub struct Repeat<A> {
4699 #[stable(feature = "rust1", since = "1.0.0")]
4700 impl<A: Clone> Iterator for Repeat<A> {
4704 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4706 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4709 #[stable(feature = "rust1", since = "1.0.0")]
4710 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4712 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4715 /// Creates a new iterator that endlessly repeats a single element.
4717 /// The `repeat()` function repeats a single value over and over and over and
4718 /// over and over and 🔁.
4720 /// Infinite iterators like `repeat()` are often used with adapters like
4721 /// [`take()`], in order to make them finite.
4723 /// [`take()`]: trait.Iterator.html#method.take
4732 /// // the number four 4ever:
4733 /// let mut fours = iter::repeat(4);
4735 /// assert_eq!(Some(4), fours.next());
4736 /// assert_eq!(Some(4), fours.next());
4737 /// assert_eq!(Some(4), fours.next());
4738 /// assert_eq!(Some(4), fours.next());
4739 /// assert_eq!(Some(4), fours.next());
4741 /// // yup, still four
4742 /// assert_eq!(Some(4), fours.next());
4745 /// Going finite with [`take()`]:
4750 /// // that last example was too many fours. Let's only have four fours.
4751 /// let mut four_fours = iter::repeat(4).take(4);
4753 /// assert_eq!(Some(4), four_fours.next());
4754 /// assert_eq!(Some(4), four_fours.next());
4755 /// assert_eq!(Some(4), four_fours.next());
4756 /// assert_eq!(Some(4), four_fours.next());
4758 /// // ... and now we're done
4759 /// assert_eq!(None, four_fours.next());
4762 #[stable(feature = "rust1", since = "1.0.0")]
4763 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4764 Repeat{element: elt}
4767 /// An iterator that yields nothing.
4769 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4771 /// [`empty()`]: fn.empty.html
4772 #[stable(feature = "iter_empty", since = "1.2.0")]
4773 pub struct Empty<T>(marker::PhantomData<T>);
4775 #[stable(feature = "iter_empty", since = "1.2.0")]
4776 impl<T> Iterator for Empty<T> {
4779 fn next(&mut self) -> Option<T> {
4783 fn size_hint(&self) -> (usize, Option<usize>){
4788 #[stable(feature = "iter_empty", since = "1.2.0")]
4789 impl<T> DoubleEndedIterator for Empty<T> {
4790 fn next_back(&mut self) -> Option<T> {
4795 #[stable(feature = "iter_empty", since = "1.2.0")]
4796 impl<T> ExactSizeIterator for Empty<T> {
4797 fn len(&self) -> usize {
4802 // not #[derive] because that adds a Clone bound on T,
4803 // which isn't necessary.
4804 #[stable(feature = "iter_empty", since = "1.2.0")]
4805 impl<T> Clone for Empty<T> {
4806 fn clone(&self) -> Empty<T> {
4807 Empty(marker::PhantomData)
4811 // not #[derive] because that adds a Default bound on T,
4812 // which isn't necessary.
4813 #[stable(feature = "iter_empty", since = "1.2.0")]
4814 impl<T> Default for Empty<T> {
4815 fn default() -> Empty<T> {
4816 Empty(marker::PhantomData)
4820 /// Creates an iterator that yields nothing.
4829 /// // this could have been an iterator over i32, but alas, it's just not.
4830 /// let mut nope = iter::empty::<i32>();
4832 /// assert_eq!(None, nope.next());
4834 #[stable(feature = "iter_empty", since = "1.2.0")]
4835 pub fn empty<T>() -> Empty<T> {
4836 Empty(marker::PhantomData)
4839 /// An iterator that yields an element exactly once.
4841 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4843 /// [`once()`]: fn.once.html
4845 #[stable(feature = "iter_once", since = "1.2.0")]
4846 pub struct Once<T> {
4847 inner: ::option::IntoIter<T>
4850 #[stable(feature = "iter_once", since = "1.2.0")]
4851 impl<T> Iterator for Once<T> {
4854 fn next(&mut self) -> Option<T> {
4858 fn size_hint(&self) -> (usize, Option<usize>) {
4859 self.inner.size_hint()
4863 #[stable(feature = "iter_once", since = "1.2.0")]
4864 impl<T> DoubleEndedIterator for Once<T> {
4865 fn next_back(&mut self) -> Option<T> {
4866 self.inner.next_back()
4870 #[stable(feature = "iter_once", since = "1.2.0")]
4871 impl<T> ExactSizeIterator for Once<T> {
4872 fn len(&self) -> usize {
4877 /// Creates an iterator that yields an element exactly once.
4879 /// This is commonly used to adapt a single value into a [`chain()`] of other
4880 /// kinds of iteration. Maybe you have an iterator that covers almost
4881 /// everything, but you need an extra special case. Maybe you have a function
4882 /// which works on iterators, but you only need to process one value.
4884 /// [`chain()`]: trait.Iterator.html#method.chain
4893 /// // one is the loneliest number
4894 /// let mut one = iter::once(1);
4896 /// assert_eq!(Some(1), one.next());
4898 /// // just one, that's all we get
4899 /// assert_eq!(None, one.next());
4902 /// Chaining together with another iterator. Let's say that we want to iterate
4903 /// over each file of the `.foo` directory, but also a configuration file,
4909 /// use std::path::PathBuf;
4911 /// let dirs = fs::read_dir(".foo").unwrap();
4913 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4914 /// // PathBufs, so we use map
4915 /// let dirs = dirs.map(|file| file.unwrap().path());
4917 /// // now, our iterator just for our config file
4918 /// let config = iter::once(PathBuf::from(".foorc"));
4920 /// // chain the two iterators together into one big iterator
4921 /// let files = dirs.chain(config);
4923 /// // this will give us all of the files in .foo as well as .foorc
4924 /// for f in files {
4925 /// println!("{:?}", f);
4928 #[stable(feature = "iter_once", since = "1.2.0")]
4929 pub fn once<T>(value: T) -> Once<T> {
4930 Once { inner: Some(value).into_iter() }