1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Composable external iteration
13 //! If you've found yourself with a collection of some kind, and needed to
14 //! perform an operation on the elements of said collection, you'll quickly run
15 //! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
16 //! it's worth becoming familiar with them.
18 //! Before explaining more, let's talk about how this module is structured:
22 //! This module is largely organized by type:
24 //! * [Traits] are the core portion: these traits define what kind of iterators
25 //! exist and what you can do with them. The methods of these traits are worth
26 //! putting some extra study time into.
27 //! * [Functions] provide some helpful ways to create some basic iterators.
28 //! * [Structs] are often the return types of the various methods on this
29 //! module's traits. You'll usually want to look at the method that creates
30 //! the `struct`, rather than the `struct` itself. For more detail about why,
31 //! see '[Implementing Iterator](#implementing-iterator)'.
34 //! [Functions]: #functions
35 //! [Structs]: #structs
37 //! That's it! Let's dig into iterators.
41 //! The heart and soul of this module is the [`Iterator`] trait. The core of
42 //! [`Iterator`] looks like this:
47 //! fn next(&mut self) -> Option<Self::Item>;
51 //! An iterator has a method, [`next()`], which when called, returns an
52 //! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
53 //! are elements, and once they've all been exhausted, will return `None` to
54 //! indicate that iteration is finished. Individual iterators may choose to
55 //! resume iteration, and so calling [`next()`] again may or may not eventually
56 //! start returning `Some(Item)` again at some point.
58 //! [`Iterator`]'s full definition includes a number of other methods as well,
59 //! but they are default methods, built on top of [`next()`], and so you get
62 //! Iterators are also composable, and it's common to chain them together to do
63 //! more complex forms of processing. See the [Adapters](#adapters) section
64 //! below for more details.
66 //! [`Iterator`]: trait.Iterator.html
67 //! [`next()`]: trait.Iterator.html#tymethod.next
68 //! [`Option`]: ../option/enum.Option.html
70 //! # The three forms of iteration
72 //! There are three common methods which can create iterators from a collection:
74 //! * `iter()`, which iterates over `&T`.
75 //! * `iter_mut()`, which iterates over `&mut T`.
76 //! * `into_iter()`, which iterates over `T`.
78 //! Various things in the standard library may implement one or more of the
79 //! three, where appropriate.
81 //! # Implementing Iterator
83 //! Creating an iterator of your own involves two steps: creating a `struct` to
84 //! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
85 //! `struct`. This is why there are so many `struct`s in this module: there is
86 //! one for each iterator and iterator adapter.
88 //! Let's make an iterator named `Counter` which counts from `1` to `5`:
91 //! // First, the struct:
93 //! /// An iterator which counts from one to five
98 //! // we want our count to start at one, so let's add a new() method to help.
99 //! // This isn't strictly necessary, but is convenient. Note that we start
100 //! // `count` at zero, we'll see why in `next()`'s implementation below.
102 //! fn new() -> Counter {
103 //! Counter { count: 0 }
107 //! // Then, we implement `Iterator` for our `Counter`:
109 //! impl Iterator for Counter {
110 //! // we will be counting with usize
111 //! type Item = usize;
113 //! // next() is the only required method
114 //! fn next(&mut self) -> Option<usize> {
115 //! // increment our count. This is why we started at zero.
118 //! // check to see if we've finished counting or not.
119 //! if self.count < 6 {
127 //! // And now we can use it!
129 //! let mut counter = Counter::new();
131 //! let x = counter.next().unwrap();
132 //! println!("{}", x);
134 //! let x = counter.next().unwrap();
135 //! println!("{}", x);
137 //! let x = counter.next().unwrap();
138 //! println!("{}", x);
140 //! let x = counter.next().unwrap();
141 //! println!("{}", x);
143 //! let x = counter.next().unwrap();
144 //! println!("{}", x);
147 //! This will print `1` through `5`, each on their own line.
149 //! Calling `next()` this way gets repetitive. Rust has a construct which can
150 //! call `next()` on your iterator, until it reaches `None`. Let's go over that
153 //! # for Loops and IntoIterator
155 //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
156 //! example of `for`:
159 //! let values = vec![1, 2, 3, 4, 5];
161 //! for x in values {
162 //! println!("{}", x);
166 //! This will print the numbers one through five, each on their own line. But
167 //! you'll notice something here: we never called anything on our vector to
168 //! produce an iterator. What gives?
170 //! There's a trait in the standard library for converting something into an
171 //! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
172 //! which converts the thing implementing [`IntoIterator`] into an iterator.
173 //! Let's take a look at that `for` loop again, and what the compiler converts
176 //! [`IntoIterator`]: trait.IntoIterator.html
177 //! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
180 //! let values = vec![1, 2, 3, 4, 5];
182 //! for x in values {
183 //! println!("{}", x);
187 //! Rust de-sugars this into:
190 //! let values = vec![1, 2, 3, 4, 5];
192 //! let result = match values.into_iter() {
193 //! mut iter => loop {
194 //! match iter.next() {
195 //! Some(x) => { println!("{}", x); },
204 //! First, we call `into_iter()` on the value. Then, we match on the iterator
205 //! that returns, calling [`next()`] over and over until we see a `None`. At
206 //! that point, we `break` out of the loop, and we're done iterating.
208 //! There's one more subtle bit here: the standard library contains an
209 //! interesting implementation of [`IntoIterator`]:
212 //! impl<I: Iterator> IntoIterator for I
215 //! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
216 //! returning themselves. This means two things:
218 //! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
219 //! 2. If you're creating a collection, implementing [`IntoIterator`] for it
220 //! will allow your collection to be used with the `for` loop.
224 //! Functions which take an [`Iterator`] and return another [`Iterator`] are
225 //! often called 'iterator adapters', as they're a form of the 'adapter
228 //! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
229 //! For more, see their documentation.
231 //! [`map()`]: trait.Iterator.html#method.map
232 //! [`take()`]: trait.Iterator.html#method.take
233 //! [`collect()`]: trait.Iterator.html#method.collect
237 //! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
238 //! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
239 //! until you call [`next()`]. This is sometimes a source of confusion when
240 //! creating an iterator solely for its side effects. For example, the [`map()`]
241 //! method calls a closure on each element it iterates over:
244 //! # #![allow(unused_must_use)]
245 //! let v = vec![1, 2, 3, 4, 5];
246 //! v.iter().map(|x| println!("{}", x));
249 //! This will not print any values, as we only created an iterator, rather than
250 //! using it. The compiler will warn us about this kind of behavior:
253 //! warning: unused result which must be used: iterator adaptors are lazy and
254 //! do nothing unless consumed
257 //! The idiomatic way to write a [`map()`] for its side effects is to use a
258 //! `for` loop instead:
261 //! let v = vec![1, 2, 3, 4, 5];
264 //! println!("{}", x);
268 //! [`map()`]: trait.Iterator.html#method.map
270 //! The two most common ways to evaluate an iterator are to use a `for` loop
271 //! like this, or using the [`collect()`] adapter to produce a new collection.
273 //! [`collect()`]: trait.Iterator.html#method.collect
277 //! Iterators do not have to be finite. As an example, an open-ended range is
278 //! an infinite iterator:
281 //! let numbers = 0..;
284 //! It is common to use the [`take()`] iterator adapter to turn an infinite
285 //! iterator into a finite one:
288 //! let numbers = 0..;
289 //! let five_numbers = numbers.take(5);
291 //! for number in five_numbers {
292 //! println!("{}", number);
296 //! This will print the numbers `0` through `4`, each on their own line.
298 //! [`take()`]: trait.Iterator.html#method.take
300 #![stable(feature = "rust1", since = "1.0.0")]
304 use cmp::{Ord, PartialOrd, PartialEq, Ordering};
305 use default::Default;
308 use num::{Zero, One};
309 use ops::{self, Add, Sub, FnMut, Mul, RangeFrom};
310 use option::Option::{self, Some, None};
314 fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
316 /// An interface for dealing with iterators.
318 /// This is the main iterator trait. For more about the concept of iterators
319 /// generally, please see the [module-level documentation]. In particular, you
320 /// may want to know how to [implement `Iterator`][impl].
322 /// [module-level documentation]: index.html
323 /// [impl]: index.html#implementing-iterator
325 #[stable(feature = "rust1", since = "1.0.0")]
326 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
327 `.iter()` or a similar method"]
329 /// The type of the elements being iterated over.
330 #[stable(feature = "rust1", since = "1.0.0")]
333 /// Advances the iterator and returns the next value.
335 /// Returns `None` when iteration is finished. Individual iterator
336 /// implementations may choose to resume iteration, and so calling `next()`
337 /// again may or may not eventually start returning `Some(Item)` again at some
345 /// let a = [1, 2, 3];
347 /// let mut iter = a.iter();
349 /// // A call to next() returns the next value...
350 /// assert_eq!(Some(&1), iter.next());
351 /// assert_eq!(Some(&2), iter.next());
352 /// assert_eq!(Some(&3), iter.next());
354 /// // ... and then None once it's over.
355 /// assert_eq!(None, iter.next());
357 /// // More calls may or may not return None. Here, they always will.
358 /// assert_eq!(None, iter.next());
359 /// assert_eq!(None, iter.next());
361 #[stable(feature = "rust1", since = "1.0.0")]
362 fn next(&mut self) -> Option<Self::Item>;
364 /// Returns the bounds on the remaining length of the iterator.
366 /// Specifically, `size_hint()` returns a tuple where the first element
367 /// is the lower bound, and the second element is the upper bound.
369 /// The second half of the tuple that is returned is an `Option<usize>`. A
370 /// `None` here means that either there is no known upper bound, or the
371 /// upper bound is larger than `usize`.
373 /// # Implementation notes
375 /// It is not enforced that an iterator implementation yields the declared
376 /// number of elements. A buggy iterator may yield less than the lower bound
377 /// or more than the upper bound of elements.
379 /// `size_hint()` is primarily intended to be used for optimizations such as
380 /// reserving space for the elements of the iterator, but must not be
381 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
382 /// implementation of `size_hint()` should not lead to memory safety
385 /// That said, the implementation should provide a correct estimation,
386 /// because otherwise it would be a violation of the trait's protocol.
388 /// The default implementation returns `(0, None)` which is correct for any
396 /// let a = [1, 2, 3];
397 /// let iter = a.iter();
399 /// assert_eq!((3, Some(3)), iter.size_hint());
402 /// A more complex example:
405 /// // The even numbers from zero to ten.
406 /// let iter = (0..10).filter(|x| x % 2 == 0);
408 /// // We might iterate from zero to ten times. Knowing that it's five
409 /// // exactly wouldn't be possible without executing filter().
410 /// assert_eq!((0, Some(10)), iter.size_hint());
412 /// // Let's add one five more numbers with chain()
413 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
415 /// // now both bounds are increased by five
416 /// assert_eq!((5, Some(15)), iter.size_hint());
419 /// Returning `None` for an upper bound:
422 /// // an infinite iterator has no upper bound
425 /// assert_eq!((0, None), iter.size_hint());
428 #[stable(feature = "rust1", since = "1.0.0")]
429 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
431 /// Consumes the iterator, counting the number of iterations and returning it.
433 /// This method will evaluate the iterator until its [`next()`] returns
434 /// `None`. Once `None` is encountered, `count()` returns the number of
435 /// times it called [`next()`].
437 /// [`next()`]: #method.next
439 /// # Overflow Behavior
441 /// The method does no guarding against overflows, so counting elements of
442 /// an iterator with more than `usize::MAX` elements either produces the
443 /// wrong result or panics. If debug assertions are enabled, a panic is
448 /// This function might panic if the iterator has more than `usize::MAX`
456 /// let a = [1, 2, 3];
457 /// assert_eq!(a.iter().count(), 3);
459 /// let a = [1, 2, 3, 4, 5];
460 /// assert_eq!(a.iter().count(), 5);
463 #[stable(feature = "rust1", since = "1.0.0")]
464 fn count(self) -> usize where Self: Sized {
466 self.fold(0, |cnt, _| cnt + 1)
469 /// Consumes the iterator, returning the last element.
471 /// This method will evaluate the iterator until it returns `None`. While
472 /// doing so, it keeps track of the current element. After `None` is
473 /// returned, `last()` will then return the last element it saw.
480 /// let a = [1, 2, 3];
481 /// assert_eq!(a.iter().last(), Some(&3));
483 /// let a = [1, 2, 3, 4, 5];
484 /// assert_eq!(a.iter().last(), Some(&5));
487 #[stable(feature = "rust1", since = "1.0.0")]
488 fn last(self) -> Option<Self::Item> where Self: Sized {
490 for x in self { last = Some(x); }
494 /// Consumes the `n` first elements of the iterator, then returns the
497 /// This method will evaluate the iterator `n` times, discarding those elements.
498 /// After it does so, it will call [`next()`] and return its value.
500 /// [`next()`]: #method.next
502 /// Like most indexing operations, the count starts from zero, so `nth(0)`
503 /// returns the first value, `nth(1)` the second, and so on.
505 /// `nth()` will return `None` if `n` is larger than the length of the
513 /// let a = [1, 2, 3];
514 /// assert_eq!(a.iter().nth(1), Some(&2));
517 /// Calling `nth()` multiple times doesn't rewind the iterator:
520 /// let a = [1, 2, 3];
522 /// let mut iter = a.iter();
524 /// assert_eq!(iter.nth(1), Some(&2));
525 /// assert_eq!(iter.nth(1), None);
528 /// Returning `None` if there are less than `n` elements:
531 /// let a = [1, 2, 3];
532 /// assert_eq!(a.iter().nth(10), None);
535 #[stable(feature = "rust1", since = "1.0.0")]
536 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
538 if n == 0 { return Some(x) }
544 /// Takes two iterators and creates a new iterator over both in sequence.
546 /// `chain()` will return a new iterator which will first iterate over
547 /// values from the first iterator and then over values from the second
550 /// In other words, it links two iterators together, in a chain. 🔗
557 /// let a1 = [1, 2, 3];
558 /// let a2 = [4, 5, 6];
560 /// let mut iter = a1.iter().chain(a2.iter());
562 /// assert_eq!(iter.next(), Some(&1));
563 /// assert_eq!(iter.next(), Some(&2));
564 /// assert_eq!(iter.next(), Some(&3));
565 /// assert_eq!(iter.next(), Some(&4));
566 /// assert_eq!(iter.next(), Some(&5));
567 /// assert_eq!(iter.next(), Some(&6));
568 /// assert_eq!(iter.next(), None);
571 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
572 /// anything that can be converted into an [`Iterator`], not just an
573 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
574 /// [`IntoIterator`], and so can be passed to `chain()` directly:
576 /// [`IntoIterator`]: trait.IntoIterator.html
577 /// [`Iterator`]: trait.Iterator.html
580 /// let s1 = &[1, 2, 3];
581 /// let s2 = &[4, 5, 6];
583 /// let mut iter = s1.iter().chain(s2);
585 /// assert_eq!(iter.next(), Some(&1));
586 /// assert_eq!(iter.next(), Some(&2));
587 /// assert_eq!(iter.next(), Some(&3));
588 /// assert_eq!(iter.next(), Some(&4));
589 /// assert_eq!(iter.next(), Some(&5));
590 /// assert_eq!(iter.next(), Some(&6));
591 /// assert_eq!(iter.next(), None);
594 #[stable(feature = "rust1", since = "1.0.0")]
595 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
596 Self: Sized, U: IntoIterator<Item=Self::Item>,
598 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
601 /// 'Zips up' two iterators into a single iterator of pairs.
603 /// `zip()` returns a new iterator that will iterate over two other
604 /// iterators, returning a tuple where the first element comes from the
605 /// first iterator, and the second element comes from the second iterator.
607 /// In other words, it zips two iterators together, into a single one.
609 /// When either iterator returns `None`, all further calls to `next()`
610 /// will return `None`.
617 /// let a1 = [1, 2, 3];
618 /// let a2 = [4, 5, 6];
620 /// let mut iter = a1.iter().zip(a2.iter());
622 /// assert_eq!(iter.next(), Some((&1, &4)));
623 /// assert_eq!(iter.next(), Some((&2, &5)));
624 /// assert_eq!(iter.next(), Some((&3, &6)));
625 /// assert_eq!(iter.next(), None);
628 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
629 /// anything that can be converted into an [`Iterator`], not just an
630 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
631 /// [`IntoIterator`], and so can be passed to `zip()` directly:
633 /// [`IntoIterator`]: trait.IntoIterator.html
634 /// [`Iterator`]: trait.Iterator.html
637 /// let s1 = &[1, 2, 3];
638 /// let s2 = &[4, 5, 6];
640 /// let mut iter = s1.iter().zip(s2);
642 /// assert_eq!(iter.next(), Some((&1, &4)));
643 /// assert_eq!(iter.next(), Some((&2, &5)));
644 /// assert_eq!(iter.next(), Some((&3, &6)));
645 /// assert_eq!(iter.next(), None);
648 /// `zip()` is often used to zip an infinite iterator to a finite one.
649 /// This works because the finite iterator will eventually return `None`,
650 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
653 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
655 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
657 /// assert_eq!((0, 'f'), enumerate[0]);
658 /// assert_eq!((0, 'f'), zipper[0]);
660 /// assert_eq!((1, 'o'), enumerate[1]);
661 /// assert_eq!((1, 'o'), zipper[1]);
663 /// assert_eq!((2, 'o'), enumerate[2]);
664 /// assert_eq!((2, 'o'), zipper[2]);
667 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
669 #[stable(feature = "rust1", since = "1.0.0")]
670 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
671 Self: Sized, U: IntoIterator
673 Zip{a: self, b: other.into_iter()}
676 /// Takes a closure and creates an iterator which calls that closure on each
679 /// `map()` transforms one iterator into another, by means of its argument:
680 /// something that implements `FnMut`. It produces a new iterator which
681 /// calls this closure on each element of the original iterator.
683 /// If you are good at thinking in types, you can think of `map()` like this:
684 /// If you have an iterator that gives you elements of some type `A`, and
685 /// you want an iterator of some other type `B`, you can use `map()`,
686 /// passing a closure that takes an `A` and returns a `B`.
688 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
689 /// lazy, it is best used when you're already working with other iterators.
690 /// If you're doing some sort of looping for a side effect, it's considered
691 /// more idiomatic to use [`for`] than `map()`.
693 /// [`for`]: ../../book/loops.html#for
700 /// let a = [1, 2, 3];
702 /// let mut iter = a.into_iter().map(|x| 2 * x);
704 /// assert_eq!(iter.next(), Some(2));
705 /// assert_eq!(iter.next(), Some(4));
706 /// assert_eq!(iter.next(), Some(6));
707 /// assert_eq!(iter.next(), None);
710 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
713 /// # #![allow(unused_must_use)]
714 /// // don't do this:
715 /// (0..5).map(|x| println!("{}", x));
717 /// // it won't even execute, as it is lazy. Rust will warn you about this.
719 /// // Instead, use for:
721 /// println!("{}", x);
725 #[stable(feature = "rust1", since = "1.0.0")]
726 fn map<B, F>(self, f: F) -> Map<Self, F> where
727 Self: Sized, F: FnMut(Self::Item) -> B,
729 Map{iter: self, f: f}
732 /// Creates an iterator which uses a closure to determine if an element
733 /// should be yielded.
735 /// The closure must return `true` or `false`. `filter()` creates an
736 /// iterator which calls this closure on each element. If the closure
737 /// returns `true`, then the element is returned. If the closure returns
738 /// `false`, it will try again, and call the closure on the next element,
739 /// seeing if it passes the test.
746 /// let a = [0i32, 1, 2];
748 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
750 /// assert_eq!(iter.next(), Some(&1));
751 /// assert_eq!(iter.next(), Some(&2));
752 /// assert_eq!(iter.next(), None);
755 /// Because the closure passed to `filter()` takes a reference, and many
756 /// iterators iterate over references, this leads to a possibly confusing
757 /// situation, where the type of the closure is a double reference:
760 /// let a = [0, 1, 2];
762 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
764 /// assert_eq!(iter.next(), Some(&2));
765 /// assert_eq!(iter.next(), None);
768 /// It's common to instead use destructuring on the argument to strip away
772 /// let a = [0, 1, 2];
774 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
776 /// assert_eq!(iter.next(), Some(&2));
777 /// assert_eq!(iter.next(), None);
783 /// let a = [0, 1, 2];
785 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
787 /// assert_eq!(iter.next(), Some(&2));
788 /// assert_eq!(iter.next(), None);
793 #[stable(feature = "rust1", since = "1.0.0")]
794 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
795 Self: Sized, P: FnMut(&Self::Item) -> bool,
797 Filter{iter: self, predicate: predicate}
800 /// Creates an iterator that both filters and maps.
802 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
803 /// iterator which calls this closure on each element. If the closure
804 /// returns `Some(element)`, then that element is returned. If the
805 /// closure returns `None`, it will try again, and call the closure on the
806 /// next element, seeing if it will return `Some`.
808 /// [`Option<T>`]: ../option/enum.Option.html
810 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
813 /// [`filter()`]: #method.filter
814 /// [`map()`]: #method.map
816 /// > If the closure returns `Some(element)`, then that element is returned.
818 /// In other words, it removes the [`Option<T>`] layer automatically. If your
819 /// mapping is already returning an [`Option<T>`] and you want to skip over
820 /// `None`s, then `filter_map()` is much, much nicer to use.
827 /// let a = ["1", "2", "lol"];
829 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
831 /// assert_eq!(iter.next(), Some(1));
832 /// assert_eq!(iter.next(), Some(2));
833 /// assert_eq!(iter.next(), None);
836 /// Here's the same example, but with [`filter()`] and [`map()`]:
839 /// let a = ["1", "2", "lol"];
841 /// let mut iter = a.iter()
842 /// .map(|s| s.parse().ok())
843 /// .filter(|s| s.is_some());
845 /// assert_eq!(iter.next(), Some(Some(1)));
846 /// assert_eq!(iter.next(), Some(Some(2)));
847 /// assert_eq!(iter.next(), None);
850 /// There's an extra layer of `Some` in there.
852 #[stable(feature = "rust1", since = "1.0.0")]
853 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
854 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
856 FilterMap { iter: self, f: f }
859 /// Creates an iterator which gives the current iteration count as well as
862 /// The iterator returned yields pairs `(i, val)`, where `i` is the
863 /// current index of iteration and `val` is the value returned by the
866 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
867 /// different sized integer, the [`zip()`] function provides similar
870 /// [`usize`]: ../primitive.usize.html
871 /// [`zip()`]: #method.zip
873 /// # Overflow Behavior
875 /// The method does no guarding against overflows, so enumerating more than
876 /// [`usize::MAX`] elements either produces the wrong result or panics. If
877 /// debug assertions are enabled, a panic is guaranteed.
879 /// [`usize::MAX`]: ../usize/constant.MAX.html
883 /// The returned iterator might panic if the to-be-returned index would
884 /// overflow a `usize`.
889 /// let a = [1, 2, 3];
891 /// let mut iter = a.iter().enumerate();
893 /// assert_eq!(iter.next(), Some((0, &1)));
894 /// assert_eq!(iter.next(), Some((1, &2)));
895 /// assert_eq!(iter.next(), Some((2, &3)));
896 /// assert_eq!(iter.next(), None);
899 #[stable(feature = "rust1", since = "1.0.0")]
900 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
901 Enumerate { iter: self, count: 0 }
904 /// Creates an iterator which can look at the `next()` element without
907 /// Adds a [`peek()`] method to an iterator. See its documentation for
908 /// more information.
910 /// [`peek()`]: struct.Peekable.html#method.peek
917 /// let xs = [1, 2, 3];
919 /// let mut iter = xs.iter().peekable();
921 /// // peek() lets us see into the future
922 /// assert_eq!(iter.peek(), Some(&&1));
923 /// assert_eq!(iter.next(), Some(&1));
925 /// assert_eq!(iter.next(), Some(&2));
927 /// // we can peek() multiple times, the iterator won't advance
928 /// assert_eq!(iter.peek(), Some(&&3));
929 /// assert_eq!(iter.peek(), Some(&&3));
931 /// assert_eq!(iter.next(), Some(&3));
933 /// // after the iterator is finished, so is peek()
934 /// assert_eq!(iter.peek(), None);
935 /// assert_eq!(iter.next(), None);
938 #[stable(feature = "rust1", since = "1.0.0")]
939 fn peekable(self) -> Peekable<Self> where Self: Sized {
940 Peekable{iter: self, peeked: None}
943 /// Creates an iterator that [`skip()`]s elements based on a predicate.
945 /// [`skip()`]: #method.skip
947 /// `skip_while()` takes a closure as an argument. It will call this
948 /// closure on each element of the iterator, and ignore elements
949 /// until it returns `false`.
951 /// After `false` is returned, `skip_while()`'s job is over, and the
952 /// rest of the elements are yielded.
959 /// let a = [-1i32, 0, 1];
961 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
963 /// assert_eq!(iter.next(), Some(&0));
964 /// assert_eq!(iter.next(), Some(&1));
965 /// assert_eq!(iter.next(), None);
968 /// Because the closure passed to `skip_while()` takes a reference, and many
969 /// iterators iterate over references, this leads to a possibly confusing
970 /// situation, where the type of the closure is a double reference:
973 /// let a = [-1, 0, 1];
975 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
977 /// assert_eq!(iter.next(), Some(&0));
978 /// assert_eq!(iter.next(), Some(&1));
979 /// assert_eq!(iter.next(), None);
982 /// Stopping after an initial `false`:
985 /// let a = [-1, 0, 1, -2];
987 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
989 /// assert_eq!(iter.next(), Some(&0));
990 /// assert_eq!(iter.next(), Some(&1));
992 /// // while this would have been false, since we already got a false,
993 /// // skip_while() isn't used any more
994 /// assert_eq!(iter.next(), Some(&-2));
996 /// assert_eq!(iter.next(), None);
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
1001 Self: Sized, P: FnMut(&Self::Item) -> bool,
1003 SkipWhile{iter: self, flag: false, predicate: predicate}
1006 /// Creates an iterator that yields elements based on a predicate.
1008 /// `take_while()` takes a closure as an argument. It will call this
1009 /// closure on each element of the iterator, and yield elements
1010 /// while it returns `true`.
1012 /// After `false` is returned, `take_while()`'s job is over, and the
1013 /// rest of the elements are ignored.
1020 /// let a = [-1i32, 0, 1];
1022 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1024 /// assert_eq!(iter.next(), Some(&-1));
1025 /// assert_eq!(iter.next(), None);
1028 /// Because the closure passed to `take_while()` takes a reference, and many
1029 /// iterators iterate over references, this leads to a possibly confusing
1030 /// situation, where the type of the closure is a double reference:
1033 /// let a = [-1, 0, 1];
1035 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1037 /// assert_eq!(iter.next(), Some(&-1));
1038 /// assert_eq!(iter.next(), None);
1041 /// Stopping after an initial `false`:
1044 /// let a = [-1, 0, 1, -2];
1046 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1048 /// assert_eq!(iter.next(), Some(&-1));
1050 /// // We have more elements that are less than zero, but since we already
1051 /// // got a false, take_while() isn't used any more
1052 /// assert_eq!(iter.next(), None);
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1057 Self: Sized, P: FnMut(&Self::Item) -> bool,
1059 TakeWhile{iter: self, flag: false, predicate: predicate}
1062 /// Creates an iterator that skips the first `n` elements.
1064 /// After they have been consumed, the rest of the elements are yielded.
1071 /// let a = [1, 2, 3];
1073 /// let mut iter = a.iter().skip(2);
1075 /// assert_eq!(iter.next(), Some(&3));
1076 /// assert_eq!(iter.next(), None);
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1081 Skip{iter: self, n: n}
1084 /// Creates an iterator that yields its first `n` elements.
1091 /// let a = [1, 2, 3];
1093 /// let mut iter = a.iter().take(2);
1095 /// assert_eq!(iter.next(), Some(&1));
1096 /// assert_eq!(iter.next(), Some(&2));
1097 /// assert_eq!(iter.next(), None);
1100 /// `take()` is often used with an infinite iterator, to make it finite:
1103 /// let mut iter = (0..).take(3);
1105 /// assert_eq!(iter.next(), Some(0));
1106 /// assert_eq!(iter.next(), Some(1));
1107 /// assert_eq!(iter.next(), Some(2));
1108 /// assert_eq!(iter.next(), None);
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1113 Take{iter: self, n: n}
1116 /// An iterator adaptor similar to [`fold()`] that holds internal state and
1117 /// produces a new iterator.
1119 /// [`fold()`]: #method.fold
1121 /// `scan()` takes two arguments: an initial value which seeds the internal
1122 /// state, and a closure with two arguments, the first being a mutable
1123 /// reference to the internal state and the second an iterator element.
1124 /// The closure can assign to the internal state to share state between
1127 /// On iteration, the closure will be applied to each element of the
1128 /// iterator and the return value from the closure, an [`Option`], is
1129 /// yielded by the iterator.
1131 /// [`Option`]: ../option/enum.Option.html
1138 /// let a = [1, 2, 3];
1140 /// let mut iter = a.iter().scan(1, |state, &x| {
1141 /// // each iteration, we'll multiply the state by the element
1142 /// *state = *state * x;
1144 /// // the value passed on to the next iteration
1148 /// assert_eq!(iter.next(), Some(1));
1149 /// assert_eq!(iter.next(), Some(2));
1150 /// assert_eq!(iter.next(), Some(6));
1151 /// assert_eq!(iter.next(), None);
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1156 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1158 Scan{iter: self, f: f, state: initial_state}
1161 /// Creates an iterator that works like map, but flattens nested structure.
1163 /// The [`map()`] adapter is very useful, but only when the closure
1164 /// argument produces values. If it produces an iterator instead, there's
1165 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1168 /// [`map()`]: #method.map
1170 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1171 /// one item for each element, and `flat_map()`'s closure returns an
1172 /// iterator for each element.
1179 /// let words = ["alpha", "beta", "gamma"];
1181 /// // chars() returns an iterator
1182 /// let merged: String = words.iter()
1183 /// .flat_map(|s| s.chars())
1185 /// assert_eq!(merged, "alphabetagamma");
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1190 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1192 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1195 /// Creates an iterator which ends after the first `None`.
1197 /// After an iterator returns `None`, future calls may or may not yield
1198 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1199 /// `None` is given, it will always return `None` forever.
1206 /// // an iterator which alternates between Some and None
1207 /// struct Alternate {
1211 /// impl Iterator for Alternate {
1212 /// type Item = i32;
1214 /// fn next(&mut self) -> Option<i32> {
1215 /// let val = self.state;
1216 /// self.state = self.state + 1;
1218 /// // if it's even, Some(i32), else None
1219 /// if val % 2 == 0 {
1227 /// let mut iter = Alternate { state: 0 };
1229 /// // we can see our iterator going back and forth
1230 /// assert_eq!(iter.next(), Some(0));
1231 /// assert_eq!(iter.next(), None);
1232 /// assert_eq!(iter.next(), Some(2));
1233 /// assert_eq!(iter.next(), None);
1235 /// // however, once we fuse it...
1236 /// let mut iter = iter.fuse();
1238 /// assert_eq!(iter.next(), Some(4));
1239 /// assert_eq!(iter.next(), None);
1241 /// // it will always return None after the first time.
1242 /// assert_eq!(iter.next(), None);
1243 /// assert_eq!(iter.next(), None);
1244 /// assert_eq!(iter.next(), None);
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 fn fuse(self) -> Fuse<Self> where Self: Sized {
1249 Fuse{iter: self, done: false}
1252 /// Do something with each element of an iterator, passing the value on.
1254 /// When using iterators, you'll often chain several of them together.
1255 /// While working on such code, you might want to check out what's
1256 /// happening at various parts in the pipeline. To do that, insert
1257 /// a call to `inspect()`.
1259 /// It's much more common for `inspect()` to be used as a debugging tool
1260 /// than to exist in your final code, but never say never.
1267 /// let a = [1, 4, 2, 3];
1269 /// // this iterator sequence is complex.
1270 /// let sum = a.iter()
1272 /// .filter(|&x| x % 2 == 0)
1273 /// .fold(0, |sum, i| sum + i);
1275 /// println!("{}", sum);
1277 /// // let's add some inspect() calls to investigate what's happening
1278 /// let sum = a.iter()
1280 /// .inspect(|x| println!("about to filter: {}", x))
1281 /// .filter(|&x| x % 2 == 0)
1282 /// .inspect(|x| println!("made it through filter: {}", x))
1283 /// .fold(0, |sum, i| sum + i);
1285 /// println!("{}", sum);
1288 /// This will print:
1291 /// about to filter: 1
1292 /// about to filter: 4
1293 /// made it through filter: 4
1294 /// about to filter: 2
1295 /// made it through filter: 2
1296 /// about to filter: 3
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1302 Self: Sized, F: FnMut(&Self::Item),
1304 Inspect{iter: self, f: f}
1307 /// Borrows an iterator, rather than consuming it.
1309 /// This is useful to allow applying iterator adaptors while still
1310 /// retaining ownership of the original iterator.
1317 /// let a = [1, 2, 3];
1319 /// let iter = a.into_iter();
1321 /// let sum: i32 = iter.take(5)
1322 /// .fold(0, |acc, &i| acc + i );
1324 /// assert_eq!(sum, 6);
1326 /// // if we try to use iter again, it won't work. The following line
1327 /// // gives "error: use of moved value: `iter`
1328 /// // assert_eq!(iter.next(), None);
1330 /// // let's try that again
1331 /// let a = [1, 2, 3];
1333 /// let mut iter = a.into_iter();
1335 /// // instead, we add in a .by_ref()
1336 /// let sum: i32 = iter.by_ref()
1338 /// .fold(0, |acc, &i| acc + i );
1340 /// assert_eq!(sum, 3);
1342 /// // now this is just fine:
1343 /// assert_eq!(iter.next(), Some(&3));
1344 /// assert_eq!(iter.next(), None);
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1349 /// Transforms an iterator into a collection.
1351 /// `collect()` can take anything iterable, and turn it into a relevant
1352 /// collection. This is one of the more powerful methods in the standard
1353 /// library, used in a variety of contexts.
1355 /// The most basic pattern in which `collect()` is used is to turn one
1356 /// collection into another. You take a collection, call `iter()` on it,
1357 /// do a bunch of transformations, and then `collect()` at the end.
1359 /// One of the keys to `collect()`'s power is that many things you might
1360 /// not think of as 'collections' actually are. For example, a [`String`]
1361 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1362 /// be thought of as single [`Result<Collection<T>, E>`]. See the examples
1365 /// [`String`]: ../string/struct.String.html
1366 /// [`Result<T, E>`]: ../result/enum.Result.html
1367 /// [`char`]: ../primitive.char.html
1369 /// Because `collect()` is so general, it can cause problems with type
1370 /// inference. As such, `collect()` is one of the few times you'll see
1371 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1372 /// helps the inference algorithm understand specifically which collection
1373 /// you're trying to collect into.
1380 /// let a = [1, 2, 3];
1382 /// let doubled: Vec<i32> = a.iter()
1383 /// .map(|&x| x * 2)
1386 /// assert_eq!(vec![2, 4, 6], doubled);
1389 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1390 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1392 /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1395 /// use std::collections::VecDeque;
1397 /// let a = [1, 2, 3];
1399 /// let doubled: VecDeque<i32> = a.iter()
1400 /// .map(|&x| x * 2)
1403 /// assert_eq!(2, doubled[0]);
1404 /// assert_eq!(4, doubled[1]);
1405 /// assert_eq!(6, doubled[2]);
1408 /// Using the 'turbofish' instead of annotationg `doubled`:
1411 /// let a = [1, 2, 3];
1413 /// let doubled = a.iter()
1414 /// .map(|&x| x * 2)
1415 /// .collect::<Vec<i32>>();
1417 /// assert_eq!(vec![2, 4, 6], doubled);
1420 /// Because `collect()` cares about what you're collecting into, you can
1421 /// still use a partial type hint, `_`, with the turbofish:
1424 /// let a = [1, 2, 3];
1426 /// let doubled = a.iter()
1427 /// .map(|&x| x * 2)
1428 /// .collect::<Vec<_>>();
1430 /// assert_eq!(vec![2, 4, 6], doubled);
1433 /// Using `collect()` to make a [`String`]:
1436 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1438 /// let hello: String = chars.iter()
1439 /// .map(|&x| x as u8)
1440 /// .map(|x| (x + 1) as char)
1443 /// assert_eq!("hello", hello);
1446 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1447 /// see if any of them failed:
1450 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1452 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1454 /// // gives us the first error
1455 /// assert_eq!(Err("nope"), result);
1457 /// let results = [Ok(1), Ok(3)];
1459 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1461 /// // gives us the list of answers
1462 /// assert_eq!(Ok(vec![1, 3]), result);
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1467 FromIterator::from_iter(self)
1470 /// Consumes an iterator, creating two collections from it.
1472 /// The predicate passed to `partition()` can return `true`, or `false`.
1473 /// `partition()` returns a pair, all of the elements for which it returned
1474 /// `true`, and all of the elements for which it returned `false`.
1481 /// let a = [1, 2, 3];
1483 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1484 /// .partition(|&n| n % 2 == 0);
1486 /// assert_eq!(even, vec![2]);
1487 /// assert_eq!(odd, vec![1, 3]);
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 fn partition<B, F>(self, mut f: F) -> (B, B) where
1492 B: Default + Extend<Self::Item>,
1493 F: FnMut(&Self::Item) -> bool
1495 let mut left: B = Default::default();
1496 let mut right: B = Default::default();
1500 left.extend(Some(x))
1502 right.extend(Some(x))
1509 /// An iterator adaptor that applies a function, producing a single, final value.
1511 /// `fold()` takes two arguments: an initial value, and a closure with two
1512 /// arguments: an 'accumulator', and an element. It returns the value that
1513 /// the accumulator should have for the next iteration.
1515 /// The initial value is the value the accumulator will have on the first
1518 /// After applying this closure to every element of the iterator, `fold()`
1519 /// returns the accumulator.
1521 /// This operation is sometimes called 'reduce' or 'inject'.
1523 /// Folding is useful whenever you have a collection of something, and want
1524 /// to produce a single value from it.
1531 /// let a = [1, 2, 3];
1533 /// // the sum of all of the elements of a
1534 /// let sum = a.iter()
1535 /// .fold(0, |acc, &x| acc + x);
1537 /// assert_eq!(sum, 6);
1540 /// Let's walk through each step of the iteration here:
1542 /// | element | acc | x | result |
1543 /// |---------|-----|---|--------|
1545 /// | 1 | 0 | 1 | 1 |
1546 /// | 2 | 1 | 2 | 3 |
1547 /// | 3 | 3 | 3 | 6 |
1549 /// And so, our final result, `6`.
1551 /// It's common for people who haven't used iterators a lot to
1552 /// use a `for` loop with a list of things to build up a result. Those
1553 /// can be turned into `fold()`s:
1556 /// let numbers = [1, 2, 3, 4, 5];
1558 /// let mut result = 0;
1561 /// for i in &numbers {
1562 /// result = result + i;
1566 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1568 /// // they're the same
1569 /// assert_eq!(result, result2);
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 fn fold<B, F>(self, init: B, mut f: F) -> B where
1574 Self: Sized, F: FnMut(B, Self::Item) -> B,
1576 let mut accum = init;
1578 accum = f(accum, x);
1583 /// Tests if every element of the iterator matches a predicate.
1585 /// `all()` takes a closure that returns `true` or `false`. It applies
1586 /// this closure to each element of the iterator, and if they all return
1587 /// `true`, then so does `all()`. If any of them return `false`, it
1588 /// returns `false`.
1590 /// `all()` is short-circuting; in other words, it will stop processing
1591 /// as soon as it finds a `false`, given that no matter what else happens,
1592 /// the result will also be `false`.
1594 /// An empty iterator returns `true`.
1601 /// let a = [1, 2, 3];
1603 /// assert!(a.iter().all(|&x| x > 0));
1605 /// assert!(!a.iter().all(|&x| x > 2));
1608 /// Stopping at the first `false`:
1611 /// let a = [1, 2, 3];
1613 /// let mut iter = a.iter();
1615 /// assert!(!iter.all(|&x| x != 2));
1617 /// // we can still use `iter`, as there are more elements.
1618 /// assert_eq!(iter.next(), Some(&3));
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 fn all<F>(&mut self, mut f: F) -> bool where
1623 Self: Sized, F: FnMut(Self::Item) -> bool
1633 /// Tests if any element of the iterator matches a predicate.
1635 /// `any()` takes a closure that returns `true` or `false`. It applies
1636 /// this closure to each element of the iterator, and if any of them return
1637 /// `true`, then so does `any()`. If they all return `false`, it
1638 /// returns `false`.
1640 /// `any()` is short-circuting; in other words, it will stop processing
1641 /// as soon as it finds a `true`, given that no matter what else happens,
1642 /// the result will also be `true`.
1644 /// An empty iterator returns `false`.
1651 /// let a = [1, 2, 3];
1653 /// assert!(a.iter().any(|&x| x > 0));
1655 /// assert!(!a.iter().any(|&x| x > 5));
1658 /// Stopping at the first `true`:
1661 /// let a = [1, 2, 3];
1663 /// let mut iter = a.iter();
1665 /// assert!(iter.any(|&x| x != 2));
1667 /// // we can still use `iter`, as there are more elements.
1668 /// assert_eq!(iter.next(), Some(&2));
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 fn any<F>(&mut self, mut f: F) -> bool where
1674 F: FnMut(Self::Item) -> bool
1684 /// Searches for an element of an iterator that satisfies a predicate.
1686 /// `find()` takes a closure that returns `true` or `false`. It applies
1687 /// this closure to each element of the iterator, and if any of them return
1688 /// `true`, then `find()` returns `Some(element)`. If they all return
1689 /// `false`, it returns `None`.
1691 /// `find()` is short-circuting; in other words, it will stop processing
1692 /// as soon as the closure returns `true`.
1694 /// Because `find()` takes a reference, and many iterators iterate over
1695 /// references, this leads to a possibly confusing situation where the
1696 /// argument is a double reference. You can see this effect in the
1697 /// examples below, with `&&x`.
1704 /// let a = [1, 2, 3];
1706 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1708 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1711 /// Stopping at the first `true`:
1714 /// let a = [1, 2, 3];
1716 /// let mut iter = a.iter();
1718 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1720 /// // we can still use `iter`, as there are more elements.
1721 /// assert_eq!(iter.next(), Some(&3));
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1727 P: FnMut(&Self::Item) -> bool,
1730 if predicate(&x) { return Some(x) }
1735 /// Searches for an element in an iterator, returning its index.
1737 /// `position()` takes a closure that returns `true` or `false`. It applies
1738 /// this closure to each element of the iterator, and if one of them
1739 /// returns `true`, then `position()` returns `Some(index)`. If all of
1740 /// them return `false`, it returns `None`.
1742 /// `position()` is short-circuting; in other words, it will stop
1743 /// processing as soon as it finds a `true`.
1745 /// # Overflow Behavior
1747 /// The method does no guarding against overflows, so if there are more
1748 /// than `usize::MAX` non-matching elements, it either produces the wrong
1749 /// result or panics. If debug assertions are enabled, a panic is
1754 /// This function might panic if the iterator has more than `usize::MAX`
1755 /// non-matching elements.
1762 /// let a = [1, 2, 3];
1764 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1766 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1769 /// Stopping at the first `true`:
1772 /// let a = [1, 2, 3];
1774 /// let mut iter = a.iter();
1776 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1778 /// // we can still use `iter`, as there are more elements.
1779 /// assert_eq!(iter.next(), Some(&3));
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1785 P: FnMut(Self::Item) -> bool,
1787 // `enumerate` might overflow.
1788 for (i, x) in self.enumerate() {
1796 /// Searches for an element in an iterator from the right, returning its
1799 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1800 /// this closure to each element of the iterator, starting from the end,
1801 /// and if one of them returns `true`, then `rposition()` returns
1802 /// `Some(index)`. If all of them return `false`, it returns `None`.
1804 /// `rposition()` is short-circuting; in other words, it will stop
1805 /// processing as soon as it finds a `true`.
1812 /// let a = [1, 2, 3];
1814 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1816 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1819 /// Stopping at the first `true`:
1822 /// let a = [1, 2, 3];
1824 /// let mut iter = a.iter();
1826 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1828 /// // we can still use `iter`, as there are more elements.
1829 /// assert_eq!(iter.next(), Some(&1));
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1834 P: FnMut(Self::Item) -> bool,
1835 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1837 let mut i = self.len();
1839 while let Some(v) = self.next_back() {
1843 // No need for an overflow check here, because `ExactSizeIterator`
1844 // implies that the number of elements fits into a `usize`.
1850 /// Returns the maximum element of an iterator.
1852 /// If the two elements are equally maximum, the latest element is
1860 /// let a = [1, 2, 3];
1862 /// assert_eq!(a.iter().max(), Some(&3));
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1870 // switch to y even if it is only equal, to preserve
1872 |_, x, _, y| *x <= *y)
1876 /// Returns the minimum element of an iterator.
1878 /// If the two elements are equally minimum, the first element is
1886 /// let a = [1, 2, 3];
1888 /// assert_eq!(a.iter().min(), Some(&1));
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1896 // only switch to y if it is strictly smaller, to
1897 // preserve stability.
1898 |_, x, _, y| *x > *y)
1902 #[allow(missing_docs)]
1904 #[unstable(feature = "iter_cmp",
1905 reason = "may want to produce an Ordering directly; see #15311",
1907 #[rustc_deprecated(reason = "renamed to max_by_key", since = "1.6.0")]
1908 fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1910 F: FnMut(&Self::Item) -> B,
1915 /// Returns the element that gives the maximum value from the
1916 /// specified function.
1918 /// Returns the rightmost element if the comparison determines two elements
1919 /// to be equally maximum.
1924 /// let a = [-3_i32, 0, 1, 5, -10];
1925 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1928 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1929 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1930 where Self: Sized, F: FnMut(&Self::Item) -> B,
1934 // switch to y even if it is only equal, to preserve
1936 |x_p, _, y_p, _| x_p <= y_p)
1941 #[allow(missing_docs)]
1942 #[unstable(feature = "iter_cmp",
1943 reason = "may want to produce an Ordering directly; see #15311",
1945 #[rustc_deprecated(reason = "renamed to min_by_key", since = "1.6.0")]
1946 fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1948 F: FnMut(&Self::Item) -> B,
1953 /// Returns the element that gives the minimum value from the
1954 /// specified function.
1956 /// Returns the latest element if the comparison determines two elements
1957 /// to be equally minimum.
1962 /// let a = [-3_i32, 0, 1, 5, -10];
1963 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1965 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1966 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1967 where Self: Sized, F: FnMut(&Self::Item) -> B,
1971 // only switch to y if it is strictly smaller, to
1972 // preserve stability.
1973 |x_p, _, y_p, _| x_p > y_p)
1977 /// Reverses an iterator's direction.
1979 /// Usually, iterators iterate from left to right. After using `rev()`,
1980 /// an iterator will instead iterate from right to left.
1982 /// This is only possible if the iterator has an end, so `rev()` only
1983 /// works on [`DoubleEndedIterator`]s.
1985 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1990 /// let a = [1, 2, 3];
1992 /// let mut iter = a.iter().rev();
1994 /// assert_eq!(iter.next(), Some(&3));
1995 /// assert_eq!(iter.next(), Some(&2));
1996 /// assert_eq!(iter.next(), Some(&1));
1998 /// assert_eq!(iter.next(), None);
2001 #[stable(feature = "rust1", since = "1.0.0")]
2002 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2006 /// Converts an iterator of pairs into a pair of containers.
2008 /// `unzip()` consumes an entire iterator of pairs, producing two
2009 /// collections: one from the left elements of the pairs, and one
2010 /// from the right elements.
2012 /// This function is, in some sense, the opposite of [`zip()`].
2014 /// [`zip()`]: #method.zip
2021 /// let a = [(1, 2), (3, 4)];
2023 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2025 /// assert_eq!(left, [1, 3]);
2026 /// assert_eq!(right, [2, 4]);
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2030 FromA: Default + Extend<A>,
2031 FromB: Default + Extend<B>,
2032 Self: Sized + Iterator<Item=(A, B)>,
2034 struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
2035 impl<A> Iterator for SizeHint<A> {
2038 fn next(&mut self) -> Option<A> { None }
2039 fn size_hint(&self) -> (usize, Option<usize>) {
2044 let (lo, hi) = self.size_hint();
2045 let mut ts: FromA = Default::default();
2046 let mut us: FromB = Default::default();
2048 ts.extend(SizeHint(lo, hi, marker::PhantomData));
2049 us.extend(SizeHint(lo, hi, marker::PhantomData));
2051 for (t, u) in self {
2059 /// Creates an iterator which clone()s all of its elements.
2061 /// This is useful when you have an iterator over `&T`, but you need an
2062 /// iterator over `T`.
2069 /// let a = [1, 2, 3];
2071 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2073 /// // cloned is the same as .map(|&x| x), for integers
2074 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2076 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2077 /// assert_eq!(v_map, vec![1, 2, 3]);
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2081 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2086 /// Repeats an iterator endlessly.
2088 /// Instead of stopping at `None`, the iterator will instead start again,
2089 /// from the beginning. After iterating again, it will start at the
2090 /// beginning again. And again. And again. Forever.
2097 /// let a = [1, 2, 3];
2099 /// let mut it = a.iter().cycle();
2101 /// assert_eq!(it.next(), Some(&1));
2102 /// assert_eq!(it.next(), Some(&2));
2103 /// assert_eq!(it.next(), Some(&3));
2104 /// assert_eq!(it.next(), Some(&1));
2105 /// assert_eq!(it.next(), Some(&2));
2106 /// assert_eq!(it.next(), Some(&3));
2107 /// assert_eq!(it.next(), Some(&1));
2109 #[stable(feature = "rust1", since = "1.0.0")]
2111 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2112 Cycle{orig: self.clone(), iter: self}
2115 /// Sums the elements of an iterator.
2117 /// Takes each element, adds them together, and returns the result.
2119 /// An empty iterator returns the zero value of the type.
2126 /// #![feature(iter_arith)]
2128 /// let a = [1, 2, 3];
2129 /// let sum: i32 = a.iter().sum();
2131 /// assert_eq!(sum, 6);
2133 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2135 fn sum<S=<Self as Iterator>::Item>(self) -> S where
2136 S: Add<Self::Item, Output=S> + Zero,
2139 self.fold(Zero::zero(), |s, e| s + e)
2142 /// Iterates over the entire iterator, multiplying all the elements
2144 /// An empty iterator returns the one value of the type.
2149 /// #![feature(iter_arith)]
2151 /// fn factorial(n: u32) -> u32 {
2152 /// (1..).take_while(|&i| i <= n).product()
2154 /// assert_eq!(factorial(0), 1);
2155 /// assert_eq!(factorial(1), 1);
2156 /// assert_eq!(factorial(5), 120);
2158 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2160 fn product<P=<Self as Iterator>::Item>(self) -> P where
2161 P: Mul<Self::Item, Output=P> + One,
2164 self.fold(One::one(), |p, e| p * e)
2167 /// Lexicographically compares the elements of this `Iterator` with those
2169 #[stable(feature = "iter_order", since = "1.5.0")]
2170 fn cmp<I>(mut self, other: I) -> Ordering where
2171 I: IntoIterator<Item = Self::Item>,
2175 let mut other = other.into_iter();
2178 match (self.next(), other.next()) {
2179 (None, None) => return Ordering::Equal,
2180 (None, _ ) => return Ordering::Less,
2181 (_ , None) => return Ordering::Greater,
2182 (Some(x), Some(y)) => match x.cmp(&y) {
2183 Ordering::Equal => (),
2184 non_eq => return non_eq,
2190 /// Lexicographically compares the elements of this `Iterator` with those
2192 #[stable(feature = "iter_order", since = "1.5.0")]
2193 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2195 Self::Item: PartialOrd<I::Item>,
2198 let mut other = other.into_iter();
2201 match (self.next(), other.next()) {
2202 (None, None) => return Some(Ordering::Equal),
2203 (None, _ ) => return Some(Ordering::Less),
2204 (_ , None) => return Some(Ordering::Greater),
2205 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2206 Some(Ordering::Equal) => (),
2207 non_eq => return non_eq,
2213 /// Determines if the elements of this `Iterator` are equal to those of
2215 #[stable(feature = "iter_order", since = "1.5.0")]
2216 fn eq<I>(mut self, other: I) -> bool where
2218 Self::Item: PartialEq<I::Item>,
2221 let mut other = other.into_iter();
2224 match (self.next(), other.next()) {
2225 (None, None) => return true,
2226 (None, _) | (_, None) => return false,
2227 (Some(x), Some(y)) => if x != y { return false },
2232 /// Determines if the elements of this `Iterator` are unequal to those of
2234 #[stable(feature = "iter_order", since = "1.5.0")]
2235 fn ne<I>(mut self, other: I) -> bool where
2237 Self::Item: PartialEq<I::Item>,
2240 let mut other = other.into_iter();
2243 match (self.next(), other.next()) {
2244 (None, None) => return false,
2245 (None, _) | (_, None) => return true,
2246 (Some(x), Some(y)) => if x.ne(&y) { return true },
2251 /// Determines if the elements of this `Iterator` are lexicographically
2252 /// less than those of another.
2253 #[stable(feature = "iter_order", since = "1.5.0")]
2254 fn lt<I>(mut self, other: I) -> bool where
2256 Self::Item: PartialOrd<I::Item>,
2259 let mut other = other.into_iter();
2262 match (self.next(), other.next()) {
2263 (None, None) => return false,
2264 (None, _ ) => return true,
2265 (_ , None) => return false,
2266 (Some(x), Some(y)) => {
2267 match x.partial_cmp(&y) {
2268 Some(Ordering::Less) => return true,
2269 Some(Ordering::Equal) => {}
2270 Some(Ordering::Greater) => return false,
2271 None => return false,
2278 /// Determines if the elements of this `Iterator` are lexicographically
2279 /// less or equal to those of another.
2280 #[stable(feature = "iter_order", since = "1.5.0")]
2281 fn le<I>(mut self, other: I) -> bool where
2283 Self::Item: PartialOrd<I::Item>,
2286 let mut other = other.into_iter();
2289 match (self.next(), other.next()) {
2290 (None, None) => return true,
2291 (None, _ ) => return true,
2292 (_ , None) => return false,
2293 (Some(x), Some(y)) => {
2294 match x.partial_cmp(&y) {
2295 Some(Ordering::Less) => return true,
2296 Some(Ordering::Equal) => {}
2297 Some(Ordering::Greater) => return false,
2298 None => return false,
2305 /// Determines if the elements of this `Iterator` are lexicographically
2306 /// greater than those of another.
2307 #[stable(feature = "iter_order", since = "1.5.0")]
2308 fn gt<I>(mut self, other: I) -> bool where
2310 Self::Item: PartialOrd<I::Item>,
2313 let mut other = other.into_iter();
2316 match (self.next(), other.next()) {
2317 (None, None) => return false,
2318 (None, _ ) => return false,
2319 (_ , None) => return true,
2320 (Some(x), Some(y)) => {
2321 match x.partial_cmp(&y) {
2322 Some(Ordering::Less) => return false,
2323 Some(Ordering::Equal) => {}
2324 Some(Ordering::Greater) => return true,
2325 None => return false,
2332 /// Determines if the elements of this `Iterator` are lexicographically
2333 /// greater than or equal to those of another.
2334 #[stable(feature = "iter_order", since = "1.5.0")]
2335 fn ge<I>(mut self, other: I) -> bool where
2337 Self::Item: PartialOrd<I::Item>,
2340 let mut other = other.into_iter();
2343 match (self.next(), other.next()) {
2344 (None, None) => return true,
2345 (None, _ ) => return false,
2346 (_ , None) => return true,
2347 (Some(x), Some(y)) => {
2348 match x.partial_cmp(&y) {
2349 Some(Ordering::Less) => return false,
2350 Some(Ordering::Equal) => {}
2351 Some(Ordering::Greater) => return true,
2352 None => return false,
2360 /// Select an element from an iterator based on the given projection
2361 /// and "comparison" function.
2363 /// This is an idiosyncratic helper to try to factor out the
2364 /// commonalities of {max,min}{,_by}. In particular, this avoids
2365 /// having to implement optimizations several times.
2367 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2369 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2371 FProj: FnMut(&I::Item) -> B,
2372 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2374 // start with the first element as our selection. This avoids
2375 // having to use `Option`s inside the loop, translating to a
2376 // sizeable performance gain (6x in one case).
2377 it.next().map(|mut sel| {
2378 let mut sel_p = f_proj(&sel);
2381 let x_p = f_proj(&x);
2382 if f_cmp(&sel_p, &sel, &x_p, &x) {
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2393 type Item = I::Item;
2394 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2395 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2398 /// Conversion from an `Iterator`.
2400 /// By implementing `FromIterator` for a type, you define how it will be
2401 /// created from an iterator. This is common for types which describe a
2402 /// collection of some kind.
2404 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
2405 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
2406 /// documentation for more examples.
2408 /// [`from_iter()`]: #tymethod.from_iter
2409 /// [`Iterator`]: trait.Iterator.html
2410 /// [`collect()`]: trait.Iterator.html#method.collect
2412 /// See also: [`IntoIterator`].
2414 /// [`IntoIterator`]: trait.IntoIterator.html
2421 /// use std::iter::FromIterator;
2423 /// let five_fives = std::iter::repeat(5).take(5);
2425 /// let v = Vec::from_iter(five_fives);
2427 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2430 /// Using [`collect()`] to implicitly use `FromIterator`:
2433 /// let five_fives = std::iter::repeat(5).take(5);
2435 /// let v: Vec<i32> = five_fives.collect();
2437 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2440 /// Implementing `FromIterator` for your type:
2443 /// use std::iter::FromIterator;
2445 /// // A sample collection, that's just a wrapper over Vec<T>
2446 /// #[derive(Debug)]
2447 /// struct MyCollection(Vec<i32>);
2449 /// // Let's give it some methods so we can create one and add things
2451 /// impl MyCollection {
2452 /// fn new() -> MyCollection {
2453 /// MyCollection(Vec::new())
2456 /// fn add(&mut self, elem: i32) {
2457 /// self.0.push(elem);
2461 /// // and we'll implement FromIterator
2462 /// impl FromIterator<i32> for MyCollection {
2463 /// fn from_iter<I: IntoIterator<Item=i32>>(iterator: I) -> Self {
2464 /// let mut c = MyCollection::new();
2466 /// for i in iterator {
2474 /// // Now we can make a new iterator...
2475 /// let iter = (0..5).into_iter();
2477 /// // ... and make a MyCollection out of it
2478 /// let c = MyCollection::from_iter(iter);
2480 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2482 /// // collect works too!
2484 /// let iter = (0..5).into_iter();
2485 /// let c: MyCollection = iter.collect();
2487 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2491 built from an iterator over elements of type `{A}`"]
2492 pub trait FromIterator<A>: Sized {
2493 /// Creates a value from an iterator.
2495 /// See the [module-level documentation] for more.
2497 /// [module-level documentation]: trait.FromIterator.html
2504 /// use std::iter::FromIterator;
2506 /// let five_fives = std::iter::repeat(5).take(5);
2508 /// let v = Vec::from_iter(five_fives);
2510 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
2516 /// Conversion into an `Iterator`.
2518 /// By implementing `IntoIterator` for a type, you define how it will be
2519 /// converted to an iterator. This is common for types which describe a
2520 /// collection of some kind.
2522 /// One benefit of implementing `IntoIterator` is that your type will [work
2523 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2525 /// See also: [`FromIterator`].
2527 /// [`FromIterator`]: trait.FromIterator.html
2534 /// let v = vec![1, 2, 3];
2536 /// let mut iter = v.into_iter();
2538 /// let n = iter.next();
2539 /// assert_eq!(Some(1), n);
2541 /// let n = iter.next();
2542 /// assert_eq!(Some(2), n);
2544 /// let n = iter.next();
2545 /// assert_eq!(Some(3), n);
2547 /// let n = iter.next();
2548 /// assert_eq!(None, n);
2551 /// Implementing `IntoIterator` for your type:
2554 /// // A sample collection, that's just a wrapper over Vec<T>
2555 /// #[derive(Debug)]
2556 /// struct MyCollection(Vec<i32>);
2558 /// // Let's give it some methods so we can create one and add things
2560 /// impl MyCollection {
2561 /// fn new() -> MyCollection {
2562 /// MyCollection(Vec::new())
2565 /// fn add(&mut self, elem: i32) {
2566 /// self.0.push(elem);
2570 /// // and we'll implement IntoIterator
2571 /// impl IntoIterator for MyCollection {
2572 /// type Item = i32;
2573 /// type IntoIter = ::std::vec::IntoIter<i32>;
2575 /// fn into_iter(self) -> Self::IntoIter {
2576 /// self.0.into_iter()
2580 /// // Now we can make a new collection...
2581 /// let mut c = MyCollection::new();
2583 /// // ... add some stuff to it ...
2588 /// // ... and then turn it into an Iterator:
2589 /// for (i, n) in c.into_iter().enumerate() {
2590 /// assert_eq!(i as i32, n);
2593 #[stable(feature = "rust1", since = "1.0.0")]
2594 pub trait IntoIterator {
2595 /// The type of the elements being iterated over.
2596 #[stable(feature = "rust1", since = "1.0.0")]
2599 /// Which kind of iterator are we turning this into?
2600 #[stable(feature = "rust1", since = "1.0.0")]
2601 type IntoIter: Iterator<Item=Self::Item>;
2603 /// Creates an iterator from a value.
2605 /// See the [module-level documentation] for more.
2607 /// [module-level documentation]: trait.IntoIterator.html
2614 /// let v = vec![1, 2, 3];
2616 /// let mut iter = v.into_iter();
2618 /// let n = iter.next();
2619 /// assert_eq!(Some(1), n);
2621 /// let n = iter.next();
2622 /// assert_eq!(Some(2), n);
2624 /// let n = iter.next();
2625 /// assert_eq!(Some(3), n);
2627 /// let n = iter.next();
2628 /// assert_eq!(None, n);
2630 #[stable(feature = "rust1", since = "1.0.0")]
2631 fn into_iter(self) -> Self::IntoIter;
2634 #[stable(feature = "rust1", since = "1.0.0")]
2635 impl<I: Iterator> IntoIterator for I {
2636 type Item = I::Item;
2639 fn into_iter(self) -> I {
2644 /// Extend a collection with the contents of an iterator.
2646 /// Iterators produce a series of values, and collections can also be thought
2647 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2648 /// to extend a collection by including the contents of that iterator.
2655 /// // You can extend a String with some chars:
2656 /// let mut message = String::from("The first three letters are: ");
2658 /// message.extend(&['a', 'b', 'c']);
2660 /// assert_eq!("abc", &message[29..32]);
2663 /// Implementing `Extend`:
2666 /// // A sample collection, that's just a wrapper over Vec<T>
2667 /// #[derive(Debug)]
2668 /// struct MyCollection(Vec<i32>);
2670 /// // Let's give it some methods so we can create one and add things
2672 /// impl MyCollection {
2673 /// fn new() -> MyCollection {
2674 /// MyCollection(Vec::new())
2677 /// fn add(&mut self, elem: i32) {
2678 /// self.0.push(elem);
2682 /// // since MyCollection has a list of i32s, we implement Extend for i32
2683 /// impl Extend<i32> for MyCollection {
2685 /// // This is a bit simpler with the concrete type signature: we can call
2686 /// // extend on anything which can be turned into an Iterator which gives
2687 /// // us i32s. Because we need i32s to put into MyCollection.
2688 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2690 /// // The implementation is very straightforward: loop through the
2691 /// // iterator, and add() each element to ourselves.
2692 /// for elem in iterable {
2698 /// let mut c = MyCollection::new();
2704 /// // let's extend our collection with three more numbers
2705 /// c.extend(vec![1, 2, 3]);
2707 /// // we've added these elements onto the end
2708 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2710 #[stable(feature = "rust1", since = "1.0.0")]
2711 pub trait Extend<A> {
2712 /// Extends a collection with the contents of an iterator.
2714 /// As this is the only method for this trait, the [trait-level] docs
2715 /// contain more details.
2717 /// [trait-level]: trait.Extend.html
2724 /// // You can extend a String with some chars:
2725 /// let mut message = String::from("abc");
2727 /// message.extend(['d', 'e', 'f'].iter());
2729 /// assert_eq!("abcdef", &message);
2731 #[stable(feature = "rust1", since = "1.0.0")]
2732 fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
2735 /// An iterator able to yield elements from both ends.
2737 /// Something that implements `DoubleEndedIterator` has one extra capability
2738 /// over something that implements [`Iterator`]: the ability to also take
2739 /// `Item`s from the back, as well as the front.
2741 /// It is important to note that both back and forth work on the same range,
2742 /// and do not cross: iteration is over when they meet in the middle.
2744 /// [`Iterator`]: trait.Iterator.html
2750 /// let numbers = vec![1, 2, 3];
2752 /// let mut iter = numbers.iter();
2754 /// let n = iter.next();
2755 /// assert_eq!(Some(&1), n);
2757 /// let n = iter.next_back();
2758 /// assert_eq!(Some(&3), n);
2760 /// let n = iter.next_back();
2761 /// assert_eq!(Some(&2), n);
2763 /// let n = iter.next();
2764 /// assert_eq!(None, n);
2766 /// let n = iter.next_back();
2767 /// assert_eq!(None, n);
2769 #[stable(feature = "rust1", since = "1.0.0")]
2770 pub trait DoubleEndedIterator: Iterator {
2771 /// An iterator able to yield elements from both ends.
2773 /// As this is the only method for this trait, the [trait-level] docs
2774 /// contain more details.
2776 /// [trait-level]: trait.DoubleEndedIterator.html
2783 /// let numbers = vec![1, 2, 3];
2785 /// let mut iter = numbers.iter();
2787 /// let n = iter.next();
2788 /// assert_eq!(Some(&1), n);
2790 /// let n = iter.next_back();
2791 /// assert_eq!(Some(&3), n);
2793 /// let n = iter.next_back();
2794 /// assert_eq!(Some(&2), n);
2796 /// let n = iter.next();
2797 /// assert_eq!(None, n);
2799 /// let n = iter.next_back();
2800 /// assert_eq!(None, n);
2802 #[stable(feature = "rust1", since = "1.0.0")]
2803 fn next_back(&mut self) -> Option<Self::Item>;
2806 #[stable(feature = "rust1", since = "1.0.0")]
2807 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2808 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2811 /// An iterator that knows its exact length.
2813 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2814 /// If an iterator knows how many times it can iterate, providing access to
2815 /// that information can be useful. For example, if you want to iterate
2816 /// backwards, a good start is to know where the end is.
2818 /// When implementing an `ExactSizeIterator`, You must also implement
2819 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2820 /// return the exact size of the iterator.
2822 /// [`Iterator`]: trait.Iterator.html
2823 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2825 /// The [`len()`] method has a default implementation, so you usually shouldn't
2826 /// implement it. However, you may be able to provide a more performant
2827 /// implementation than the default, so overriding it in this case makes sense.
2829 /// [`len()`]: #method.len
2836 /// // a finite range knows exactly how many times it will iterate
2837 /// let five = 0..5;
2839 /// assert_eq!(5, five.len());
2842 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2843 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2845 /// [moddocs]: index.html
2848 /// # struct Counter {
2851 /// # impl Counter {
2852 /// # fn new() -> Counter {
2853 /// # Counter { count: 0 }
2856 /// # impl Iterator for Counter {
2857 /// # type Item = usize;
2858 /// # fn next(&mut self) -> Option<usize> {
2859 /// # self.count += 1;
2860 /// # if self.count < 6 {
2861 /// # Some(self.count)
2867 /// impl ExactSizeIterator for Counter {
2868 /// // We already have the number of iterations, so we can use it directly.
2869 /// fn len(&self) -> usize {
2874 /// // And now we can use it!
2876 /// let counter = Counter::new();
2878 /// assert_eq!(0, counter.len());
2880 #[stable(feature = "rust1", since = "1.0.0")]
2881 pub trait ExactSizeIterator: Iterator {
2883 #[stable(feature = "rust1", since = "1.0.0")]
2884 /// Returns the exact number of times the iterator will iterate.
2886 /// This method has a default implementation, so you usually should not
2887 /// implement it directly. However, if you can provide a more efficient
2888 /// implementation, you can do so. See the [trait-level] docs for an
2891 /// This function has the same safety guarantees as the [`size_hint()`]
2894 /// [trait-level]: trait.ExactSizeIterator.html
2895 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2902 /// // a finite range knows exactly how many times it will iterate
2903 /// let five = 0..5;
2905 /// assert_eq!(5, five.len());
2907 fn len(&self) -> usize {
2908 let (lower, upper) = self.size_hint();
2909 // Note: This assertion is overly defensive, but it checks the invariant
2910 // guaranteed by the trait. If this trait were rust-internal,
2911 // we could use debug_assert!; assert_eq! will check all Rust user
2912 // implementations too.
2913 assert_eq!(upper, Some(lower));
2918 #[stable(feature = "rust1", since = "1.0.0")]
2919 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2921 // All adaptors that preserve the size of the wrapped iterator are fine
2922 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2923 #[stable(feature = "rust1", since = "1.0.0")]
2924 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2925 #[stable(feature = "rust1", since = "1.0.0")]
2926 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2929 #[stable(feature = "rust1", since = "1.0.0")]
2930 impl<I> ExactSizeIterator for Rev<I>
2931 where I: ExactSizeIterator + DoubleEndedIterator {}
2932 #[stable(feature = "rust1", since = "1.0.0")]
2933 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2934 F: FnMut(I::Item) -> B,
2936 #[stable(feature = "rust1", since = "1.0.0")]
2937 impl<A, B> ExactSizeIterator for Zip<A, B>
2938 where A: ExactSizeIterator, B: ExactSizeIterator {}
2940 /// An double-ended iterator with the direction inverted.
2942 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2943 /// documentation for more.
2945 /// [`rev()`]: trait.Iterator.html#method.rev
2946 /// [`Iterator`]: trait.Iterator.html
2948 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2949 #[stable(feature = "rust1", since = "1.0.0")]
2954 #[stable(feature = "rust1", since = "1.0.0")]
2955 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2956 type Item = <I as Iterator>::Item;
2959 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2961 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2964 #[stable(feature = "rust1", since = "1.0.0")]
2965 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2967 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2970 /// An iterator that clones the elements of an underlying iterator.
2972 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2973 /// documentation for more.
2975 /// [`cloned()`]: trait.Iterator.html#method.cloned
2976 /// [`Iterator`]: trait.Iterator.html
2977 #[stable(feature = "iter_cloned", since = "1.1.0")]
2978 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2980 pub struct Cloned<I> {
2984 #[stable(feature = "rust1", since = "1.0.0")]
2985 impl<'a, I, T: 'a> Iterator for Cloned<I>
2986 where I: Iterator<Item=&'a T>, T: Clone
2990 fn next(&mut self) -> Option<T> {
2991 self.it.next().cloned()
2994 fn size_hint(&self) -> (usize, Option<usize>) {
2999 #[stable(feature = "rust1", since = "1.0.0")]
3000 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
3001 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
3003 fn next_back(&mut self) -> Option<T> {
3004 self.it.next_back().cloned()
3008 #[stable(feature = "rust1", since = "1.0.0")]
3009 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
3010 where I: ExactSizeIterator<Item=&'a T>, T: Clone
3013 /// An iterator that repeats endlessly.
3015 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
3016 /// documentation for more.
3018 /// [`cycle()`]: trait.Iterator.html#method.cycle
3019 /// [`Iterator`]: trait.Iterator.html
3021 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3022 #[stable(feature = "rust1", since = "1.0.0")]
3023 pub struct Cycle<I> {
3028 #[stable(feature = "rust1", since = "1.0.0")]
3029 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
3030 type Item = <I as Iterator>::Item;
3033 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3034 match self.iter.next() {
3035 None => { self.iter = self.orig.clone(); self.iter.next() }
3041 fn size_hint(&self) -> (usize, Option<usize>) {
3042 // the cycle iterator is either empty or infinite
3043 match self.orig.size_hint() {
3044 sz @ (0, Some(0)) => sz,
3045 (0, _) => (0, None),
3046 _ => (usize::MAX, None)
3051 /// An iterator that strings two iterators together.
3053 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
3054 /// documentation for more.
3056 /// [`chain()`]: trait.Iterator.html#method.chain
3057 /// [`Iterator`]: trait.Iterator.html
3059 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3060 #[stable(feature = "rust1", since = "1.0.0")]
3061 pub struct Chain<A, B> {
3067 // The iterator protocol specifies that iteration ends with the return value
3068 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
3069 // further calls return. The chain adaptor must account for this since it uses
3070 // two subiterators.
3072 // It uses three states:
3074 // - Both: `a` and `b` are remaining
3075 // - Front: `a` remaining
3076 // - Back: `b` remaining
3078 // The fourth state (neither iterator is remaining) only occurs after Chain has
3079 // returned None once, so we don't need to store this state.
3082 // both front and back iterator are remaining
3084 // only front is remaining
3086 // only back is remaining
3090 #[stable(feature = "rust1", since = "1.0.0")]
3091 impl<A, B> Iterator for Chain<A, B> where
3093 B: Iterator<Item = A::Item>
3095 type Item = A::Item;
3098 fn next(&mut self) -> Option<A::Item> {
3100 ChainState::Both => match self.a.next() {
3101 elt @ Some(..) => elt,
3103 self.state = ChainState::Back;
3107 ChainState::Front => self.a.next(),
3108 ChainState::Back => self.b.next(),
3113 fn count(self) -> usize {
3115 ChainState::Both => self.a.count() + self.b.count(),
3116 ChainState::Front => self.a.count(),
3117 ChainState::Back => self.b.count(),
3122 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
3124 ChainState::Both | ChainState::Front => {
3125 for x in self.a.by_ref() {
3131 if let ChainState::Both = self.state {
3132 self.state = ChainState::Back;
3135 ChainState::Back => {}
3137 if let ChainState::Back = self.state {
3145 fn last(self) -> Option<A::Item> {
3147 ChainState::Both => {
3148 // Must exhaust a before b.
3149 let a_last = self.a.last();
3150 let b_last = self.b.last();
3153 ChainState::Front => self.a.last(),
3154 ChainState::Back => self.b.last()
3159 fn size_hint(&self) -> (usize, Option<usize>) {
3160 let (a_lower, a_upper) = self.a.size_hint();
3161 let (b_lower, b_upper) = self.b.size_hint();
3163 let lower = a_lower.saturating_add(b_lower);
3165 let upper = match (a_upper, b_upper) {
3166 (Some(x), Some(y)) => x.checked_add(y),
3174 #[stable(feature = "rust1", since = "1.0.0")]
3175 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3176 A: DoubleEndedIterator,
3177 B: DoubleEndedIterator<Item=A::Item>,
3180 fn next_back(&mut self) -> Option<A::Item> {
3182 ChainState::Both => match self.b.next_back() {
3183 elt @ Some(..) => elt,
3185 self.state = ChainState::Front;
3189 ChainState::Front => self.a.next_back(),
3190 ChainState::Back => self.b.next_back(),
3195 /// An iterator that iterates two other iterators simultaneously.
3197 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3198 /// documentation for more.
3200 /// [`zip()`]: trait.Iterator.html#method.zip
3201 /// [`Iterator`]: trait.Iterator.html
3203 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3204 #[stable(feature = "rust1", since = "1.0.0")]
3205 pub struct Zip<A, B> {
3210 #[stable(feature = "rust1", since = "1.0.0")]
3211 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3213 type Item = (A::Item, B::Item);
3216 fn next(&mut self) -> Option<(A::Item, B::Item)> {
3217 self.a.next().and_then(|x| {
3218 self.b.next().and_then(|y| {
3225 fn size_hint(&self) -> (usize, Option<usize>) {
3226 let (a_lower, a_upper) = self.a.size_hint();
3227 let (b_lower, b_upper) = self.b.size_hint();
3229 let lower = cmp::min(a_lower, b_lower);
3231 let upper = match (a_upper, b_upper) {
3232 (Some(x), Some(y)) => Some(cmp::min(x,y)),
3233 (Some(x), None) => Some(x),
3234 (None, Some(y)) => Some(y),
3235 (None, None) => None
3242 #[stable(feature = "rust1", since = "1.0.0")]
3243 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3244 A: DoubleEndedIterator + ExactSizeIterator,
3245 B: DoubleEndedIterator + ExactSizeIterator,
3248 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3249 let a_sz = self.a.len();
3250 let b_sz = self.b.len();
3252 // Adjust a, b to equal length
3254 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3256 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3259 match (self.a.next_back(), self.b.next_back()) {
3260 (Some(x), Some(y)) => Some((x, y)),
3261 (None, None) => None,
3262 _ => unreachable!(),
3267 /// An iterator that maps the values of `iter` with `f`.
3269 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3270 /// documentation for more.
3272 /// [`map()`]: trait.Iterator.html#method.map
3273 /// [`Iterator`]: trait.Iterator.html
3274 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3275 #[stable(feature = "rust1", since = "1.0.0")]
3277 pub struct Map<I, F> {
3282 #[stable(feature = "rust1", since = "1.0.0")]
3283 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3287 fn next(&mut self) -> Option<B> {
3288 self.iter.next().map(&mut self.f)
3292 fn size_hint(&self) -> (usize, Option<usize>) {
3293 self.iter.size_hint()
3297 #[stable(feature = "rust1", since = "1.0.0")]
3298 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3299 F: FnMut(I::Item) -> B,
3302 fn next_back(&mut self) -> Option<B> {
3303 self.iter.next_back().map(&mut self.f)
3307 /// An iterator that filters the elements of `iter` with `predicate`.
3309 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3310 /// documentation for more.
3312 /// [`filter()`]: trait.Iterator.html#method.filter
3313 /// [`Iterator`]: trait.Iterator.html
3314 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3315 #[stable(feature = "rust1", since = "1.0.0")]
3317 pub struct Filter<I, P> {
3322 #[stable(feature = "rust1", since = "1.0.0")]
3323 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3324 type Item = I::Item;
3327 fn next(&mut self) -> Option<I::Item> {
3328 for x in self.iter.by_ref() {
3329 if (self.predicate)(&x) {
3337 fn size_hint(&self) -> (usize, Option<usize>) {
3338 let (_, upper) = self.iter.size_hint();
3339 (0, upper) // can't know a lower bound, due to the predicate
3343 #[stable(feature = "rust1", since = "1.0.0")]
3344 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3345 where P: FnMut(&I::Item) -> bool,
3348 fn next_back(&mut self) -> Option<I::Item> {
3349 for x in self.iter.by_ref().rev() {
3350 if (self.predicate)(&x) {
3358 /// An iterator that uses `f` to both filter and map elements from `iter`.
3360 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3361 /// documentation for more.
3363 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3364 /// [`Iterator`]: trait.Iterator.html
3365 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3366 #[stable(feature = "rust1", since = "1.0.0")]
3368 pub struct FilterMap<I, F> {
3373 #[stable(feature = "rust1", since = "1.0.0")]
3374 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3375 where F: FnMut(I::Item) -> Option<B>,
3380 fn next(&mut self) -> Option<B> {
3381 for x in self.iter.by_ref() {
3382 if let Some(y) = (self.f)(x) {
3390 fn size_hint(&self) -> (usize, Option<usize>) {
3391 let (_, upper) = self.iter.size_hint();
3392 (0, upper) // can't know a lower bound, due to the predicate
3396 #[stable(feature = "rust1", since = "1.0.0")]
3397 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3398 where F: FnMut(I::Item) -> Option<B>,
3401 fn next_back(&mut self) -> Option<B> {
3402 for x in self.iter.by_ref().rev() {
3403 if let Some(y) = (self.f)(x) {
3411 /// An iterator that yields the current count and the element during iteration.
3413 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3414 /// documentation for more.
3416 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3417 /// [`Iterator`]: trait.Iterator.html
3419 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3420 #[stable(feature = "rust1", since = "1.0.0")]
3421 pub struct Enumerate<I> {
3426 #[stable(feature = "rust1", since = "1.0.0")]
3427 impl<I> Iterator for Enumerate<I> where I: Iterator {
3428 type Item = (usize, <I as Iterator>::Item);
3430 /// # Overflow Behavior
3432 /// The method does no guarding against overflows, so enumerating more than
3433 /// `usize::MAX` elements either produces the wrong result or panics. If
3434 /// debug assertions are enabled, a panic is guaranteed.
3438 /// Might panic if the index of the element overflows a `usize`.
3440 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3441 self.iter.next().map(|a| {
3442 let ret = (self.count, a);
3443 // Possible undefined overflow.
3450 fn size_hint(&self) -> (usize, Option<usize>) {
3451 self.iter.size_hint()
3455 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3456 self.iter.nth(n).map(|a| {
3457 let i = self.count + n;
3464 fn count(self) -> usize {
3469 #[stable(feature = "rust1", since = "1.0.0")]
3470 impl<I> DoubleEndedIterator for Enumerate<I> where
3471 I: ExactSizeIterator + DoubleEndedIterator
3474 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3475 self.iter.next_back().map(|a| {
3476 let len = self.iter.len();
3477 // Can safely add, `ExactSizeIterator` promises that the number of
3478 // elements fits into a `usize`.
3479 (self.count + len, a)
3484 /// An iterator with a `peek()` that returns an optional reference to the next
3487 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3488 /// documentation for more.
3490 /// [`peekable()`]: trait.Iterator.html#method.peekable
3491 /// [`Iterator`]: trait.Iterator.html
3493 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3494 #[stable(feature = "rust1", since = "1.0.0")]
3495 pub struct Peekable<I: Iterator> {
3497 peeked: Option<I::Item>,
3500 #[stable(feature = "rust1", since = "1.0.0")]
3501 impl<I: Iterator> Iterator for Peekable<I> {
3502 type Item = I::Item;
3505 fn next(&mut self) -> Option<I::Item> {
3507 Some(_) => self.peeked.take(),
3508 None => self.iter.next(),
3513 fn count(self) -> usize {
3514 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3518 fn nth(&mut self, n: usize) -> Option<I::Item> {
3520 Some(_) if n == 0 => self.peeked.take(),
3525 None => self.iter.nth(n)
3530 fn last(self) -> Option<I::Item> {
3531 self.iter.last().or(self.peeked)
3535 fn size_hint(&self) -> (usize, Option<usize>) {
3536 let (lo, hi) = self.iter.size_hint();
3537 if self.peeked.is_some() {
3538 let lo = lo.saturating_add(1);
3539 let hi = hi.and_then(|x| x.checked_add(1));
3547 #[stable(feature = "rust1", since = "1.0.0")]
3548 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3550 impl<I: Iterator> Peekable<I> {
3551 /// Returns a reference to the next() value without advancing the iterator.
3553 /// The `peek()` method will return the value that a call to [`next()`] would
3554 /// return, but does not advance the iterator. Like [`next()`], if there is
3555 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3556 /// will return `None`.
3558 /// [`next()`]: trait.Iterator.html#tymethod.next
3560 /// Because `peek()` returns reference, and many iterators iterate over
3561 /// references, this leads to a possibly confusing situation where the
3562 /// return value is a double reference. You can see this effect in the
3563 /// examples below, with `&&i32`.
3570 /// let xs = [1, 2, 3];
3572 /// let mut iter = xs.iter().peekable();
3574 /// // peek() lets us see into the future
3575 /// assert_eq!(iter.peek(), Some(&&1));
3576 /// assert_eq!(iter.next(), Some(&1));
3578 /// assert_eq!(iter.next(), Some(&2));
3580 /// // we can peek() multiple times, the iterator won't advance
3581 /// assert_eq!(iter.peek(), Some(&&3));
3582 /// assert_eq!(iter.peek(), Some(&&3));
3584 /// assert_eq!(iter.next(), Some(&3));
3586 /// // after the iterator is finished, so is peek()
3587 /// assert_eq!(iter.peek(), None);
3588 /// assert_eq!(iter.next(), None);
3591 #[stable(feature = "rust1", since = "1.0.0")]
3592 pub fn peek(&mut self) -> Option<&I::Item> {
3593 if self.peeked.is_none() {
3594 self.peeked = self.iter.next();
3597 Some(ref value) => Some(value),
3602 /// Checks if the iterator has finished iterating.
3604 /// Returns `true` if there are no more elements in the iterator, and
3605 /// `false` if there are.
3612 /// #![feature(peekable_is_empty)]
3614 /// let xs = [1, 2, 3];
3616 /// let mut iter = xs.iter().peekable();
3618 /// // there are still elements to iterate over
3619 /// assert_eq!(iter.is_empty(), false);
3621 /// // let's consume the iterator
3626 /// assert_eq!(iter.is_empty(), true);
3628 #[unstable(feature = "peekable_is_empty", issue = "27701")]
3630 pub fn is_empty(&mut self) -> bool {
3631 self.peek().is_none()
3635 /// An iterator that rejects elements while `predicate` is true.
3637 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3638 /// documentation for more.
3640 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3641 /// [`Iterator`]: trait.Iterator.html
3642 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3643 #[stable(feature = "rust1", since = "1.0.0")]
3645 pub struct SkipWhile<I, P> {
3651 #[stable(feature = "rust1", since = "1.0.0")]
3652 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3653 where P: FnMut(&I::Item) -> bool
3655 type Item = I::Item;
3658 fn next(&mut self) -> Option<I::Item> {
3659 for x in self.iter.by_ref() {
3660 if self.flag || !(self.predicate)(&x) {
3669 fn size_hint(&self) -> (usize, Option<usize>) {
3670 let (_, upper) = self.iter.size_hint();
3671 (0, upper) // can't know a lower bound, due to the predicate
3675 /// An iterator that only accepts elements while `predicate` is true.
3677 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3678 /// documentation for more.
3680 /// [`take_while()`]: trait.Iterator.html#method.take_while
3681 /// [`Iterator`]: trait.Iterator.html
3682 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3683 #[stable(feature = "rust1", since = "1.0.0")]
3685 pub struct TakeWhile<I, P> {
3691 #[stable(feature = "rust1", since = "1.0.0")]
3692 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3693 where P: FnMut(&I::Item) -> bool
3695 type Item = I::Item;
3698 fn next(&mut self) -> Option<I::Item> {
3702 self.iter.next().and_then(|x| {
3703 if (self.predicate)(&x) {
3714 fn size_hint(&self) -> (usize, Option<usize>) {
3715 let (_, upper) = self.iter.size_hint();
3716 (0, upper) // can't know a lower bound, due to the predicate
3720 /// An iterator that skips over `n` elements of `iter`.
3722 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3723 /// documentation for more.
3725 /// [`skip()`]: trait.Iterator.html#method.skip
3726 /// [`Iterator`]: trait.Iterator.html
3728 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3729 #[stable(feature = "rust1", since = "1.0.0")]
3730 pub struct Skip<I> {
3735 #[stable(feature = "rust1", since = "1.0.0")]
3736 impl<I> Iterator for Skip<I> where I: Iterator {
3737 type Item = <I as Iterator>::Item;
3740 fn next(&mut self) -> Option<I::Item> {
3746 self.iter.nth(old_n)
3751 fn nth(&mut self, n: usize) -> Option<I::Item> {
3752 // Can't just add n + self.n due to overflow.
3756 let to_skip = self.n;
3759 if self.iter.nth(to_skip-1).is_none() {
3767 fn count(self) -> usize {
3768 self.iter.count().saturating_sub(self.n)
3772 fn last(mut self) -> Option<I::Item> {
3776 let next = self.next();
3778 // recurse. n should be 0.
3779 self.last().or(next)
3787 fn size_hint(&self) -> (usize, Option<usize>) {
3788 let (lower, upper) = self.iter.size_hint();
3790 let lower = lower.saturating_sub(self.n);
3791 let upper = upper.map(|x| x.saturating_sub(self.n));
3797 #[stable(feature = "rust1", since = "1.0.0")]
3798 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3800 /// An iterator that only iterates over the first `n` iterations of `iter`.
3802 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3803 /// documentation for more.
3805 /// [`take()`]: trait.Iterator.html#method.take
3806 /// [`Iterator`]: trait.Iterator.html
3808 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3809 #[stable(feature = "rust1", since = "1.0.0")]
3810 pub struct Take<I> {
3815 #[stable(feature = "rust1", since = "1.0.0")]
3816 impl<I> Iterator for Take<I> where I: Iterator{
3817 type Item = <I as Iterator>::Item;
3820 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3830 fn nth(&mut self, n: usize) -> Option<I::Item> {
3836 self.iter.nth(self.n - 1);
3844 fn size_hint(&self) -> (usize, Option<usize>) {
3845 let (lower, upper) = self.iter.size_hint();
3847 let lower = cmp::min(lower, self.n);
3849 let upper = match upper {
3850 Some(x) if x < self.n => Some(x),
3858 #[stable(feature = "rust1", since = "1.0.0")]
3859 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3862 /// An iterator to maintain state while iterating another iterator.
3864 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3865 /// documentation for more.
3867 /// [`scan()`]: trait.Iterator.html#method.scan
3868 /// [`Iterator`]: trait.Iterator.html
3869 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3870 #[stable(feature = "rust1", since = "1.0.0")]
3872 pub struct Scan<I, St, F> {
3878 #[stable(feature = "rust1", since = "1.0.0")]
3879 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3881 F: FnMut(&mut St, I::Item) -> Option<B>,
3886 fn next(&mut self) -> Option<B> {
3887 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3891 fn size_hint(&self) -> (usize, Option<usize>) {
3892 let (_, upper) = self.iter.size_hint();
3893 (0, upper) // can't know a lower bound, due to the scan function
3897 /// An iterator that maps each element to an iterator, and yields the elements
3898 /// of the produced iterators.
3900 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3901 /// documentation for more.
3903 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
3904 /// [`Iterator`]: trait.Iterator.html
3905 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3906 #[stable(feature = "rust1", since = "1.0.0")]
3908 pub struct FlatMap<I, U: IntoIterator, F> {
3911 frontiter: Option<U::IntoIter>,
3912 backiter: Option<U::IntoIter>,
3915 #[stable(feature = "rust1", since = "1.0.0")]
3916 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
3917 where F: FnMut(I::Item) -> U,
3919 type Item = U::Item;
3922 fn next(&mut self) -> Option<U::Item> {
3924 if let Some(ref mut inner) = self.frontiter {
3925 if let Some(x) = inner.by_ref().next() {
3929 match self.iter.next().map(&mut self.f) {
3930 None => return self.backiter.as_mut().and_then(|it| it.next()),
3931 next => self.frontiter = next.map(IntoIterator::into_iter),
3937 fn size_hint(&self) -> (usize, Option<usize>) {
3938 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3939 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3940 let lo = flo.saturating_add(blo);
3941 match (self.iter.size_hint(), fhi, bhi) {
3942 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
3948 #[stable(feature = "rust1", since = "1.0.0")]
3949 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
3950 F: FnMut(I::Item) -> U,
3952 U::IntoIter: DoubleEndedIterator
3955 fn next_back(&mut self) -> Option<U::Item> {
3957 if let Some(ref mut inner) = self.backiter {
3958 if let Some(y) = inner.next_back() {
3962 match self.iter.next_back().map(&mut self.f) {
3963 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
3964 next => self.backiter = next.map(IntoIterator::into_iter),
3970 /// An iterator that yields `None` forever after the underlying iterator
3971 /// yields `None` once.
3973 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
3974 /// documentation for more.
3976 /// [`fuse()`]: trait.Iterator.html#method.fuse
3977 /// [`Iterator`]: trait.Iterator.html
3979 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3980 #[stable(feature = "rust1", since = "1.0.0")]
3981 pub struct Fuse<I> {
3986 #[stable(feature = "rust1", since = "1.0.0")]
3987 impl<I> Iterator for Fuse<I> where I: Iterator {
3988 type Item = <I as Iterator>::Item;
3991 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3995 let next = self.iter.next();
3996 self.done = next.is_none();
4002 fn nth(&mut self, n: usize) -> Option<I::Item> {
4006 let nth = self.iter.nth(n);
4007 self.done = nth.is_none();
4013 fn last(self) -> Option<I::Item> {
4022 fn count(self) -> usize {
4031 fn size_hint(&self) -> (usize, Option<usize>) {
4035 self.iter.size_hint()
4040 #[stable(feature = "rust1", since = "1.0.0")]
4041 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
4043 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
4047 let next = self.iter.next_back();
4048 self.done = next.is_none();
4054 #[stable(feature = "rust1", since = "1.0.0")]
4055 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
4057 /// An iterator that calls a function with a reference to each element before
4060 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
4061 /// documentation for more.
4063 /// [`inspect()`]: trait.Iterator.html#method.inspect
4064 /// [`Iterator`]: trait.Iterator.html
4065 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4066 #[stable(feature = "rust1", since = "1.0.0")]
4068 pub struct Inspect<I, F> {
4073 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
4075 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
4076 if let Some(ref a) = elt {
4084 #[stable(feature = "rust1", since = "1.0.0")]
4085 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
4086 type Item = I::Item;
4089 fn next(&mut self) -> Option<I::Item> {
4090 let next = self.iter.next();
4091 self.do_inspect(next)
4095 fn size_hint(&self) -> (usize, Option<usize>) {
4096 self.iter.size_hint()
4100 #[stable(feature = "rust1", since = "1.0.0")]
4101 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
4102 where F: FnMut(&I::Item),
4105 fn next_back(&mut self) -> Option<I::Item> {
4106 let next = self.iter.next_back();
4107 self.do_inspect(next)
4111 /// Objects that can be stepped over in both directions.
4113 /// The `steps_between` function provides a way to efficiently compare
4114 /// two `Step` objects.
4115 #[unstable(feature = "step_trait",
4116 reason = "likely to be replaced by finer-grained traits",
4118 pub trait Step: PartialOrd + Sized {
4119 /// Steps `self` if possible.
4120 fn step(&self, by: &Self) -> Option<Self>;
4122 /// Returns the number of steps between two step objects. The count is
4123 /// inclusive of `start` and exclusive of `end`.
4125 /// Returns `None` if it is not possible to calculate `steps_between`
4126 /// without overflow.
4127 fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
4130 macro_rules! step_impl_unsigned {
4132 #[unstable(feature = "step_trait",
4133 reason = "likely to be replaced by finer-grained traits",
4137 fn step(&self, by: &$t) -> Option<$t> {
4138 (*self).checked_add(*by)
4141 #[allow(trivial_numeric_casts)]
4142 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4143 if *by == 0 { return None; }
4145 // Note: We assume $t <= usize here
4146 let diff = (*end - *start) as usize;
4147 let by = *by as usize;
4160 macro_rules! step_impl_signed {
4162 #[unstable(feature = "step_trait",
4163 reason = "likely to be replaced by finer-grained traits",
4167 fn step(&self, by: &$t) -> Option<$t> {
4168 (*self).checked_add(*by)
4171 #[allow(trivial_numeric_casts)]
4172 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4173 if *by == 0 { return None; }
4180 // Note: We assume $t <= isize here
4181 // Use .wrapping_sub and cast to usize to compute the
4182 // difference that may not fit inside the range of isize.
4183 diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4184 by_u = *by as usize;
4189 diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4190 by_u = (*by as isize).wrapping_mul(-1) as usize;
4192 if diff % by_u > 0 {
4193 Some(diff / by_u + 1)
4202 macro_rules! step_impl_no_between {
4204 #[unstable(feature = "step_trait",
4205 reason = "likely to be replaced by finer-grained traits",
4209 fn step(&self, by: &$t) -> Option<$t> {
4210 (*self).checked_add(*by)
4213 fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4220 step_impl_unsigned!(usize u8 u16 u32);
4221 step_impl_signed!(isize i8 i16 i32);
4222 #[cfg(target_pointer_width = "64")]
4223 step_impl_unsigned!(u64);
4224 #[cfg(target_pointer_width = "64")]
4225 step_impl_signed!(i64);
4226 // If the target pointer width is not 64-bits, we
4227 // assume here that it is less than 64-bits.
4228 #[cfg(not(target_pointer_width = "64"))]
4229 step_impl_no_between!(u64 i64);
4231 /// An adapter for stepping range iterators by a custom amount.
4233 /// The resulting iterator handles overflow by stopping. The `A`
4234 /// parameter is the type being iterated over, while `R` is the range
4235 /// type (usually one of `std::ops::{Range, RangeFrom}`.
4237 #[unstable(feature = "step_by", reason = "recent addition",
4239 pub struct StepBy<A, R> {
4244 impl<A: Step> RangeFrom<A> {
4245 /// Creates an iterator starting at the same point, but stepping by
4246 /// the given amount at each iteration.
4251 /// for i in (0u8..).step_by(2) {
4252 /// println!("{}", i);
4256 /// This prints all even `u8` values.
4257 #[unstable(feature = "step_by", reason = "recent addition",
4259 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4267 impl<A: Step> ops::Range<A> {
4268 /// Creates an iterator with the same range, but stepping by the
4269 /// given amount at each iteration.
4271 /// The resulting iterator handles overflow by stopping.
4276 /// #![feature(step_by)]
4278 /// for i in (0..10).step_by(2) {
4279 /// println!("{}", i);
4292 #[unstable(feature = "step_by", reason = "recent addition",
4294 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4302 #[stable(feature = "rust1", since = "1.0.0")]
4303 impl<A> Iterator for StepBy<A, RangeFrom<A>> where
4305 for<'a> &'a A: Add<&'a A, Output = A>
4310 fn next(&mut self) -> Option<A> {
4311 let mut n = &self.range.start + &self.step_by;
4312 mem::swap(&mut n, &mut self.range.start);
4317 fn size_hint(&self) -> (usize, Option<usize>) {
4318 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4322 /// An iterator over the range [start, stop]
4324 #[unstable(feature = "range_inclusive",
4325 reason = "likely to be replaced by range notation and adapters",
4327 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4328 #[allow(deprecated)]
4329 pub struct RangeInclusive<A> {
4330 range: ops::Range<A>,
4334 /// Returns an iterator over the range [start, stop].
4336 #[unstable(feature = "range_inclusive",
4337 reason = "likely to be replaced by range notation and adapters",
4339 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4340 #[allow(deprecated)]
4341 pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
4342 where A: Step + One + Clone
4350 #[unstable(feature = "range_inclusive",
4351 reason = "likely to be replaced by range notation and adapters",
4353 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4354 #[allow(deprecated)]
4355 impl<A> Iterator for RangeInclusive<A> where
4356 A: PartialEq + Step + One + Clone,
4357 for<'a> &'a A: Add<&'a A, Output = A>
4362 fn next(&mut self) -> Option<A> {
4363 self.range.next().or_else(|| {
4364 if !self.done && self.range.start == self.range.end {
4366 Some(self.range.end.clone())
4374 fn size_hint(&self) -> (usize, Option<usize>) {
4375 let (lo, hi) = self.range.size_hint();
4379 let lo = lo.saturating_add(1);
4380 let hi = hi.and_then(|x| x.checked_add(1));
4386 #[unstable(feature = "range_inclusive",
4387 reason = "likely to be replaced by range notation and adapters",
4389 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4390 #[allow(deprecated)]
4391 impl<A> DoubleEndedIterator for RangeInclusive<A> where
4392 A: PartialEq + Step + One + Clone,
4393 for<'a> &'a A: Add<&'a A, Output = A>,
4394 for<'a> &'a A: Sub<Output=A>
4397 fn next_back(&mut self) -> Option<A> {
4398 if self.range.end > self.range.start {
4399 let result = self.range.end.clone();
4400 self.range.end = &self.range.end - &A::one();
4402 } else if !self.done && self.range.start == self.range.end {
4404 Some(self.range.end.clone())
4411 #[stable(feature = "rust1", since = "1.0.0")]
4412 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4416 fn next(&mut self) -> Option<A> {
4417 let rev = self.step_by < A::zero();
4418 if (rev && self.range.start > self.range.end) ||
4419 (!rev && self.range.start < self.range.end)
4421 match self.range.start.step(&self.step_by) {
4423 mem::swap(&mut self.range.start, &mut n);
4427 let mut n = self.range.end.clone();
4428 mem::swap(&mut self.range.start, &mut n);
4438 fn size_hint(&self) -> (usize, Option<usize>) {
4439 match Step::steps_between(&self.range.start,
4442 Some(hint) => (hint, Some(hint)),
4448 macro_rules! range_exact_iter_impl {
4450 #[stable(feature = "rust1", since = "1.0.0")]
4451 impl ExactSizeIterator for ops::Range<$t> { }
4455 #[stable(feature = "rust1", since = "1.0.0")]
4456 impl<A: Step + One> Iterator for ops::Range<A> where
4457 for<'a> &'a A: Add<&'a A, Output = A>
4462 fn next(&mut self) -> Option<A> {
4463 if self.start < self.end {
4464 let mut n = &self.start + &A::one();
4465 mem::swap(&mut n, &mut self.start);
4473 fn size_hint(&self) -> (usize, Option<usize>) {
4474 match Step::steps_between(&self.start, &self.end, &A::one()) {
4475 Some(hint) => (hint, Some(hint)),
4481 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4482 // a length <= usize::MAX, which is required by ExactSizeIterator.
4483 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4485 #[stable(feature = "rust1", since = "1.0.0")]
4486 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4487 for<'a> &'a A: Add<&'a A, Output = A>,
4488 for<'a> &'a A: Sub<&'a A, Output = A>
4491 fn next_back(&mut self) -> Option<A> {
4492 if self.start < self.end {
4493 self.end = &self.end - &A::one();
4494 Some(self.end.clone())
4501 #[stable(feature = "rust1", since = "1.0.0")]
4502 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4503 for<'a> &'a A: Add<&'a A, Output = A>
4508 fn next(&mut self) -> Option<A> {
4509 let mut n = &self.start + &A::one();
4510 mem::swap(&mut n, &mut self.start);
4515 /// An iterator that repeats an element endlessly.
4517 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4519 /// [`repeat()`]: fn.repeat.html
4521 #[stable(feature = "rust1", since = "1.0.0")]
4522 pub struct Repeat<A> {
4526 #[stable(feature = "rust1", since = "1.0.0")]
4527 impl<A: Clone> Iterator for Repeat<A> {
4531 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4533 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4536 #[stable(feature = "rust1", since = "1.0.0")]
4537 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4539 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4542 /// Creates a new iterator that endlessly repeats a single element.
4544 /// The `repeat()` function repeats a single value over and over and over and
4545 /// over and over and 🔁.
4547 /// Infinite iterators like `repeat()` are often used with adapters like
4548 /// [`take()`], in order to make them finite.
4550 /// [`take()`]: trait.Iterator.html#method.take
4559 /// // the number four 4ever:
4560 /// let mut fours = iter::repeat(4);
4562 /// assert_eq!(Some(4), fours.next());
4563 /// assert_eq!(Some(4), fours.next());
4564 /// assert_eq!(Some(4), fours.next());
4565 /// assert_eq!(Some(4), fours.next());
4566 /// assert_eq!(Some(4), fours.next());
4568 /// // yup, still four
4569 /// assert_eq!(Some(4), fours.next());
4572 /// Going finite with [`take()`]:
4577 /// // that last example was too many fours. Let's only have four fours.
4578 /// let mut four_fours = iter::repeat(4).take(4);
4580 /// assert_eq!(Some(4), four_fours.next());
4581 /// assert_eq!(Some(4), four_fours.next());
4582 /// assert_eq!(Some(4), four_fours.next());
4583 /// assert_eq!(Some(4), four_fours.next());
4585 /// // ... and now we're done
4586 /// assert_eq!(None, four_fours.next());
4589 #[stable(feature = "rust1", since = "1.0.0")]
4590 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4591 Repeat{element: elt}
4594 /// An iterator that yields nothing.
4596 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4598 /// [`empty()`]: fn.empty.html
4599 #[stable(feature = "iter_empty", since = "1.2.0")]
4600 pub struct Empty<T>(marker::PhantomData<T>);
4602 #[stable(feature = "iter_empty", since = "1.2.0")]
4603 impl<T> Iterator for Empty<T> {
4606 fn next(&mut self) -> Option<T> {
4610 fn size_hint(&self) -> (usize, Option<usize>){
4615 #[stable(feature = "iter_empty", since = "1.2.0")]
4616 impl<T> DoubleEndedIterator for Empty<T> {
4617 fn next_back(&mut self) -> Option<T> {
4622 #[stable(feature = "iter_empty", since = "1.2.0")]
4623 impl<T> ExactSizeIterator for Empty<T> {
4624 fn len(&self) -> usize {
4629 // not #[derive] because that adds a Clone bound on T,
4630 // which isn't necessary.
4631 #[stable(feature = "iter_empty", since = "1.2.0")]
4632 impl<T> Clone for Empty<T> {
4633 fn clone(&self) -> Empty<T> {
4634 Empty(marker::PhantomData)
4638 // not #[derive] because that adds a Default bound on T,
4639 // which isn't necessary.
4640 #[stable(feature = "iter_empty", since = "1.2.0")]
4641 impl<T> Default for Empty<T> {
4642 fn default() -> Empty<T> {
4643 Empty(marker::PhantomData)
4647 /// Creates an iterator that yields nothing.
4656 /// // this could have been an iterator over i32, but alas, it's just not.
4657 /// let mut nope = iter::empty::<i32>();
4659 /// assert_eq!(None, nope.next());
4661 #[stable(feature = "iter_empty", since = "1.2.0")]
4662 pub fn empty<T>() -> Empty<T> {
4663 Empty(marker::PhantomData)
4666 /// An iterator that yields an element exactly once.
4668 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4670 /// [`once()`]: fn.once.html
4672 #[stable(feature = "iter_once", since = "1.2.0")]
4673 pub struct Once<T> {
4674 inner: ::option::IntoIter<T>
4677 #[stable(feature = "iter_once", since = "1.2.0")]
4678 impl<T> Iterator for Once<T> {
4681 fn next(&mut self) -> Option<T> {
4685 fn size_hint(&self) -> (usize, Option<usize>) {
4686 self.inner.size_hint()
4690 #[stable(feature = "iter_once", since = "1.2.0")]
4691 impl<T> DoubleEndedIterator for Once<T> {
4692 fn next_back(&mut self) -> Option<T> {
4693 self.inner.next_back()
4697 #[stable(feature = "iter_once", since = "1.2.0")]
4698 impl<T> ExactSizeIterator for Once<T> {
4699 fn len(&self) -> usize {
4704 /// Creates an iterator that yields an element exactly once.
4706 /// This is commonly used to adapt a single value into a [`chain()`] of other
4707 /// kinds of iteration. Maybe you have an iterator that covers almost
4708 /// everything, but you need an extra special case. Maybe you have a function
4709 /// which works on iterators, but you only need to process one value.
4711 /// [`chain()`]: trait.Iterator.html#method.chain
4720 /// // one is the loneliest number
4721 /// let mut one = iter::once(1);
4723 /// assert_eq!(Some(1), one.next());
4725 /// // just one, that's all we get
4726 /// assert_eq!(None, one.next());
4729 /// Chaining together with another iterator. Let's say that we want to iterate
4730 /// over each file of the `.foo` directory, but also a configuration file,
4736 /// use std::path::PathBuf;
4738 /// let dirs = fs::read_dir(".foo").unwrap();
4740 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4741 /// // PathBufs, so we use map
4742 /// let dirs = dirs.map(|file| file.unwrap().path());
4744 /// // now, our iterator just for our config file
4745 /// let config = iter::once(PathBuf::from(".foorc"));
4747 /// // chain the two iterators together into one big iterator
4748 /// let files = dirs.chain(config);
4750 /// // this will give us all of the files in .foo as well as .foorc
4751 /// for f in files {
4752 /// println!("{:?}", f);
4755 #[stable(feature = "iter_once", since = "1.2.0")]
4756 pub fn once<T>(value: T) -> Once<T> {
4757 Once { inner: Some(value).into_iter() }