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 //! let v = vec![1, 2, 3, 4, 5];
245 //! v.iter().map(|x| println!("{}", x));
248 //! This will not print any values, as we only created an iterator, rather than
249 //! using it. The compiler will warn us about this kind of behavior:
252 //! warning: unused result which must be used: iterator adaptors are lazy and
253 //! do nothing unless consumed
256 //! The idiomatic way to write a [`map()`] for its side effects is to use a
257 //! `for` loop instead:
260 //! let v = vec![1, 2, 3, 4, 5];
263 //! println!("{}", x);
267 //! [`map()`]: trait.Iterator.html#method.map
269 //! The two most common ways to evaluate an iterator are to use a `for` loop
270 //! like this, or using the [`collect()`] adapter to produce a new collection.
272 //! [`collect()`]: trait.Iterator.html#method.collect
276 //! Iterators do not have to be finite. As an example, an open-ended range is
277 //! an infinite iterator:
280 //! let numbers = 0..;
283 //! It is common to use the [`take()`] iterator adapter to turn an infinite
284 //! iterator into a finite one:
287 //! let numbers = 0..;
288 //! let five_numbers = numbers.take(5);
290 //! for number in five_numbers {
291 //! println!("{}", number);
295 //! This will print the numbers `0` through `4`, each on their own line.
297 //! [`take()`]: trait.Iterator.html#method.take
299 #![stable(feature = "rust1", since = "1.0.0")]
303 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
304 use default::Default;
307 use num::{Zero, One};
308 use ops::{self, Add, Sub, FnMut, Mul, RangeFrom};
309 use option::Option::{self, Some, None};
313 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
315 /// An interface for dealing with iterators.
317 /// This is the main iterator trait. For more about the concept of iterators
318 /// generally, please see the [module-level documentation]. In particular, you
319 /// may want to know how to [implement `Iterator`][impl].
321 /// [module-level documentation]: index.html
322 /// [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`.
377 /// let a = [1, 2, 3];
378 /// let iter = a.iter();
380 /// assert_eq!((3, Some(3)), iter.size_hint());
383 /// A more complex example:
386 /// // The even numbers from zero to ten.
387 /// let iter = (0..10).filter(|x| x % 2 == 0);
389 /// // We might iterate from zero to ten times. Knowing that it's five
390 /// // exactly wouldn't be possible without executing filter().
391 /// assert_eq!((0, Some(10)), iter.size_hint());
393 /// // Let's add one five more numbers with chain()
394 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
396 /// // now both bounds are increased by five
397 /// assert_eq!((5, Some(15)), iter.size_hint());
400 /// Returning `None` for an upper bound:
403 /// // an infinite iterator has no upper bound
404 /// let iter = (0..);
406 /// assert_eq!((0, None), iter.size_hint());
409 #[stable(feature = "rust1", since = "1.0.0")]
410 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
412 /// Consumes the iterator, counting the number of iterations and returning it.
414 /// This method will evaluate the iterator until its [`next()`] returns
415 /// `None`. Once `None` is encountered, `count()` returns the number of
416 /// times it called [`next()`].
418 /// [`next()`]: #method.next
420 /// # Overflow Behavior
422 /// The method does no guarding against overflows, so counting elements of
423 /// an iterator with more than `usize::MAX` elements either produces the
424 /// wrong result or panics. If debug assertions are enabled, a panic is
429 /// This function might panic if the iterator has more than `usize::MAX`
437 /// let a = [1, 2, 3];
438 /// assert_eq!(a.iter().count(), 3);
440 /// let a = [1, 2, 3, 4, 5];
441 /// assert_eq!(a.iter().count(), 5);
444 #[stable(feature = "rust1", since = "1.0.0")]
445 fn count(self) -> usize where Self: Sized {
447 self.fold(0, |cnt, _| cnt + 1)
450 /// Consumes the iterator, returning the last element.
452 /// This method will evaluate the iterator until it returns `None`. While
453 /// doing so, it keeps track of the current element. After `None` is
454 /// returned, `last()` will then return the last element it saw.
461 /// let a = [1, 2, 3];
462 /// assert_eq!(a.iter().last(), Some(&3));
464 /// let a = [1, 2, 3, 4, 5];
465 /// assert_eq!(a.iter().last(), Some(&5));
468 #[stable(feature = "rust1", since = "1.0.0")]
469 fn last(self) -> Option<Self::Item> where Self: Sized {
471 for x in self { last = Some(x); }
475 /// Consumes the `n` first elements of the iterator, then returns the
478 /// This method will evaluate the iterator `n` times, discarding those elements.
479 /// After it does so, it will call [`next()`] and return its value.
481 /// [`next()`]: #method.next
483 /// Like most indexing operations, the count starts from zero, so `nth(0)`
484 /// returns the first value, `nth(1)` the second, and so on.
486 /// `nth()` will return `None` if `n` is larger than the length of the
494 /// let a = [1, 2, 3];
495 /// assert_eq!(a.iter().nth(1), Some(&2));
498 /// Calling `nth()` multiple times doesn't rewind the iterator:
501 /// let a = [1, 2, 3];
503 /// let mut iter = a.iter();
505 /// assert_eq!(iter.nth(1), Some(&2));
506 /// assert_eq!(iter.nth(1), None);
509 /// Returning `None` if there are less than `n` elements:
512 /// let a = [1, 2, 3];
513 /// assert_eq!(a.iter().nth(10), None);
516 #[stable(feature = "rust1", since = "1.0.0")]
517 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
519 if n == 0 { return Some(x) }
525 /// Takes two iterators and creates a new iterator over both in sequence.
527 /// `chain()` will return a new iterator which will first iterate over
528 /// values from the first iterator and then over values from the second
531 /// In other words, it links two iterators together, in a chain. 🔗
538 /// let a1 = [1, 2, 3];
539 /// let a2 = [4, 5, 6];
541 /// let mut iter = a1.iter().chain(a2.iter());
543 /// assert_eq!(iter.next(), Some(&1));
544 /// assert_eq!(iter.next(), Some(&2));
545 /// assert_eq!(iter.next(), Some(&3));
546 /// assert_eq!(iter.next(), Some(&4));
547 /// assert_eq!(iter.next(), Some(&5));
548 /// assert_eq!(iter.next(), Some(&6));
549 /// assert_eq!(iter.next(), None);
552 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
553 /// anything that can be converted into an [`Iterator`], not just an
554 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
555 /// [`IntoIterator`], and so can be passed to `chain()` directly:
557 /// [`IntoIterator`]: trait.IntoIterator.html
558 /// [`Iterator`]: trait.Iterator.html
561 /// let s1 = &[1, 2, 3];
562 /// let s2 = &[4, 5, 6];
564 /// let mut iter = s1.iter().chain(s2);
566 /// assert_eq!(iter.next(), Some(&1));
567 /// assert_eq!(iter.next(), Some(&2));
568 /// assert_eq!(iter.next(), Some(&3));
569 /// assert_eq!(iter.next(), Some(&4));
570 /// assert_eq!(iter.next(), Some(&5));
571 /// assert_eq!(iter.next(), Some(&6));
572 /// assert_eq!(iter.next(), None);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
577 Self: Sized, U: IntoIterator<Item=Self::Item>,
579 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
582 /// 'Zips up' two iterators into a single iterator of pairs.
584 /// `zip()` returns a new iterator that will iterate over two other
585 /// iterators, returning a tuple where the first element comes from the
586 /// first iterator, and the second element comes from the second iterator.
588 /// In other words, it zips two iterators together, into a single one. 🤐
590 /// When either iterator returns `None`, all further calls to `next()`
591 /// will return `None`.
598 /// let a1 = [1, 2, 3];
599 /// let a2 = [4, 5, 6];
601 /// let mut iter = a1.iter().zip(a2.iter());
603 /// assert_eq!(iter.next(), Some((&1, &4)));
604 /// assert_eq!(iter.next(), Some((&2, &5)));
605 /// assert_eq!(iter.next(), Some((&3, &6)));
606 /// assert_eq!(iter.next(), None);
609 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
610 /// anything that can be converted into an [`Iterator`], not just an
611 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
612 /// [`IntoIterator`], and so can be passed to `zip()` directly:
614 /// [`IntoIterator`]: trait.IntoIterator.html
615 /// [`Iterator`]: trait.Iterator.html
618 /// let s1 = &[1, 2, 3];
619 /// let s2 = &[4, 5, 6];
621 /// let mut iter = s1.iter().zip(s2);
623 /// assert_eq!(iter.next(), Some((&1, &4)));
624 /// assert_eq!(iter.next(), Some((&2, &5)));
625 /// assert_eq!(iter.next(), Some((&3, &6)));
626 /// assert_eq!(iter.next(), None);
629 /// `zip()` is often used to zip an infinite iterator to a finite one.
630 /// This works because the finite iterator will eventually return `None`,
631 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
634 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
636 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
638 /// assert_eq!((0, 'f'), enumerate[0]);
639 /// assert_eq!((0, 'f'), zipper[0]);
641 /// assert_eq!((1, 'o'), enumerate[1]);
642 /// assert_eq!((1, 'o'), zipper[1]);
644 /// assert_eq!((2, 'o'), enumerate[2]);
645 /// assert_eq!((2, 'o'), zipper[2]);
648 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
650 #[stable(feature = "rust1", since = "1.0.0")]
651 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
652 Self: Sized, U: IntoIterator
654 Zip{a: self, b: other.into_iter()}
657 /// Takes a closure and creates an iterator which calls that closure on each
660 /// `map()` transforms one iterator into another, by means of its argument:
661 /// something that implements `FnMut`. It produces a new iterator which
662 /// calls this closure on each element of the original iterator.
664 /// If you are good at thinking in types, you can think of `map()` like this:
665 /// If you have an iterator that gives you elements of some type `A`, and
666 /// you want an iterator of some other type `B`, you can use `map()`,
667 /// passing a closure that takes an `A` and returns a `B`.
669 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
670 /// lazy, it is best used when you're already working with other iterators.
671 /// If you're doing some sort of looping for a side effect, it's considered
672 /// more idiomatic to use [`for`] than `map()`.
674 /// [`for`]: ../../book/loops.html#for
681 /// let a = [1, 2, 3];
683 /// let mut iter = a.into_iter().map(|x| 2 * x);
685 /// assert_eq!(iter.next(), Some(2));
686 /// assert_eq!(iter.next(), Some(4));
687 /// assert_eq!(iter.next(), Some(6));
688 /// assert_eq!(iter.next(), None);
691 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
694 /// // don't do this:
695 /// (0..5).map(|x| println!("{}", x));
697 /// // it won't even execute, as it is lazy. Rust will warn you about this.
699 /// // Instead, use for:
701 /// println!("{}", x);
705 #[stable(feature = "rust1", since = "1.0.0")]
706 fn map<B, F>(self, f: F) -> Map<Self, F> where
707 Self: Sized, F: FnMut(Self::Item) -> B,
709 Map{iter: self, f: f}
712 /// Creates an iterator which uses a closure to determine if an element
713 /// should be yielded.
715 /// The closure must return `true` or `false`. `filter()` creates an
716 /// iterator which calls this closure on each element. If the closure
717 /// returns `true`, then the element is returned. If the closure returns
718 /// `false`, it will try again, and call the closure on the next element,
719 /// seeing if it passes the test.
726 /// let a = [0i32, 1, 2];
728 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
730 /// assert_eq!(iter.next(), Some(&1));
731 /// assert_eq!(iter.next(), Some(&2));
732 /// assert_eq!(iter.next(), None);
735 /// Because the closure passed to `filter()` takes a reference, and many
736 /// iterators iterate over references, this leads to a possibly confusing
737 /// situation, where the type of the closure is a double reference:
740 /// let a = [0, 1, 2];
742 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
744 /// assert_eq!(iter.next(), Some(&2));
745 /// assert_eq!(iter.next(), None);
748 /// It's common to instead use destructuring on the argument to strip away
752 /// let a = [0, 1, 2];
754 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
756 /// assert_eq!(iter.next(), Some(&2));
757 /// assert_eq!(iter.next(), None);
763 /// let a = [0, 1, 2];
765 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
767 /// assert_eq!(iter.next(), Some(&2));
768 /// assert_eq!(iter.next(), None);
773 #[stable(feature = "rust1", since = "1.0.0")]
774 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
775 Self: Sized, P: FnMut(&Self::Item) -> bool,
777 Filter{iter: self, predicate: predicate}
780 /// Creates an iterator that both filters and maps.
782 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
783 /// iterator which calls this closure on each element. If the closure
784 /// returns `Some(element)`, then that element is returned. If the
785 /// closure returns `None`, it will try again, and call the closure on the
786 /// next element, seeing if it will return `Some`.
788 /// [`Option<T>`]: ../option/enum.Option.html
790 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
793 /// [`filter()`]: #method.filter
794 /// [`map()`]: #method.map
796 /// > If the closure returns `Some(element)`, then that element is returned.
798 /// In other words, it removes the [`Option<T>`] layer automatically. If your
799 /// mapping is already returning an [`Option<T>`] and you want to skip over
800 /// `None`s, then `filter_map()` is much, much nicer to use.
807 /// let a = ["1", "2", "lol"];
809 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
811 /// assert_eq!(iter.next(), Some(1));
812 /// assert_eq!(iter.next(), Some(2));
813 /// assert_eq!(iter.next(), None);
816 /// Here's the same example, but with [`filter()`] and [`map()`]:
819 /// let a = ["1", "2", "lol"];
821 /// let mut iter = a.iter()
822 /// .map(|s| s.parse().ok())
823 /// .filter(|s| s.is_some());
825 /// assert_eq!(iter.next(), Some(Some(1)));
826 /// assert_eq!(iter.next(), Some(Some(2)));
827 /// assert_eq!(iter.next(), None);
830 /// There's an extra layer of `Some` in there.
832 #[stable(feature = "rust1", since = "1.0.0")]
833 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
834 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
836 FilterMap { iter: self, f: f }
839 /// Creates an iterator which gives the current iteration count as well as
842 /// The iterator returned yields pairs `(i, val)`, where `i` is the
843 /// current index of iteration and `val` is the value returned by the
846 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
847 /// different sized integer, the [`zip()`] function provides similar
850 /// [`usize`]: ../primitive.usize.html
851 /// [`zip()`]: #method.zip
853 /// # Overflow Behavior
855 /// The method does no guarding against overflows, so enumerating more than
856 /// [`usize::MAX`] elements either produces the wrong result or panics. If
857 /// debug assertions are enabled, a panic is guaranteed.
859 /// [`usize::MAX`]: ../usize/constant.MAX.html
863 /// The returned iterator might panic if the to-be-returned index would
864 /// overflow a `usize`.
869 /// let a = [1, 2, 3];
871 /// let mut iter = a.iter().enumerate();
873 /// assert_eq!(iter.next(), Some((0, &1)));
874 /// assert_eq!(iter.next(), Some((1, &2)));
875 /// assert_eq!(iter.next(), Some((2, &3)));
876 /// assert_eq!(iter.next(), None);
879 #[stable(feature = "rust1", since = "1.0.0")]
880 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
881 Enumerate { iter: self, count: 0 }
884 /// Creates an iterator which can look at the `next()` element without
887 /// Adds a [`peek()`] method to an iterator. See its documentation for
888 /// more information.
890 /// [`peek()`]: struct.Peekable.html#method.peek
897 /// let xs = [1, 2, 3];
899 /// let mut iter = xs.iter().peekable();
901 /// // peek() lets us see into the future
902 /// assert_eq!(iter.peek(), Some(&&1));
903 /// assert_eq!(iter.next(), Some(&1));
905 /// assert_eq!(iter.next(), Some(&2));
907 /// // we can peek() multiple times, the itererator won't advance
908 /// assert_eq!(iter.peek(), Some(&&3));
909 /// assert_eq!(iter.peek(), Some(&&3));
911 /// assert_eq!(iter.next(), Some(&3));
913 /// // after the itererator is finished, so is peek()
914 /// assert_eq!(iter.peek(), None);
915 /// assert_eq!(iter.next(), None);
918 #[stable(feature = "rust1", since = "1.0.0")]
919 fn peekable(self) -> Peekable<Self> where Self: Sized {
920 Peekable{iter: self, peeked: None}
923 /// Creates an iterator that [`skip()`]s elements based on a predicate.
925 /// [`skip()`]: #method.skip
927 /// `skip_while()` takes a closure as an argument. It will call this
928 /// closure on each element of the iterator, and ignore elements
929 /// until it returns `false`.
931 /// After `false` is returned, `skip_while()`'s job is over, and the
932 /// rest of the elements are yielded.
939 /// let a = [-1i32, 0, 1];
941 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
943 /// assert_eq!(iter.next(), Some(&0));
944 /// assert_eq!(iter.next(), Some(&1));
945 /// assert_eq!(iter.next(), None);
948 /// Because the closure passed to `skip_while()` takes a reference, and many
949 /// iterators iterate over references, this leads to a possibly confusing
950 /// situation, where the type of the closure is a double reference:
953 /// let a = [-1, 0, 1];
955 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
957 /// assert_eq!(iter.next(), Some(&0));
958 /// assert_eq!(iter.next(), Some(&1));
959 /// assert_eq!(iter.next(), None);
962 /// Stopping after an initial `false`:
965 /// let a = [-1, 0, 1, -2];
967 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
969 /// assert_eq!(iter.next(), Some(&0));
970 /// assert_eq!(iter.next(), Some(&1));
972 /// // while this would have been false, since we already got a false,
973 /// // skip_while() isn't used any more
974 /// assert_eq!(iter.next(), Some(&-2));
976 /// assert_eq!(iter.next(), None);
979 #[stable(feature = "rust1", since = "1.0.0")]
980 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
981 Self: Sized, P: FnMut(&Self::Item) -> bool,
983 SkipWhile{iter: self, flag: false, predicate: predicate}
986 /// Creates an iterator that yields elements based on a predicate.
988 /// `take_while()` takes a closure as an argument. It will call this
989 /// closure on each element of the iterator, and yield elements
990 /// while it returns `true`.
992 /// After `false` is returned, `take_while()`'s job is over, and the
993 /// rest of the elements are ignored.
1000 /// let a = [-1i32, 0, 1];
1002 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1004 /// assert_eq!(iter.next(), Some(&-1));
1005 /// assert_eq!(iter.next(), None);
1008 /// Because the closure passed to `take_while()` takes a reference, and many
1009 /// iterators iterate over references, this leads to a possibly confusing
1010 /// situation, where the type of the closure is a double reference:
1013 /// let a = [-1, 0, 1];
1015 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1017 /// assert_eq!(iter.next(), Some(&-1));
1018 /// assert_eq!(iter.next(), None);
1021 /// Stopping after an initial `false`:
1024 /// let a = [-1, 0, 1, -2];
1026 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1028 /// assert_eq!(iter.next(), Some(&-1));
1030 /// // We have more elements that are less than zero, but since we already
1031 /// // got a false, take_while() isn't used any more
1032 /// assert_eq!(iter.next(), None);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1037 Self: Sized, P: FnMut(&Self::Item) -> bool,
1039 TakeWhile{iter: self, flag: false, predicate: predicate}
1042 /// Creates an iterator that skips the first `n` elements.
1044 /// After they have been consumed, the rest of the elements are yielded.
1051 /// let a = [1, 2, 3];
1053 /// let mut iter = a.iter().skip(2);
1055 /// assert_eq!(iter.next(), Some(&3));
1056 /// assert_eq!(iter.next(), None);
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1061 Skip{iter: self, n: n}
1064 /// Creates an iterator that yields its first `n` elements.
1071 /// let a = [1, 2, 3];
1073 /// let mut iter = a.iter().take(2);
1075 /// assert_eq!(iter.next(), Some(&1));
1076 /// assert_eq!(iter.next(), Some(&2));
1077 /// assert_eq!(iter.next(), None);
1080 /// `take()` is often used with an infinite iterator, to make it finite:
1083 /// let mut iter = (0..).take(3);
1085 /// assert_eq!(iter.next(), Some(0));
1086 /// assert_eq!(iter.next(), Some(1));
1087 /// assert_eq!(iter.next(), Some(2));
1088 /// assert_eq!(iter.next(), None);
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1093 Take{iter: self, n: n}
1096 /// An iterator similar to `fold()`, with internal state.
1098 /// `scan()` accumulates a final value, similar to [`fold()`], but instead
1099 /// of passing along an accumulator, it maintains the accumulator internally.
1101 /// [`fold()`]: #method.fold
1103 /// On each iteraton of `scan()`, you can assign to the internal state, and
1104 /// a mutable reference to the state is passed as the first argument to the
1105 /// closure, allowing you to modify it on each iteration.
1112 /// let a = [1, 2, 3];
1114 /// let mut iter = a.iter().scan(1, |state, &x| {
1115 /// // each iteration, we'll multiply the state by the element
1116 /// *state = *state * x;
1118 /// // the value passed on to the next iteration
1122 /// assert_eq!(iter.next(), Some(1));
1123 /// assert_eq!(iter.next(), Some(2));
1124 /// assert_eq!(iter.next(), Some(6));
1125 /// assert_eq!(iter.next(), None);
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1130 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1132 Scan{iter: self, f: f, state: initial_state}
1135 /// Creates an iterator that works like map, but flattens nested structure.
1137 /// The [`map()`] adapter is very useful, but only when the closure
1138 /// argument produces values. If it produces an iterator instead, there's
1139 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1142 /// [`map()`]: #method.map
1144 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1145 /// one item for each element, and `flat_map()`'s closure returns an
1146 /// iterator for each element.
1153 /// let words = ["alpha", "beta", "gamma"];
1155 /// // chars() returns an iterator
1156 /// let merged: String = words.iter()
1157 /// .flat_map(|s| s.chars())
1159 /// assert_eq!(merged, "alphabetagamma");
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1164 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1166 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1169 /// Creates an iterator which ends after the first `None`.
1171 /// After an iterator returns `None`, future calls may or may not yield
1172 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1173 /// `None` is given, it will always return `None` forever.
1180 /// // an iterator which alternates between Some and None
1181 /// struct Alternate {
1185 /// impl Iterator for Alternate {
1186 /// type Item = i32;
1188 /// fn next(&mut self) -> Option<i32> {
1189 /// let val = self.state;
1190 /// self.state = self.state + 1;
1192 /// // if it's even, Some(i32), else None
1193 /// if val % 2 == 0 {
1201 /// let mut iter = Alternate { state: 0 };
1203 /// // we can see our iterator going back and forth
1204 /// assert_eq!(iter.next(), Some(0));
1205 /// assert_eq!(iter.next(), None);
1206 /// assert_eq!(iter.next(), Some(2));
1207 /// assert_eq!(iter.next(), None);
1209 /// // however, once we fuse it...
1210 /// let mut iter = iter.fuse();
1212 /// assert_eq!(iter.next(), Some(4));
1213 /// assert_eq!(iter.next(), None);
1215 /// // it will always return None after the first time.
1216 /// assert_eq!(iter.next(), None);
1217 /// assert_eq!(iter.next(), None);
1218 /// assert_eq!(iter.next(), None);
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 fn fuse(self) -> Fuse<Self> where Self: Sized {
1223 Fuse{iter: self, done: false}
1226 /// Do something with each element of an iterator, passing the value on.
1228 /// When using iterators, you'll often chain several of them together.
1229 /// While working on such code, you might want to check out what's
1230 /// happening at various parts in the pipeline. To do that, insert
1231 /// a call to `inspect()`.
1233 /// It's much more common for `inspect()` to be used as a debugging tool
1234 /// than to exist in your final code, but never say never.
1241 /// let a = [1, 4, 2, 3];
1243 /// // this iterator sequence is complex.
1244 /// let sum = a.iter()
1246 /// .filter(|&x| x % 2 == 0)
1247 /// .fold(0, |sum, i| sum + i);
1249 /// println!("{}", sum);
1251 /// // let's add some inspect() calls to investigate what's happening
1252 /// let sum = a.iter()
1254 /// .inspect(|x| println!("about to filter: {}", x))
1255 /// .filter(|&x| x % 2 == 0)
1256 /// .inspect(|x| println!("made it through filter: {}", x))
1257 /// .fold(0, |sum, i| sum + i);
1259 /// println!("{}", sum);
1262 /// This will print:
1265 /// about to filter: 1
1266 /// about to filter: 4
1267 /// made it through filter: 4
1268 /// about to filter: 2
1269 /// made it through filter: 2
1270 /// about to filter: 3
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1276 Self: Sized, F: FnMut(&Self::Item),
1278 Inspect{iter: self, f: f}
1281 /// Borrows an iterator, rather than consuming it.
1283 /// This is useful to allow applying iterator adaptors while still
1284 /// retaining ownership of the original iterator.
1291 /// let a = [1, 2, 3];
1293 /// let iter = a.into_iter();
1295 /// let sum: i32 = iter.take(5)
1296 /// .fold(0, |acc, &i| acc + i );
1298 /// assert_eq!(sum, 6);
1300 /// // if we try to use iter again, it won't work. The following line
1301 /// // gives "error: use of moved value: `iter`
1302 /// // assert_eq!(iter.next(), None);
1304 /// // let's try that again
1305 /// let a = [1, 2, 3];
1307 /// let mut iter = a.into_iter();
1309 /// // instead, we add in a .by_ref()
1310 /// let sum: i32 = iter.by_ref()
1312 /// .fold(0, |acc, &i| acc + i );
1314 /// assert_eq!(sum, 3);
1316 /// // now this is just fine:
1317 /// assert_eq!(iter.next(), Some(&3));
1318 /// assert_eq!(iter.next(), None);
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1323 /// Transforms an iterator into a collection.
1325 /// `collect()` can take anything iterable, and turn it into a relevant
1326 /// collection. This is one of the more powerful methods in the standard
1327 /// library, used in a variety of contexts.
1329 /// The most basic pattern in which `collect()` is used is to turn one
1330 /// collection into another. You take a collection, call `iter()` on it,
1331 /// do a bunch of transformations, and then `collect()` at the end.
1333 /// One of the keys to `collect()`'s power is that many things you might
1334 /// not think of as 'collections' actually are. For example, a [`String`]
1335 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1336 /// be thought of as single [`Result<Collection<T>, E>`]. See the examples
1339 /// [`String`]: ../string/struct.String.html
1340 /// [`Result<T, E>`]: ../result/enum.Result.html
1341 /// [`char`]: ../primitive.char.html
1343 /// Because `collect()` is so general, it can cause problems with type
1344 /// inference. As such, `collect()` is one of the few times you'll see
1345 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1346 /// helps the inference algorithm understand specifically which collection
1347 /// you're trying to collect into.
1354 /// let a = [1, 2, 3];
1356 /// let doubled: Vec<i32> = a.iter()
1357 /// .map(|&x| x * 2)
1360 /// assert_eq!(vec![2, 4, 6], doubled);
1363 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1364 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1366 /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1369 /// use std::collections::VecDeque;
1371 /// let a = [1, 2, 3];
1373 /// let doubled: VecDeque<i32> = a.iter()
1374 /// .map(|&x| x * 2)
1377 /// assert_eq!(2, doubled[0]);
1378 /// assert_eq!(4, doubled[1]);
1379 /// assert_eq!(6, doubled[2]);
1382 /// Using the 'turbofish' instead of annotationg `doubled`:
1385 /// let a = [1, 2, 3];
1387 /// let doubled = a.iter()
1388 /// .map(|&x| x * 2)
1389 /// .collect::<Vec<i32>>();
1391 /// assert_eq!(vec![2, 4, 6], doubled);
1394 /// Because `collect()` cares about what you're collecting into, you can
1395 /// still use a partial type hint, `_`, with the turbofish:
1398 /// let a = [1, 2, 3];
1400 /// let doubled = a.iter()
1401 /// .map(|&x| x * 2)
1402 /// .collect::<Vec<_>>();
1404 /// assert_eq!(vec![2, 4, 6], doubled);
1407 /// Using `collect()` to make a [`String`]:
1410 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1412 /// let hello: String = chars.iter()
1413 /// .map(|&x| x as u8)
1414 /// .map(|x| (x + 1) as char)
1417 /// assert_eq!("hello", hello);
1420 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1421 /// see if any of them failed:
1424 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1426 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1428 /// // gives us the first error
1429 /// assert_eq!(Err("nope"), result);
1431 /// let results = [Ok(1), Ok(3)];
1433 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1435 /// // gives us the list of answers
1436 /// assert_eq!(Ok(vec![1, 3]), result);
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1441 FromIterator::from_iter(self)
1444 /// Consumes an iterator, creating two collections from it.
1446 /// The predicate passed to `partition()` can return `true`, or `false`.
1447 /// `partition()` returns a pair, all of the elements for which it returned
1448 /// `true`, and all of the elements for which it returned `false`.
1455 /// let a = [1, 2, 3];
1457 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1458 /// .partition(|&n| n % 2 == 0);
1460 /// assert_eq!(even, vec![2]);
1461 /// assert_eq!(odd, vec![1, 3]);
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 fn partition<B, F>(self, mut f: F) -> (B, B) where
1466 B: Default + Extend<Self::Item>,
1467 F: FnMut(&Self::Item) -> bool
1469 let mut left: B = Default::default();
1470 let mut right: B = Default::default();
1474 left.extend(Some(x))
1476 right.extend(Some(x))
1483 /// An iterator adaptor that applies a function, producing a single, final value.
1485 /// `fold()` takes two arguments: an initial value, and a closure with two
1486 /// arguments: an 'accumulator', and an element. It returns the value that
1487 /// the accumulator should have for the next iteration.
1489 /// The initial value is the value the accumulator will have on the first
1492 /// After applying this closure to every element of the iterator, `fold()`
1493 /// returns the accumulator.
1495 /// This operation is sometimes called 'reduce' or 'inject'.
1497 /// Folding is useful whenever you have a collection of something, and want
1498 /// to produce a single value from it.
1505 /// let a = [1, 2, 3];
1507 /// // the sum of all of the elements of a
1508 /// let sum = a.iter()
1509 /// .fold(0, |acc, &x| acc + x);
1511 /// assert_eq!(sum, 6);
1514 /// Let's walk through each step of the iteration here:
1516 /// | element | acc | x | result |
1517 /// |---------|-----|---|--------|
1519 /// | 1 | 0 | 1 | 1 |
1520 /// | 2 | 1 | 2 | 3 |
1521 /// | 3 | 3 | 3 | 6 |
1523 /// And so, our final result, `6`.
1525 /// It's common for people who haven't used iterators a lot to
1526 /// use a `for` loop with a list of things to build up a result. Those
1527 /// can be turned into `fold()`s:
1530 /// let numbers = [1, 2, 3, 4, 5];
1532 /// let mut result = 0;
1535 /// for i in &numbers {
1536 /// result = result + i;
1540 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1542 /// // they're the same
1543 /// assert_eq!(result, result2);
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 fn fold<B, F>(self, init: B, mut f: F) -> B where
1548 Self: Sized, F: FnMut(B, Self::Item) -> B,
1550 let mut accum = init;
1552 accum = f(accum, x);
1557 /// Tests if every element of the iterator matches a predicate.
1559 /// `all()` takes a closure that returns `true` or `false`. It applies
1560 /// this closure to each element of the iterator, and if they all return
1561 /// `true`, then so does `all()`. If any of them return `false`, it
1562 /// returns `false`.
1564 /// `all()` is short-circuting; in other words, it will stop processing
1565 /// as soon as it finds a `false`, given that no matter what else happens,
1566 /// the result will also be `false`.
1573 /// let a = [1, 2, 3];
1575 /// assert!(a.iter().all(|&x| x > 0));
1577 /// assert!(!a.iter().all(|&x| x > 2));
1580 /// Stopping at the first `false`:
1583 /// let a = [1, 2, 3];
1585 /// let mut iter = a.iter();
1587 /// assert!(!iter.all(|&x| x != 2));
1589 /// // we can still use `iter`, as there are more elements.
1590 /// assert_eq!(iter.next(), Some(&3));
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 fn all<F>(&mut self, mut f: F) -> bool where
1595 Self: Sized, F: FnMut(Self::Item) -> bool
1605 /// Tests if any element of the iterator matches a predicate.
1607 /// `any()` takes a closure that returns `true` or `false`. It applies
1608 /// this closure to each element of the iterator, and if any of them return
1609 /// `true`, then so does `any()`. If they all return `false`, it
1610 /// returns `false`.
1612 /// `any()` is short-circuting; in other words, it will stop processing
1613 /// as soon as it finds a `true`, given that no matter what else happens,
1614 /// the result will also be `true`.
1621 /// let a = [1, 2, 3];
1623 /// assert!(a.iter().any(|&x| x > 0));
1625 /// assert!(!a.iter().any(|&x| x > 5));
1628 /// Stopping at the first `true`:
1631 /// let a = [1, 2, 3];
1633 /// let mut iter = a.iter();
1635 /// assert!(iter.any(|&x| x != 2));
1637 /// // we can still use `iter`, as there are more elements.
1638 /// assert_eq!(iter.next(), Some(&2));
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 fn any<F>(&mut self, mut f: F) -> bool where
1644 F: FnMut(Self::Item) -> bool
1654 /// Searches for an element of an iterator that satisfies a predicate.
1656 /// `find()` takes a closure that returns `true` or `false`. It applies
1657 /// this closure to each element of the iterator, and if any of them return
1658 /// `true`, then `find()` returns `Some(element)`. If they all return
1659 /// `false`, it returns `None`.
1661 /// `find()` is short-circuting; in other words, it will stop processing
1662 /// as soon as the closure returns `true`.
1664 /// Because `find()` takes a reference, and many iterators iterate over
1665 /// references, this leads to a possibly confusing situation where the
1666 /// argument is a double reference. You can see this effect in the
1667 /// examples below, with `&&x`.
1674 /// let a = [1, 2, 3];
1676 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1678 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1681 /// Stopping at the first `true`:
1684 /// let a = [1, 2, 3];
1686 /// let mut iter = a.iter();
1688 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1690 /// // we can still use `iter`, as there are more elements.
1691 /// assert_eq!(iter.next(), Some(&3));
1694 #[stable(feature = "rust1", since = "1.0.0")]
1695 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1697 P: FnMut(&Self::Item) -> bool,
1700 if predicate(&x) { return Some(x) }
1705 /// Searches for an element in an iterator, returning its index.
1707 /// `position()` takes a closure that returns `true` or `false`. It applies
1708 /// this closure to each element of the iterator, and if if one of them
1709 /// returns `true`, then `position()` returns `Some(index)`. If all of
1710 /// them return `false`, it returns `None`.
1712 /// `position()` is short-circuting; in other words, it will stop
1713 /// processing as soon as it finds a `true`.
1715 /// # Overflow Behavior
1717 /// The method does no guarding against overflows, so if there are more
1718 /// than `usize::MAX` non-matching elements, it either produces the wrong
1719 /// result or panics. If debug assertions are enabled, a panic is
1724 /// This function might panic if the iterator has more than `usize::MAX`
1725 /// non-matching elements.
1732 /// let a = [1, 2, 3];
1734 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1736 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1739 /// Stopping at the first `true`:
1742 /// let a = [1, 2, 3];
1744 /// let mut iter = a.iter();
1746 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1748 /// // we can still use `iter`, as there are more elements.
1749 /// assert_eq!(iter.next(), Some(&3));
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1755 P: FnMut(Self::Item) -> bool,
1757 // `enumerate` might overflow.
1758 for (i, x) in self.enumerate() {
1766 /// Searches for an element in an iterator from the right, returning its
1769 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1770 /// this closure to each element of the iterator, starting from the end,
1771 /// and if if one of them returns `true`, then `rposition()` returns
1772 /// `Some(index)`. If all of them return `false`, it returns `None`.
1774 /// `rposition()` is short-circuting; in other words, it will stop
1775 /// processing as soon as it finds a `true`.
1782 /// let a = [1, 2, 3];
1784 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1786 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1789 /// Stopping at the first `true`:
1792 /// let a = [1, 2, 3];
1794 /// let mut iter = a.iter();
1796 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1798 /// // we can still use `iter`, as there are more elements.
1799 /// assert_eq!(iter.next(), Some(&1));
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1804 P: FnMut(Self::Item) -> bool,
1805 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1807 let mut i = self.len();
1809 while let Some(v) = self.next_back() {
1813 // No need for an overflow check here, because `ExactSizeIterator`
1814 // implies that the number of elements fits into a `usize`.
1820 /// Returns the maximum element of an iterator.
1822 /// If the two elements are equally maximum, the latest element is
1830 /// let a = [1, 2, 3];
1832 /// assert_eq!(a.iter().max(), Some(&3));
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1840 // switch to y even if it is only equal, to preserve
1842 |_, x, _, y| *x <= *y)
1846 /// Returns the minimum element of an iterator.
1848 /// If the two elements are equally minimum, the first element is
1856 /// let a = [1, 2, 3];
1858 /// assert_eq!(a.iter().min(), Some(&1));
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1866 // only switch to y if it is strictly smaller, to
1867 // preserve stability.
1868 |_, x, _, y| *x > *y)
1872 /// Returns the element that gives the maximum value from the
1873 /// specified function.
1875 /// Returns the rightmost element if the comparison determines two elements
1876 /// to be equally maximum.
1881 /// #![feature(iter_cmp)]
1883 /// let a = [-3_i32, 0, 1, 5, -10];
1884 /// assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10);
1887 #[unstable(feature = "iter_cmp",
1888 reason = "may want to produce an Ordering directly; see #15311",
1890 fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1892 F: FnMut(&Self::Item) -> B,
1896 // switch to y even if it is only equal, to preserve
1898 |x_p, _, y_p, _| x_p <= y_p)
1902 /// Returns the element that gives the minimum value from the
1903 /// specified function.
1905 /// Returns the latest element if the comparison determines two elements
1906 /// to be equally minimum.
1911 /// #![feature(iter_cmp)]
1913 /// let a = [-3_i32, 0, 1, 5, -10];
1914 /// assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0);
1917 #[unstable(feature = "iter_cmp",
1918 reason = "may want to produce an Ordering directly; see #15311",
1920 fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1922 F: FnMut(&Self::Item) -> B,
1926 // only switch to y if it is strictly smaller, to
1927 // preserve stability.
1928 |x_p, _, y_p, _| x_p > y_p)
1932 /// Reverses an iterator's direction.
1934 /// Usually, iterators iterate from left to right. After using `rev()`,
1935 /// an iterator will instead iterate from right to left.
1937 /// This is only possible if the iterator has an end, so `rev()` only
1938 /// works on [`DoubleEndedIterator`]s.
1940 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1945 /// let a = [1, 2, 3];
1947 /// let mut iter = a.iter().rev();
1949 /// assert_eq!(iter.next(), Some(&3));
1950 /// assert_eq!(iter.next(), Some(&2));
1951 /// assert_eq!(iter.next(), Some(&1));
1953 /// assert_eq!(iter.next(), None);
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
1961 /// Converts an iterator of pairs into a pair of containers.
1963 /// `unzip()` consumes an entire iterator of pairs, producing two
1964 /// collections: one from the left elements of the pairs, and one
1965 /// from the right elements.
1967 /// This function is, in some sense, the opposite of [`zip()`].
1969 /// [`zip()`]: #method.zip
1976 /// let a = [(1, 2), (3, 4)];
1978 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
1980 /// assert_eq!(left, [1, 3]);
1981 /// assert_eq!(right, [2, 4]);
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
1985 FromA: Default + Extend<A>,
1986 FromB: Default + Extend<B>,
1987 Self: Sized + Iterator<Item=(A, B)>,
1989 struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
1990 impl<A> Iterator for SizeHint<A> {
1993 fn next(&mut self) -> Option<A> { None }
1994 fn size_hint(&self) -> (usize, Option<usize>) {
1999 let (lo, hi) = self.size_hint();
2000 let mut ts: FromA = Default::default();
2001 let mut us: FromB = Default::default();
2003 ts.extend(SizeHint(lo, hi, marker::PhantomData));
2004 us.extend(SizeHint(lo, hi, marker::PhantomData));
2006 for (t, u) in self {
2014 /// Creates an iterator which clone()s all of its elements.
2016 /// This is useful when you have an iterator over `&T`, but you need an
2017 /// iterator over `T`.
2024 /// let a = [1, 2, 3];
2026 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2028 /// // cloned is the same as .map(|&x| x), for integers
2029 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2031 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2032 /// assert_eq!(v_map, vec![1, 2, 3]);
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2036 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2041 /// Repeats an iterator endlessly.
2043 /// Instead of stopping at `None`, the iterator will instead start again,
2044 /// from the beginning. After iterating again, it will start at the
2045 /// beginning again. And again. And again. Forever.
2052 /// let a = [1, 2, 3];
2054 /// let mut it = a.iter().cycle();
2056 /// assert_eq!(it.next(), Some(&1));
2057 /// assert_eq!(it.next(), Some(&2));
2058 /// assert_eq!(it.next(), Some(&3));
2059 /// assert_eq!(it.next(), Some(&1));
2060 /// assert_eq!(it.next(), Some(&2));
2061 /// assert_eq!(it.next(), Some(&3));
2062 /// assert_eq!(it.next(), Some(&1));
2064 #[stable(feature = "rust1", since = "1.0.0")]
2066 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2067 Cycle{orig: self.clone(), iter: self}
2070 /// Sums the elements of an iterator.
2072 /// Takes each element, adds them together, and returns the result.
2079 /// #![feature(iter_arith)]
2081 /// let a = [1, 2, 3];
2082 /// let sum: i32 = a.iter().sum();
2084 /// assert_eq!(sum, 6);
2086 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2088 fn sum<S=<Self as Iterator>::Item>(self) -> S where
2089 S: Add<Self::Item, Output=S> + Zero,
2092 self.fold(Zero::zero(), |s, e| s + e)
2095 /// Iterates over the entire iterator, multiplying all the elements
2100 /// #![feature(iter_arith)]
2102 /// fn factorial(n: u32) -> u32 {
2103 /// (1..).take_while(|&i| i <= n).product()
2105 /// assert_eq!(factorial(0), 1);
2106 /// assert_eq!(factorial(1), 1);
2107 /// assert_eq!(factorial(5), 120);
2109 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2111 fn product<P=<Self as Iterator>::Item>(self) -> P where
2112 P: Mul<Self::Item, Output=P> + One,
2115 self.fold(One::one(), |p, e| p * e)
2118 /// Lexicographically compares the elements of this `Iterator` with those
2120 #[stable(feature = "iter_order", since = "1.5.0")]
2121 fn cmp<I>(mut self, other: I) -> Ordering where
2122 I: IntoIterator<Item = Self::Item>,
2126 let mut other = other.into_iter();
2129 match (self.next(), other.next()) {
2130 (None, None) => return Ordering::Equal,
2131 (None, _ ) => return Ordering::Less,
2132 (_ , None) => return Ordering::Greater,
2133 (Some(x), Some(y)) => match x.cmp(&y) {
2134 Ordering::Equal => (),
2135 non_eq => return non_eq,
2141 /// Lexicographically compares the elements of this `Iterator` with those
2143 #[stable(feature = "iter_order", since = "1.5.0")]
2144 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2146 Self::Item: PartialOrd<I::Item>,
2149 let mut other = other.into_iter();
2152 match (self.next(), other.next()) {
2153 (None, None) => return Some(Ordering::Equal),
2154 (None, _ ) => return Some(Ordering::Less),
2155 (_ , None) => return Some(Ordering::Greater),
2156 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2157 Some(Ordering::Equal) => (),
2158 non_eq => return non_eq,
2164 /// Determines if the elements of this `Iterator` are equal to those of
2166 #[stable(feature = "iter_order", since = "1.5.0")]
2167 fn eq<I>(mut self, other: I) -> bool where
2169 Self::Item: PartialEq<I::Item>,
2172 let mut other = other.into_iter();
2175 match (self.next(), other.next()) {
2176 (None, None) => return true,
2177 (None, _) | (_, None) => return false,
2178 (Some(x), Some(y)) => if x != y { return false },
2183 /// Determines if the elements of this `Iterator` are unequal to those of
2185 #[stable(feature = "iter_order", since = "1.5.0")]
2186 fn ne<I>(mut self, other: I) -> bool where
2188 Self::Item: PartialEq<I::Item>,
2191 let mut other = other.into_iter();
2194 match (self.next(), other.next()) {
2195 (None, None) => return false,
2196 (None, _) | (_, None) => return true,
2197 (Some(x), Some(y)) => if x.ne(&y) { return true },
2202 /// Determines if the elements of this `Iterator` are lexicographically
2203 /// less than those of another.
2204 #[stable(feature = "iter_order", since = "1.5.0")]
2205 fn lt<I>(mut self, other: I) -> bool where
2207 Self::Item: PartialOrd<I::Item>,
2210 let mut other = other.into_iter();
2213 match (self.next(), other.next()) {
2214 (None, None) => return false,
2215 (None, _ ) => return true,
2216 (_ , None) => return false,
2217 (Some(x), Some(y)) => {
2218 match x.partial_cmp(&y) {
2219 Some(Ordering::Less) => return true,
2220 Some(Ordering::Equal) => {}
2221 Some(Ordering::Greater) => return false,
2222 None => return false,
2229 /// Determines if the elements of this `Iterator` are lexicographically
2230 /// less or equal to those of another.
2231 #[stable(feature = "iter_order", since = "1.5.0")]
2232 fn le<I>(mut self, other: I) -> bool where
2234 Self::Item: PartialOrd<I::Item>,
2237 let mut other = other.into_iter();
2240 match (self.next(), other.next()) {
2241 (None, None) => return true,
2242 (None, _ ) => return true,
2243 (_ , None) => return false,
2244 (Some(x), Some(y)) => {
2245 match x.partial_cmp(&y) {
2246 Some(Ordering::Less) => return true,
2247 Some(Ordering::Equal) => {}
2248 Some(Ordering::Greater) => return false,
2249 None => return false,
2256 /// Determines if the elements of this `Iterator` are lexicographically
2257 /// greater than those of another.
2258 #[stable(feature = "iter_order", since = "1.5.0")]
2259 fn gt<I>(mut self, other: I) -> bool where
2261 Self::Item: PartialOrd<I::Item>,
2264 let mut other = other.into_iter();
2267 match (self.next(), other.next()) {
2268 (None, None) => return false,
2269 (None, _ ) => return false,
2270 (_ , None) => return true,
2271 (Some(x), Some(y)) => {
2272 match x.partial_cmp(&y) {
2273 Some(Ordering::Less) => return false,
2274 Some(Ordering::Equal) => {}
2275 Some(Ordering::Greater) => return true,
2276 None => return false,
2283 /// Determines if the elements of this `Iterator` are lexicographically
2284 /// greater than or equal to those of another.
2285 #[stable(feature = "iter_order", since = "1.5.0")]
2286 fn ge<I>(mut self, other: I) -> bool where
2288 Self::Item: PartialOrd<I::Item>,
2291 let mut other = other.into_iter();
2294 match (self.next(), other.next()) {
2295 (None, None) => return true,
2296 (None, _ ) => return false,
2297 (_ , None) => return true,
2298 (Some(x), Some(y)) => {
2299 match x.partial_cmp(&y) {
2300 Some(Ordering::Less) => return false,
2301 Some(Ordering::Equal) => {}
2302 Some(Ordering::Greater) => return true,
2303 None => return false,
2311 /// Select an element from an iterator based on the given projection
2312 /// and "comparison" function.
2314 /// This is an idiosyncratic helper to try to factor out the
2315 /// commonalities of {max,min}{,_by}. In particular, this avoids
2316 /// having to implement optimizations several times.
2318 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2320 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2322 FProj: FnMut(&I::Item) -> B,
2323 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2325 // start with the first element as our selection. This avoids
2326 // having to use `Option`s inside the loop, translating to a
2327 // sizeable performance gain (6x in one case).
2328 it.next().map(|mut sel| {
2329 let mut sel_p = f_proj(&sel);
2332 let x_p = f_proj(&x);
2333 if f_cmp(&sel_p, &sel, &x_p, &x) {
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2344 type Item = I::Item;
2345 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2346 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2349 /// Conversion from an `Iterator`.
2350 #[stable(feature = "rust1", since = "1.0.0")]
2351 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2352 built from an iterator over elements of type `{A}`"]
2353 pub trait FromIterator<A>: Sized {
2354 /// Builds a container with elements from something iterable.
2359 /// use std::collections::HashSet;
2360 /// use std::iter::FromIterator;
2362 /// let colors_vec = vec!["red", "red", "yellow", "blue"];
2363 /// let colors_set = HashSet::<&str>::from_iter(colors_vec);
2364 /// assert_eq!(colors_set.len(), 3);
2367 /// `FromIterator` is more commonly used implicitly via the
2368 /// `Iterator::collect` method:
2371 /// use std::collections::HashSet;
2373 /// let colors_vec = vec!["red", "red", "yellow", "blue"];
2374 /// let colors_set = colors_vec.into_iter().collect::<HashSet<&str>>();
2375 /// assert_eq!(colors_set.len(), 3);
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
2381 /// Conversion into an `Iterator`.
2383 /// By implementing `IntoIterator` for a type, you define how it will be
2384 /// converted to an iterator. This is common for types which describe a
2385 /// collection of some kind.
2387 /// One benefit of implementing `IntoIterator` is that your type will [work
2388 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2392 /// Vectors implement `IntoIterator`:
2395 /// let v = vec![1, 2, 3];
2397 /// let mut iter = v.into_iter();
2399 /// let n = iter.next();
2400 /// assert_eq!(Some(1), n);
2402 /// let n = iter.next();
2403 /// assert_eq!(Some(2), n);
2405 /// let n = iter.next();
2406 /// assert_eq!(Some(3), n);
2408 /// let n = iter.next();
2409 /// assert_eq!(None, n);
2412 /// Implementing `IntoIterator` for your type:
2415 /// // A sample collection, that's just a wrapper over Vec<T>
2416 /// #[derive(Debug)]
2417 /// struct MyCollection(Vec<i32>);
2419 /// // Let's give it some methods so we can create one and add things
2421 /// impl MyCollection {
2422 /// fn new() -> MyCollection {
2423 /// MyCollection(Vec::new())
2426 /// fn add(&mut self, elem: i32) {
2427 /// self.0.push(elem);
2431 /// // and we'll implement IntoIterator
2432 /// impl IntoIterator for MyCollection {
2433 /// type Item = i32;
2434 /// type IntoIter = ::std::vec::IntoIter<i32>;
2436 /// fn into_iter(self) -> Self::IntoIter {
2437 /// self.0.into_iter()
2441 /// // Now we can make a new collection...
2442 /// let mut c = MyCollection::new();
2444 /// // ... add some stuff to it ...
2449 /// // ... and then turn it into an Iterator:
2450 /// for (i, n) in c.into_iter().enumerate() {
2451 /// assert_eq!(i as i32, n);
2454 #[stable(feature = "rust1", since = "1.0.0")]
2455 pub trait IntoIterator {
2456 /// The type of the elements being iterated over.
2457 #[stable(feature = "rust1", since = "1.0.0")]
2460 /// Which kind of iterator are we turning this into?
2461 #[stable(feature = "rust1", since = "1.0.0")]
2462 type IntoIter: Iterator<Item=Self::Item>;
2464 /// Consumes `Self` and returns an iterator over it.
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 fn into_iter(self) -> Self::IntoIter;
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 impl<I: Iterator> IntoIterator for I {
2471 type Item = I::Item;
2474 fn into_iter(self) -> I {
2479 /// Extend a collection with the contents of an iterator.
2481 /// Iterators produce a series of values, and collections can also be thought
2482 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2483 /// to extend a collection by including the contents of that iterator.
2490 /// // You can extend a String with some chars:
2491 /// let mut message = String::from("The first three letters are: ");
2493 /// message.extend(&['a', 'b', 'c']);
2495 /// assert_eq!("abc", &message[29..32]);
2498 /// Implementing `Extend`:
2501 /// // A sample collection, that's just a wrapper over Vec<T>
2502 /// #[derive(Debug)]
2503 /// struct MyCollection(Vec<i32>);
2505 /// // Let's give it some methods so we can create one and add things
2507 /// impl MyCollection {
2508 /// fn new() -> MyCollection {
2509 /// MyCollection(Vec::new())
2512 /// fn add(&mut self, elem: i32) {
2513 /// self.0.push(elem);
2517 /// // since MyCollection has a list of i32s, we implement Extend for i32
2518 /// impl Extend<i32> for MyCollection {
2520 /// // This is a bit simpler with the concrete type signature: we can call
2521 /// // extend on anything which can be turned into an Iterator which gives
2522 /// // us i32s. Because we need i32s to put into MyCollection.
2523 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2525 /// // The implementation is very straightforward: loop through the
2526 /// // iterator, and add() each element to ourselves.
2527 /// for elem in iterable {
2533 /// let mut c = MyCollection::new();
2539 /// // let's extend our collection with three more numbers
2540 /// c.extend(vec![1, 2, 3]);
2542 /// // we've added these elements onto the end
2543 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2545 #[stable(feature = "rust1", since = "1.0.0")]
2546 pub trait Extend<A> {
2547 /// Extends a collection with the contents of an iterator.
2549 /// As this is the only method for this trait, the [trait-level] docs
2550 /// contain more details.
2552 /// [trait-level]: trait.Extend.html
2559 /// // You can extend a String with some chars:
2560 /// let mut message = String::from("The first three letters are: ");
2562 /// message.extend(['a', 'b', 'c'].iter());
2564 /// assert_eq!("abc", &message[29..32]);
2566 #[stable(feature = "rust1", since = "1.0.0")]
2567 fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
2570 /// An iterator able to yield elements from both ends.
2572 /// Something that implements `DoubleEndedIterator` has one extra capability
2573 /// over something that implements [`Iterator`]: the ability to also take
2574 /// `Item`s from the back, as well as the front.
2576 /// It is important to note that both back and forth work on the same range,
2577 /// and do not cross: iteration is over when they meet in the middle.
2579 /// [`Iterator`]: trait.Iterator.html
2585 /// let numbers = vec![1, 2, 3];
2587 /// let mut iter = numbers.iter();
2589 /// let n = iter.next();
2590 /// assert_eq!(Some(&1), n);
2592 /// let n = iter.next_back();
2593 /// assert_eq!(Some(&3), n);
2595 /// let n = iter.next_back();
2596 /// assert_eq!(Some(&2), n);
2598 /// let n = iter.next();
2599 /// assert_eq!(None, n);
2601 /// let n = iter.next_back();
2602 /// assert_eq!(None, n);
2604 #[stable(feature = "rust1", since = "1.0.0")]
2605 pub trait DoubleEndedIterator: Iterator {
2606 /// An iterator able to yield elements from both ends.
2608 /// As this is the only method for this trait, the [trait-level] docs
2609 /// contain more details.
2611 /// [trait-level]: trait.DoubleEndedIterator.html
2618 /// let numbers = vec![1, 2, 3];
2620 /// let mut iter = numbers.iter();
2622 /// let n = iter.next();
2623 /// assert_eq!(Some(&1), n);
2625 /// let n = iter.next_back();
2626 /// assert_eq!(Some(&3), n);
2628 /// let n = iter.next_back();
2629 /// assert_eq!(Some(&2), n);
2631 /// let n = iter.next();
2632 /// assert_eq!(None, n);
2634 /// let n = iter.next_back();
2635 /// assert_eq!(None, n);
2637 #[stable(feature = "rust1", since = "1.0.0")]
2638 fn next_back(&mut self) -> Option<Self::Item>;
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2643 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2646 /// An iterator that knows its exact length.
2648 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2649 /// If an iterator knows how many times it can iterate, providing access to
2650 /// that information can be useful. For example, if you want to iterate
2651 /// backwards, a good start is to know where the end is.
2653 /// When implementing an `ExactSizeIterator`, You must also implement
2654 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2655 /// return the exact size of the iterator.
2657 /// [`Iterator`]: trait.Iterator.html
2658 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2660 /// The [`len()`] method has a default implementation, so you usually shouldn't
2661 /// implement it. However, you may be able to provide a more performant
2662 /// implementation than the default, so overriding it in this case makes sense.
2664 /// [`len()`]: #method.len
2671 /// // a finite range knows exactly how many times it will iterate
2672 /// let five = (0..5);
2674 /// assert_eq!(5, five.len());
2677 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2678 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2680 /// [moddocs]: index.html
2683 /// # struct Counter {
2686 /// # impl Counter {
2687 /// # fn new() -> Counter {
2688 /// # Counter { count: 0 }
2691 /// # impl Iterator for Counter {
2692 /// # type Item = usize;
2693 /// # fn next(&mut self) -> Option<usize> {
2694 /// # self.count += 1;
2695 /// # if self.count < 6 {
2696 /// # Some(self.count)
2702 /// impl ExactSizeIterator for Counter {
2703 /// // We already have the number of iterations, so we can use it directly.
2704 /// fn len(&self) -> usize {
2709 /// // And now we can use it!
2711 /// let counter = Counter::new();
2713 /// assert_eq!(0, counter.len());
2715 #[stable(feature = "rust1", since = "1.0.0")]
2716 pub trait ExactSizeIterator: Iterator {
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 /// Returns the exact number of times the iterator will iterate.
2721 /// This method has a default implementation, so you usually should not
2722 /// implement it directly. However, if you can provide a more efficient
2723 /// implementation, you can do so. See the [trait-level] docs for an
2726 /// [trait-level]: trait.ExactSizeIterator.html
2733 /// // a finite range knows exactly how many times it will iterate
2734 /// let five = (0..5);
2736 /// assert_eq!(5, five.len());
2738 fn len(&self) -> usize {
2739 let (lower, upper) = self.size_hint();
2740 // Note: This assertion is overly defensive, but it checks the invariant
2741 // guaranteed by the trait. If this trait were rust-internal,
2742 // we could use debug_assert!; assert_eq! will check all Rust user
2743 // implementations too.
2744 assert_eq!(upper, Some(lower));
2749 #[stable(feature = "rust1", since = "1.0.0")]
2750 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2752 // All adaptors that preserve the size of the wrapped iterator are fine
2753 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2754 #[stable(feature = "rust1", since = "1.0.0")]
2755 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2756 #[stable(feature = "rust1", since = "1.0.0")]
2757 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2760 #[stable(feature = "rust1", since = "1.0.0")]
2761 impl<I> ExactSizeIterator for Rev<I>
2762 where I: ExactSizeIterator + DoubleEndedIterator {}
2763 #[stable(feature = "rust1", since = "1.0.0")]
2764 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2765 F: FnMut(I::Item) -> B,
2767 #[stable(feature = "rust1", since = "1.0.0")]
2768 impl<A, B> ExactSizeIterator for Zip<A, B>
2769 where A: ExactSizeIterator, B: ExactSizeIterator {}
2771 /// An double-ended iterator with the direction inverted.
2773 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2774 /// documentation for more.
2776 /// [`rev()`]: trait.Iterator.html#method.rev
2777 /// [`Iterator`]: trait.Iterator.html
2779 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2780 #[stable(feature = "rust1", since = "1.0.0")]
2785 #[stable(feature = "rust1", since = "1.0.0")]
2786 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2787 type Item = <I as Iterator>::Item;
2790 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2792 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2795 #[stable(feature = "rust1", since = "1.0.0")]
2796 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2798 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2801 /// An iterator that clones the elements of an underlying iterator.
2803 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2804 /// documentation for more.
2806 /// [`cloned()`]: trait.Iterator.html#method.cloned
2807 /// [`Iterator`]: trait.Iterator.html
2808 #[stable(feature = "iter_cloned", since = "1.1.0")]
2809 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2811 pub struct Cloned<I> {
2815 #[stable(feature = "rust1", since = "1.0.0")]
2816 impl<'a, I, T: 'a> Iterator for Cloned<I>
2817 where I: Iterator<Item=&'a T>, T: Clone
2821 fn next(&mut self) -> Option<T> {
2822 self.it.next().cloned()
2825 fn size_hint(&self) -> (usize, Option<usize>) {
2830 #[stable(feature = "rust1", since = "1.0.0")]
2831 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
2832 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
2834 fn next_back(&mut self) -> Option<T> {
2835 self.it.next_back().cloned()
2839 #[stable(feature = "rust1", since = "1.0.0")]
2840 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
2841 where I: ExactSizeIterator<Item=&'a T>, T: Clone
2844 /// An iterator that repeats endlessly.
2846 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
2847 /// documentation for more.
2849 /// [`cycle()`]: trait.Iterator.html#method.cycle
2850 /// [`Iterator`]: trait.Iterator.html
2852 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 pub struct Cycle<I> {
2859 #[stable(feature = "rust1", since = "1.0.0")]
2860 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
2861 type Item = <I as Iterator>::Item;
2864 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2865 match self.iter.next() {
2866 None => { self.iter = self.orig.clone(); self.iter.next() }
2872 fn size_hint(&self) -> (usize, Option<usize>) {
2873 // the cycle iterator is either empty or infinite
2874 match self.orig.size_hint() {
2875 sz @ (0, Some(0)) => sz,
2876 (0, _) => (0, None),
2877 _ => (usize::MAX, None)
2882 /// An iterator that strings two iterators together.
2884 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
2885 /// documentation for more.
2887 /// [`chain()`]: trait.Iterator.html#method.chain
2888 /// [`Iterator`]: trait.Iterator.html
2890 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2891 #[stable(feature = "rust1", since = "1.0.0")]
2892 pub struct Chain<A, B> {
2898 // The iterator protocol specifies that iteration ends with the return value
2899 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
2900 // further calls return. The chain adaptor must account for this since it uses
2901 // two subiterators.
2903 // It uses three states:
2905 // - Both: `a` and `b` are remaining
2906 // - Front: `a` remaining
2907 // - Back: `b` remaining
2909 // The fourth state (neither iterator is remaining) only occurs after Chain has
2910 // returned None once, so we don't need to store this state.
2913 // both front and back iterator are remaining
2915 // only front is remaining
2917 // only back is remaining
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 impl<A, B> Iterator for Chain<A, B> where
2924 B: Iterator<Item = A::Item>
2926 type Item = A::Item;
2929 fn next(&mut self) -> Option<A::Item> {
2931 ChainState::Both => match self.a.next() {
2932 elt @ Some(..) => elt,
2934 self.state = ChainState::Back;
2938 ChainState::Front => self.a.next(),
2939 ChainState::Back => self.b.next(),
2944 fn count(self) -> usize {
2946 ChainState::Both => self.a.count() + self.b.count(),
2947 ChainState::Front => self.a.count(),
2948 ChainState::Back => self.b.count(),
2953 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
2955 ChainState::Both | ChainState::Front => {
2956 for x in self.a.by_ref() {
2962 if let ChainState::Both = self.state {
2963 self.state = ChainState::Back;
2966 ChainState::Back => {}
2968 if let ChainState::Back = self.state {
2976 fn last(self) -> Option<A::Item> {
2978 ChainState::Both => {
2979 // Must exhaust a before b.
2980 let a_last = self.a.last();
2981 let b_last = self.b.last();
2984 ChainState::Front => self.a.last(),
2985 ChainState::Back => self.b.last()
2990 fn size_hint(&self) -> (usize, Option<usize>) {
2991 let (a_lower, a_upper) = self.a.size_hint();
2992 let (b_lower, b_upper) = self.b.size_hint();
2994 let lower = a_lower.saturating_add(b_lower);
2996 let upper = match (a_upper, b_upper) {
2997 (Some(x), Some(y)) => x.checked_add(y),
3005 #[stable(feature = "rust1", since = "1.0.0")]
3006 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3007 A: DoubleEndedIterator,
3008 B: DoubleEndedIterator<Item=A::Item>,
3011 fn next_back(&mut self) -> Option<A::Item> {
3013 ChainState::Both => match self.b.next_back() {
3014 elt @ Some(..) => elt,
3016 self.state = ChainState::Front;
3020 ChainState::Front => self.a.next_back(),
3021 ChainState::Back => self.b.next_back(),
3026 /// An iterator that iterates two other iterators simultaneously.
3028 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3029 /// documentation for more.
3031 /// [`zip()`]: trait.Iterator.html#method.zip
3032 /// [`Iterator`]: trait.Iterator.html
3034 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3035 #[stable(feature = "rust1", since = "1.0.0")]
3036 pub struct Zip<A, B> {
3041 #[stable(feature = "rust1", since = "1.0.0")]
3042 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3044 type Item = (A::Item, B::Item);
3047 fn next(&mut self) -> Option<(A::Item, B::Item)> {
3048 self.a.next().and_then(|x| {
3049 self.b.next().and_then(|y| {
3056 fn size_hint(&self) -> (usize, Option<usize>) {
3057 let (a_lower, a_upper) = self.a.size_hint();
3058 let (b_lower, b_upper) = self.b.size_hint();
3060 let lower = cmp::min(a_lower, b_lower);
3062 let upper = match (a_upper, b_upper) {
3063 (Some(x), Some(y)) => Some(cmp::min(x,y)),
3064 (Some(x), None) => Some(x),
3065 (None, Some(y)) => Some(y),
3066 (None, None) => None
3073 #[stable(feature = "rust1", since = "1.0.0")]
3074 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3075 A: DoubleEndedIterator + ExactSizeIterator,
3076 B: DoubleEndedIterator + ExactSizeIterator,
3079 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3080 let a_sz = self.a.len();
3081 let b_sz = self.b.len();
3083 // Adjust a, b to equal length
3085 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3087 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3090 match (self.a.next_back(), self.b.next_back()) {
3091 (Some(x), Some(y)) => Some((x, y)),
3092 (None, None) => None,
3093 _ => unreachable!(),
3098 /// An iterator that maps the values of `iter` with `f`.
3100 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3101 /// documentation for more.
3103 /// [`map()`]: trait.Iterator.html#method.map
3104 /// [`Iterator`]: trait.Iterator.html
3105 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3106 #[stable(feature = "rust1", since = "1.0.0")]
3108 pub struct Map<I, F> {
3113 #[stable(feature = "rust1", since = "1.0.0")]
3114 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3118 fn next(&mut self) -> Option<B> {
3119 self.iter.next().map(&mut self.f)
3123 fn size_hint(&self) -> (usize, Option<usize>) {
3124 self.iter.size_hint()
3128 #[stable(feature = "rust1", since = "1.0.0")]
3129 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3130 F: FnMut(I::Item) -> B,
3133 fn next_back(&mut self) -> Option<B> {
3134 self.iter.next_back().map(&mut self.f)
3138 /// An iterator that filters the elements of `iter` with `predicate`.
3140 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3141 /// documentation for more.
3143 /// [`filter()`]: trait.Iterator.html#method.filter
3144 /// [`Iterator`]: trait.Iterator.html
3145 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3146 #[stable(feature = "rust1", since = "1.0.0")]
3148 pub struct Filter<I, P> {
3153 #[stable(feature = "rust1", since = "1.0.0")]
3154 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3155 type Item = I::Item;
3158 fn next(&mut self) -> Option<I::Item> {
3159 for x in self.iter.by_ref() {
3160 if (self.predicate)(&x) {
3168 fn size_hint(&self) -> (usize, Option<usize>) {
3169 let (_, upper) = self.iter.size_hint();
3170 (0, upper) // can't know a lower bound, due to the predicate
3174 #[stable(feature = "rust1", since = "1.0.0")]
3175 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3176 where P: FnMut(&I::Item) -> bool,
3179 fn next_back(&mut self) -> Option<I::Item> {
3180 for x in self.iter.by_ref().rev() {
3181 if (self.predicate)(&x) {
3189 /// An iterator that uses `f` to both filter and map elements from `iter`.
3191 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3192 /// documentation for more.
3194 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3195 /// [`Iterator`]: trait.Iterator.html
3196 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3197 #[stable(feature = "rust1", since = "1.0.0")]
3199 pub struct FilterMap<I, F> {
3204 #[stable(feature = "rust1", since = "1.0.0")]
3205 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3206 where F: FnMut(I::Item) -> Option<B>,
3211 fn next(&mut self) -> Option<B> {
3212 for x in self.iter.by_ref() {
3213 if let Some(y) = (self.f)(x) {
3221 fn size_hint(&self) -> (usize, Option<usize>) {
3222 let (_, upper) = self.iter.size_hint();
3223 (0, upper) // can't know a lower bound, due to the predicate
3227 #[stable(feature = "rust1", since = "1.0.0")]
3228 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3229 where F: FnMut(I::Item) -> Option<B>,
3232 fn next_back(&mut self) -> Option<B> {
3233 for x in self.iter.by_ref().rev() {
3234 if let Some(y) = (self.f)(x) {
3242 /// An iterator that yields the current count and the element during iteration.
3244 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3245 /// documentation for more.
3247 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3248 /// [`Iterator`]: trait.Iterator.html
3250 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3251 #[stable(feature = "rust1", since = "1.0.0")]
3252 pub struct Enumerate<I> {
3257 #[stable(feature = "rust1", since = "1.0.0")]
3258 impl<I> Iterator for Enumerate<I> where I: Iterator {
3259 type Item = (usize, <I as Iterator>::Item);
3261 /// # Overflow Behavior
3263 /// The method does no guarding against overflows, so enumerating more than
3264 /// `usize::MAX` elements either produces the wrong result or panics. If
3265 /// debug assertions are enabled, a panic is guaranteed.
3269 /// Might panic if the index of the element overflows a `usize`.
3271 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3272 self.iter.next().map(|a| {
3273 let ret = (self.count, a);
3274 // Possible undefined overflow.
3281 fn size_hint(&self) -> (usize, Option<usize>) {
3282 self.iter.size_hint()
3286 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3287 self.iter.nth(n).map(|a| {
3288 let i = self.count + n;
3295 fn count(self) -> usize {
3300 #[stable(feature = "rust1", since = "1.0.0")]
3301 impl<I> DoubleEndedIterator for Enumerate<I> where
3302 I: ExactSizeIterator + DoubleEndedIterator
3305 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3306 self.iter.next_back().map(|a| {
3307 let len = self.iter.len();
3308 // Can safely add, `ExactSizeIterator` promises that the number of
3309 // elements fits into a `usize`.
3310 (self.count + len, a)
3315 /// An iterator with a `peek()` that returns an optional reference to the next
3318 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3319 /// documentation for more.
3321 /// [`peekable()`]: trait.Iterator.html#method.peekable
3322 /// [`Iterator`]: trait.Iterator.html
3324 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3325 #[stable(feature = "rust1", since = "1.0.0")]
3326 pub struct Peekable<I: Iterator> {
3328 peeked: Option<I::Item>,
3331 #[stable(feature = "rust1", since = "1.0.0")]
3332 impl<I: Iterator> Iterator for Peekable<I> {
3333 type Item = I::Item;
3336 fn next(&mut self) -> Option<I::Item> {
3338 Some(_) => self.peeked.take(),
3339 None => self.iter.next(),
3344 fn count(self) -> usize {
3345 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3349 fn nth(&mut self, n: usize) -> Option<I::Item> {
3351 Some(_) if n == 0 => self.peeked.take(),
3356 None => self.iter.nth(n)
3361 fn last(self) -> Option<I::Item> {
3362 self.iter.last().or(self.peeked)
3366 fn size_hint(&self) -> (usize, Option<usize>) {
3367 let (lo, hi) = self.iter.size_hint();
3368 if self.peeked.is_some() {
3369 let lo = lo.saturating_add(1);
3370 let hi = hi.and_then(|x| x.checked_add(1));
3378 #[stable(feature = "rust1", since = "1.0.0")]
3379 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3381 #[stable(feature = "rust1", since = "1.0.0")]
3382 impl<I: Iterator> Peekable<I> {
3383 /// Returns a reference to the next() value without advancing the iterator.
3385 /// The `peek()` method will return the value that a call to [`next()`] would
3386 /// return, but does not advance the iterator. Like [`next()`], if there is
3387 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3388 /// will return `None`.
3390 /// [`next()`]: trait.Iterator.html#tymethod.next
3392 /// Because `peek()` returns reference, and many iterators iterate over
3393 /// references, this leads to a possibly confusing situation where the
3394 /// return value is a double reference. You can see this effect in the
3395 /// examples below, with `&&i32`.
3402 /// let xs = [1, 2, 3];
3404 /// let mut iter = xs.iter().peekable();
3406 /// // peek() lets us see into the future
3407 /// assert_eq!(iter.peek(), Some(&&1));
3408 /// assert_eq!(iter.next(), Some(&1));
3410 /// assert_eq!(iter.next(), Some(&2));
3412 /// // we can peek() multiple times, the itererator won't advance
3413 /// assert_eq!(iter.peek(), Some(&&3));
3414 /// assert_eq!(iter.peek(), Some(&&3));
3416 /// assert_eq!(iter.next(), Some(&3));
3418 /// // after the itererator is finished, so is peek()
3419 /// assert_eq!(iter.peek(), None);
3420 /// assert_eq!(iter.next(), None);
3423 #[stable(feature = "rust1", since = "1.0.0")]
3424 pub fn peek(&mut self) -> Option<&I::Item> {
3425 if self.peeked.is_none() {
3426 self.peeked = self.iter.next();
3429 Some(ref value) => Some(value),
3434 /// Checks if the iterator has finished iterating.
3436 /// Returns `true` if there are no more elements in the iterator, and
3437 /// `false` if there are.
3444 /// #![feature(core)]
3446 /// let xs = [1, 2, 3];
3448 /// let mut iter = xs.iter().peekable();
3450 /// // there are still elements to iterate over
3451 /// assert_eq!(iter.is_empty(), false);
3453 /// // let's consume the iterator
3458 /// assert_eq!(iter.is_empty(), true);
3461 pub fn is_empty(&mut self) -> bool {
3462 self.peek().is_none()
3466 /// An iterator that rejects elements while `predicate` is true.
3468 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3469 /// documentation for more.
3471 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3472 /// [`Iterator`]: trait.Iterator.html
3473 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3474 #[stable(feature = "rust1", since = "1.0.0")]
3476 pub struct SkipWhile<I, P> {
3482 #[stable(feature = "rust1", since = "1.0.0")]
3483 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3484 where P: FnMut(&I::Item) -> bool
3486 type Item = I::Item;
3489 fn next(&mut self) -> Option<I::Item> {
3490 for x in self.iter.by_ref() {
3491 if self.flag || !(self.predicate)(&x) {
3500 fn size_hint(&self) -> (usize, Option<usize>) {
3501 let (_, upper) = self.iter.size_hint();
3502 (0, upper) // can't know a lower bound, due to the predicate
3506 /// An iterator that only accepts elements while `predicate` is true.
3508 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3509 /// documentation for more.
3511 /// [`take_while()`]: trait.Iterator.html#method.take_while
3512 /// [`Iterator`]: trait.Iterator.html
3513 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3514 #[stable(feature = "rust1", since = "1.0.0")]
3516 pub struct TakeWhile<I, P> {
3522 #[stable(feature = "rust1", since = "1.0.0")]
3523 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3524 where P: FnMut(&I::Item) -> bool
3526 type Item = I::Item;
3529 fn next(&mut self) -> Option<I::Item> {
3533 self.iter.next().and_then(|x| {
3534 if (self.predicate)(&x) {
3545 fn size_hint(&self) -> (usize, Option<usize>) {
3546 let (_, upper) = self.iter.size_hint();
3547 (0, upper) // can't know a lower bound, due to the predicate
3551 /// An iterator that skips over `n` elements of `iter`.
3553 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3554 /// documentation for more.
3556 /// [`skip()`]: trait.Iterator.html#method.skip
3557 /// [`Iterator`]: trait.Iterator.html
3559 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3560 #[stable(feature = "rust1", since = "1.0.0")]
3561 pub struct Skip<I> {
3566 #[stable(feature = "rust1", since = "1.0.0")]
3567 impl<I> Iterator for Skip<I> where I: Iterator {
3568 type Item = <I as Iterator>::Item;
3571 fn next(&mut self) -> Option<I::Item> {
3577 self.iter.nth(old_n)
3582 fn nth(&mut self, n: usize) -> Option<I::Item> {
3583 // Can't just add n + self.n due to overflow.
3587 let to_skip = self.n;
3590 if self.iter.nth(to_skip-1).is_none() {
3598 fn count(self) -> usize {
3599 self.iter.count().saturating_sub(self.n)
3603 fn last(mut self) -> Option<I::Item> {
3607 let next = self.next();
3609 // recurse. n should be 0.
3610 self.last().or(next)
3618 fn size_hint(&self) -> (usize, Option<usize>) {
3619 let (lower, upper) = self.iter.size_hint();
3621 let lower = lower.saturating_sub(self.n);
3622 let upper = upper.map(|x| x.saturating_sub(self.n));
3628 #[stable(feature = "rust1", since = "1.0.0")]
3629 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3631 /// An iterator that only iterates over the first `n` iterations of `iter`.
3633 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3634 /// documentation for more.
3636 /// [`take()`]: trait.Iterator.html#method.take
3637 /// [`Iterator`]: trait.Iterator.html
3639 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3640 #[stable(feature = "rust1", since = "1.0.0")]
3641 pub struct Take<I> {
3646 #[stable(feature = "rust1", since = "1.0.0")]
3647 impl<I> Iterator for Take<I> where I: Iterator{
3648 type Item = <I as Iterator>::Item;
3651 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3661 fn nth(&mut self, n: usize) -> Option<I::Item> {
3667 self.iter.nth(self.n - 1);
3675 fn size_hint(&self) -> (usize, Option<usize>) {
3676 let (lower, upper) = self.iter.size_hint();
3678 let lower = cmp::min(lower, self.n);
3680 let upper = match upper {
3681 Some(x) if x < self.n => Some(x),
3689 #[stable(feature = "rust1", since = "1.0.0")]
3690 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3693 /// An iterator to maintain state while iterating another iterator.
3695 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3696 /// documentation for more.
3698 /// [`scan()`]: trait.Iterator.html#method.scan
3699 /// [`Iterator`]: trait.Iterator.html
3700 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3701 #[stable(feature = "rust1", since = "1.0.0")]
3703 pub struct Scan<I, St, F> {
3709 #[stable(feature = "rust1", since = "1.0.0")]
3710 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3712 F: FnMut(&mut St, I::Item) -> Option<B>,
3717 fn next(&mut self) -> Option<B> {
3718 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3722 fn size_hint(&self) -> (usize, Option<usize>) {
3723 let (_, upper) = self.iter.size_hint();
3724 (0, upper) // can't know a lower bound, due to the scan function
3728 /// An iterator that maps each element to an iterator, and yields the elements
3729 /// of the produced iterators.
3731 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3732 /// documentation for more.
3734 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
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 FlatMap<I, U: IntoIterator, F> {
3742 frontiter: Option<U::IntoIter>,
3743 backiter: Option<U::IntoIter>,
3746 #[stable(feature = "rust1", since = "1.0.0")]
3747 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
3748 where F: FnMut(I::Item) -> U,
3750 type Item = U::Item;
3753 fn next(&mut self) -> Option<U::Item> {
3755 if let Some(ref mut inner) = self.frontiter {
3756 if let Some(x) = inner.by_ref().next() {
3760 match self.iter.next().map(&mut self.f) {
3761 None => return self.backiter.as_mut().and_then(|it| it.next()),
3762 next => self.frontiter = next.map(IntoIterator::into_iter),
3768 fn size_hint(&self) -> (usize, Option<usize>) {
3769 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3770 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3771 let lo = flo.saturating_add(blo);
3772 match (self.iter.size_hint(), fhi, bhi) {
3773 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
3779 #[stable(feature = "rust1", since = "1.0.0")]
3780 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
3781 F: FnMut(I::Item) -> U,
3783 U::IntoIter: DoubleEndedIterator
3786 fn next_back(&mut self) -> Option<U::Item> {
3788 if let Some(ref mut inner) = self.backiter {
3789 if let Some(y) = inner.next_back() {
3793 match self.iter.next_back().map(&mut self.f) {
3794 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
3795 next => self.backiter = next.map(IntoIterator::into_iter),
3801 /// An iterator that yields `None` forever after the underlying iterator
3802 /// yields `None` once.
3804 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
3805 /// documentation for more.
3807 /// [`fuse()`]: trait.Iterator.html#method.fuse
3808 /// [`Iterator`]: trait.Iterator.html
3810 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3811 #[stable(feature = "rust1", since = "1.0.0")]
3812 pub struct Fuse<I> {
3817 #[stable(feature = "rust1", since = "1.0.0")]
3818 impl<I> Iterator for Fuse<I> where I: Iterator {
3819 type Item = <I as Iterator>::Item;
3822 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3826 let next = self.iter.next();
3827 self.done = next.is_none();
3833 fn nth(&mut self, n: usize) -> Option<I::Item> {
3837 let nth = self.iter.nth(n);
3838 self.done = nth.is_none();
3844 fn last(self) -> Option<I::Item> {
3853 fn count(self) -> usize {
3862 fn size_hint(&self) -> (usize, Option<usize>) {
3866 self.iter.size_hint()
3871 #[stable(feature = "rust1", since = "1.0.0")]
3872 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
3874 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
3878 let next = self.iter.next_back();
3879 self.done = next.is_none();
3885 #[stable(feature = "rust1", since = "1.0.0")]
3886 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
3888 /// An iterator that calls a function with a reference to each element before
3891 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
3892 /// documentation for more.
3894 /// [`inspect()`]: trait.Iterator.html#method.inspect
3895 /// [`Iterator`]: trait.Iterator.html
3896 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3897 #[stable(feature = "rust1", since = "1.0.0")]
3899 pub struct Inspect<I, F> {
3904 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
3906 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
3907 if let Some(ref a) = elt {
3915 #[stable(feature = "rust1", since = "1.0.0")]
3916 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
3917 type Item = I::Item;
3920 fn next(&mut self) -> Option<I::Item> {
3921 let next = self.iter.next();
3922 self.do_inspect(next)
3926 fn size_hint(&self) -> (usize, Option<usize>) {
3927 self.iter.size_hint()
3931 #[stable(feature = "rust1", since = "1.0.0")]
3932 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
3933 where F: FnMut(&I::Item),
3936 fn next_back(&mut self) -> Option<I::Item> {
3937 let next = self.iter.next_back();
3938 self.do_inspect(next)
3942 /// Objects that can be stepped over in both directions.
3944 /// The `steps_between` function provides a way to efficiently compare
3945 /// two `Step` objects.
3946 #[unstable(feature = "step_trait",
3947 reason = "likely to be replaced by finer-grained traits",
3949 pub trait Step: PartialOrd + Sized {
3950 /// Steps `self` if possible.
3951 fn step(&self, by: &Self) -> Option<Self>;
3953 /// Returns the number of steps between two step objects. The count is
3954 /// inclusive of `start` and exclusive of `end`.
3956 /// Returns `None` if it is not possible to calculate `steps_between`
3957 /// without overflow.
3958 fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
3961 macro_rules! step_impl_unsigned {
3965 fn step(&self, by: &$t) -> Option<$t> {
3966 (*self).checked_add(*by)
3969 #[allow(trivial_numeric_casts)]
3970 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
3971 if *by == 0 { return None; }
3973 // Note: We assume $t <= usize here
3974 let diff = (*end - *start) as usize;
3975 let by = *by as usize;
3988 macro_rules! step_impl_signed {
3992 fn step(&self, by: &$t) -> Option<$t> {
3993 (*self).checked_add(*by)
3996 #[allow(trivial_numeric_casts)]
3997 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
3998 if *by == 0 { return None; }
4005 // Note: We assume $t <= isize here
4006 // Use .wrapping_sub and cast to usize to compute the
4007 // difference that may not fit inside the range of isize.
4008 diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4009 by_u = *by as usize;
4014 diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4015 by_u = (*by as isize).wrapping_mul(-1) as usize;
4017 if diff % by_u > 0 {
4018 Some(diff / by_u + 1)
4027 macro_rules! step_impl_no_between {
4031 fn step(&self, by: &$t) -> Option<$t> {
4032 (*self).checked_add(*by)
4035 fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4042 step_impl_unsigned!(usize u8 u16 u32);
4043 step_impl_signed!(isize i8 i16 i32);
4044 #[cfg(target_pointer_width = "64")]
4045 step_impl_unsigned!(u64);
4046 #[cfg(target_pointer_width = "64")]
4047 step_impl_signed!(i64);
4048 // If the target pointer width is not 64-bits, we
4049 // assume here that it is less than 64-bits.
4050 #[cfg(not(target_pointer_width = "64"))]
4051 step_impl_no_between!(u64 i64);
4053 /// An adapter for stepping range iterators by a custom amount.
4055 /// The resulting iterator handles overflow by stopping. The `A`
4056 /// parameter is the type being iterated over, while `R` is the range
4057 /// type (usually one of `std::ops::{Range, RangeFrom}`.
4059 #[unstable(feature = "step_by", reason = "recent addition",
4061 pub struct StepBy<A, R> {
4066 impl<A: Step> RangeFrom<A> {
4067 /// Creates an iterator starting at the same point, but stepping by
4068 /// the given amount at each iteration.
4073 /// for i in (0u8..).step_by(2) {
4074 /// println!("{}", i);
4078 /// This prints all even `u8` values.
4079 #[unstable(feature = "step_by", reason = "recent addition",
4081 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4089 impl<A: Step> ops::Range<A> {
4090 /// Creates an iterator with the same range, but stepping by the
4091 /// given amount at each iteration.
4093 /// The resulting iterator handles overflow by stopping.
4098 /// #![feature(step_by)]
4100 /// for i in (0..10).step_by(2) {
4101 /// println!("{}", i);
4114 #[unstable(feature = "step_by", reason = "recent addition",
4116 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4124 #[stable(feature = "rust1", since = "1.0.0")]
4125 impl<A> Iterator for StepBy<A, RangeFrom<A>> where
4127 for<'a> &'a A: Add<&'a A, Output = A>
4132 fn next(&mut self) -> Option<A> {
4133 let mut n = &self.range.start + &self.step_by;
4134 mem::swap(&mut n, &mut self.range.start);
4139 fn size_hint(&self) -> (usize, Option<usize>) {
4140 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4144 /// An iterator over the range [start, stop]
4146 #[unstable(feature = "range_inclusive",
4147 reason = "likely to be replaced by range notation and adapters",
4149 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4150 #[allow(deprecated)]
4151 pub struct RangeInclusive<A> {
4152 range: ops::Range<A>,
4156 /// Returns an iterator over the range [start, stop].
4158 #[unstable(feature = "range_inclusive",
4159 reason = "likely to be replaced by range notation and adapters",
4161 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4162 #[allow(deprecated)]
4163 pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
4164 where A: Step + One + Clone
4172 #[unstable(feature = "range_inclusive",
4173 reason = "likely to be replaced by range notation and adapters",
4175 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4176 #[allow(deprecated)]
4177 impl<A> Iterator for RangeInclusive<A> where
4178 A: PartialEq + Step + One + Clone,
4179 for<'a> &'a A: Add<&'a A, Output = A>
4184 fn next(&mut self) -> Option<A> {
4185 self.range.next().or_else(|| {
4186 if !self.done && self.range.start == self.range.end {
4188 Some(self.range.end.clone())
4196 fn size_hint(&self) -> (usize, Option<usize>) {
4197 let (lo, hi) = self.range.size_hint();
4201 let lo = lo.saturating_add(1);
4202 let hi = hi.and_then(|x| x.checked_add(1));
4208 #[unstable(feature = "range_inclusive",
4209 reason = "likely to be replaced by range notation and adapters",
4211 #[deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4212 #[allow(deprecated)]
4213 impl<A> DoubleEndedIterator for RangeInclusive<A> where
4214 A: PartialEq + Step + One + Clone,
4215 for<'a> &'a A: Add<&'a A, Output = A>,
4216 for<'a> &'a A: Sub<Output=A>
4219 fn next_back(&mut self) -> Option<A> {
4220 if self.range.end > self.range.start {
4221 let result = self.range.end.clone();
4222 self.range.end = &self.range.end - &A::one();
4224 } else if !self.done && self.range.start == self.range.end {
4226 Some(self.range.end.clone())
4233 #[stable(feature = "rust1", since = "1.0.0")]
4234 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4238 fn next(&mut self) -> Option<A> {
4239 let rev = self.step_by < A::zero();
4240 if (rev && self.range.start > self.range.end) ||
4241 (!rev && self.range.start < self.range.end)
4243 match self.range.start.step(&self.step_by) {
4245 mem::swap(&mut self.range.start, &mut n);
4249 let mut n = self.range.end.clone();
4250 mem::swap(&mut self.range.start, &mut n);
4260 fn size_hint(&self) -> (usize, Option<usize>) {
4261 match Step::steps_between(&self.range.start,
4264 Some(hint) => (hint, Some(hint)),
4270 macro_rules! range_exact_iter_impl {
4272 #[stable(feature = "rust1", since = "1.0.0")]
4273 impl ExactSizeIterator for ops::Range<$t> { }
4277 #[stable(feature = "rust1", since = "1.0.0")]
4278 impl<A: Step + One> Iterator for ops::Range<A> where
4279 for<'a> &'a A: Add<&'a A, Output = A>
4284 fn next(&mut self) -> Option<A> {
4285 if self.start < self.end {
4286 let mut n = &self.start + &A::one();
4287 mem::swap(&mut n, &mut self.start);
4295 fn size_hint(&self) -> (usize, Option<usize>) {
4296 match Step::steps_between(&self.start, &self.end, &A::one()) {
4297 Some(hint) => (hint, Some(hint)),
4303 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4304 // a length <= usize::MAX, which is required by ExactSizeIterator.
4305 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4307 #[stable(feature = "rust1", since = "1.0.0")]
4308 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4309 for<'a> &'a A: Add<&'a A, Output = A>,
4310 for<'a> &'a A: Sub<&'a A, Output = A>
4313 fn next_back(&mut self) -> Option<A> {
4314 if self.start < self.end {
4315 self.end = &self.end - &A::one();
4316 Some(self.end.clone())
4323 #[stable(feature = "rust1", since = "1.0.0")]
4324 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4325 for<'a> &'a A: Add<&'a A, Output = A>
4330 fn next(&mut self) -> Option<A> {
4331 let mut n = &self.start + &A::one();
4332 mem::swap(&mut n, &mut self.start);
4337 /// An iterator that repeats an element endlessly.
4339 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4341 /// [`repeat()`]: fn.repeat.html
4343 #[stable(feature = "rust1", since = "1.0.0")]
4344 pub struct Repeat<A> {
4348 #[stable(feature = "rust1", since = "1.0.0")]
4349 impl<A: Clone> Iterator for Repeat<A> {
4353 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4355 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4358 #[stable(feature = "rust1", since = "1.0.0")]
4359 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4361 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4364 /// Creates a new iterator that endlessly repeats a single element.
4366 /// The `repeat()` function repeats a single value over and over and over and
4367 /// over and over and 🔁.
4369 /// Infinite iterators like `repeat()` are often used with adapters like
4370 /// [`take()`], in order to make them finite.
4372 /// [`take()`]: trait.Iterator.html#method.take
4381 /// // the number four 4ever:
4382 /// let mut fours = iter::repeat(4);
4384 /// assert_eq!(Some(4), fours.next());
4385 /// assert_eq!(Some(4), fours.next());
4386 /// assert_eq!(Some(4), fours.next());
4387 /// assert_eq!(Some(4), fours.next());
4388 /// assert_eq!(Some(4), fours.next());
4390 /// // yup, still four
4391 /// assert_eq!(Some(4), fours.next());
4394 /// Going finite with [`take()`]:
4399 /// // that last example was too many fours. Let's only have four fours.
4400 /// let mut four_fours = iter::repeat(4).take(4);
4402 /// assert_eq!(Some(4), four_fours.next());
4403 /// assert_eq!(Some(4), four_fours.next());
4404 /// assert_eq!(Some(4), four_fours.next());
4405 /// assert_eq!(Some(4), four_fours.next());
4407 /// // ... and now we're done
4408 /// assert_eq!(None, four_fours.next());
4411 #[stable(feature = "rust1", since = "1.0.0")]
4412 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4413 Repeat{element: elt}
4416 /// An iterator that yields nothing.
4418 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4420 /// [`empty()`]: fn.empty.html
4421 #[stable(feature = "iter_empty", since = "1.2.0")]
4422 pub struct Empty<T>(marker::PhantomData<T>);
4424 #[stable(feature = "iter_empty", since = "1.2.0")]
4425 impl<T> Iterator for Empty<T> {
4428 fn next(&mut self) -> Option<T> {
4432 fn size_hint(&self) -> (usize, Option<usize>){
4437 #[stable(feature = "iter_empty", since = "1.2.0")]
4438 impl<T> DoubleEndedIterator for Empty<T> {
4439 fn next_back(&mut self) -> Option<T> {
4444 #[stable(feature = "iter_empty", since = "1.2.0")]
4445 impl<T> ExactSizeIterator for Empty<T> {
4446 fn len(&self) -> usize {
4451 // not #[derive] because that adds a Clone bound on T,
4452 // which isn't necessary.
4453 #[stable(feature = "iter_empty", since = "1.2.0")]
4454 impl<T> Clone for Empty<T> {
4455 fn clone(&self) -> Empty<T> {
4456 Empty(marker::PhantomData)
4460 // not #[derive] because that adds a Default bound on T,
4461 // which isn't necessary.
4462 #[stable(feature = "iter_empty", since = "1.2.0")]
4463 impl<T> Default for Empty<T> {
4464 fn default() -> Empty<T> {
4465 Empty(marker::PhantomData)
4469 /// Creates an iterator that yields nothing.
4478 /// // this could have been an iterator over i32, but alas, it's just not.
4479 /// let mut nope = iter::empty::<i32>();
4481 /// assert_eq!(None, nope.next());
4483 #[stable(feature = "iter_empty", since = "1.2.0")]
4484 pub fn empty<T>() -> Empty<T> {
4485 Empty(marker::PhantomData)
4488 /// An iterator that yields an element exactly once.
4490 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4492 /// [`once()`]: fn.once.html
4494 #[stable(feature = "iter_once", since = "1.2.0")]
4495 pub struct Once<T> {
4496 inner: ::option::IntoIter<T>
4499 #[stable(feature = "iter_once", since = "1.2.0")]
4500 impl<T> Iterator for Once<T> {
4503 fn next(&mut self) -> Option<T> {
4507 fn size_hint(&self) -> (usize, Option<usize>) {
4508 self.inner.size_hint()
4512 #[stable(feature = "iter_once", since = "1.2.0")]
4513 impl<T> DoubleEndedIterator for Once<T> {
4514 fn next_back(&mut self) -> Option<T> {
4515 self.inner.next_back()
4519 #[stable(feature = "iter_once", since = "1.2.0")]
4520 impl<T> ExactSizeIterator for Once<T> {
4521 fn len(&self) -> usize {
4526 /// Creates an iterator that yields an element exactly once.
4528 /// This is commonly used to adapt a single value into a [`chain()`] of other
4529 /// kinds of iteration. Maybe you have an iterator that covers almost
4530 /// everything, but you need an extra special case. Maybe you have a function
4531 /// which works on iterators, but you only need to process one value.
4533 /// [`chain()`]: trait.Iterator.html#method.chain
4542 /// // one is the loneliest number
4543 /// let mut one = iter::once(1);
4545 /// assert_eq!(Some(1), one.next());
4547 /// // just one, that's all we get
4548 /// assert_eq!(None, one.next());
4551 /// Chaining together with another iterator. Let's say that we want to iterate
4552 /// over each file of the `.foo` directory, but also a configuration file,
4558 /// use std::path::PathBuf;
4560 /// let dirs = fs::read_dir(".foo").unwrap();
4562 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4563 /// // PathBufs, so we use map
4564 /// let dirs = dirs.map(|file| file.unwrap().path());
4566 /// // now, our iterator just for our config file
4567 /// let config = iter::once(PathBuf::from(".foorc"));
4569 /// // chain the two iterators together into one big iterator
4570 /// let files = dirs.chain(config);
4572 /// // this will give us all of the files in .foo as well as .foorc
4573 /// for f in files {
4574 /// println!("{:?}", f);
4577 #[stable(feature = "iter_once", since = "1.2.0")]
4578 pub fn once<T>(value: T) -> Once<T> {
4579 Once { inner: Some(value).into_iter() }
4582 /// Functions for lexicographical ordering of sequences.
4584 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
4585 /// that the elements implement both `PartialEq` and `PartialOrd`.
4587 /// If two sequences are equal up until the point where one ends,
4588 /// the shorter sequence compares less.
4589 #[deprecated(since = "1.4.0", reason = "use the equivalent methods on `Iterator` instead")]
4590 #[unstable(feature = "iter_order_deprecated", reason = "needs review and revision",
4594 use cmp::{Eq, Ord, PartialOrd, PartialEq};
4596 use super::Iterator;
4598 /// Compare `a` and `b` for equality using `Eq`
4599 pub fn equals<A, L, R>(a: L, b: R) -> bool where
4601 L: Iterator<Item=A>,
4602 R: Iterator<Item=A>,
4607 /// Order `a` and `b` lexicographically using `Ord`
4608 pub fn cmp<A, L, R>(a: L, b: R) -> cmp::Ordering where
4610 L: Iterator<Item=A>,
4611 R: Iterator<Item=A>,
4616 /// Order `a` and `b` lexicographically using `PartialOrd`
4617 pub fn partial_cmp<L: Iterator, R: Iterator>(a: L, b: R) -> Option<cmp::Ordering> where
4618 L::Item: PartialOrd<R::Item>
4623 /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
4624 pub fn eq<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4625 L::Item: PartialEq<R::Item>,
4630 /// Compares `a` and `b` for nonequality (Using partial equality, `PartialEq`)
4631 pub fn ne<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4632 L::Item: PartialEq<R::Item>,
4637 /// Returns `a` < `b` lexicographically (Using partial order, `PartialOrd`)
4638 pub fn lt<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4639 L::Item: PartialOrd<R::Item>,
4644 /// Returns `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
4645 pub fn le<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4646 L::Item: PartialOrd<R::Item>,
4651 /// Returns `a` > `b` lexicographically (Using partial order, `PartialOrd`)
4652 pub fn gt<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4653 L::Item: PartialOrd<R::Item>,
4658 /// Returns `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
4659 pub fn ge<L: Iterator, R: Iterator>(a: L, b: R) -> bool where
4660 L::Item: PartialOrd<R::Item>,