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
324 #[stable(feature = "rust1", since = "1.0.0")]
325 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
326 `.iter()` or a similar method"]
328 /// The type of the elements being iterated over.
329 #[stable(feature = "rust1", since = "1.0.0")]
332 /// Advances the iterator and returns the next value.
334 /// Returns `None` when iteration is finished. Individual iterator
335 /// implementations may choose to resume iteration, and so calling `next()`
336 /// again may or may not eventually start returning `Some(Item)` again at some
344 /// let a = [1, 2, 3];
346 /// let mut iter = a.iter();
348 /// // A call to next() returns the next value...
349 /// assert_eq!(Some(&1), iter.next());
350 /// assert_eq!(Some(&2), iter.next());
351 /// assert_eq!(Some(&3), iter.next());
353 /// // ... and then None once it's over.
354 /// assert_eq!(None, iter.next());
356 /// // More calls may or may not return None. Here, they always will.
357 /// assert_eq!(None, iter.next());
358 /// assert_eq!(None, iter.next());
360 #[stable(feature = "rust1", since = "1.0.0")]
361 fn next(&mut self) -> Option<Self::Item>;
363 /// Returns the bounds on the remaining length of the iterator.
365 /// Specifically, `size_hint()` returns a tuple where the first element
366 /// is the lower bound, and the second element is the upper bound.
368 /// The second half of the tuple that is returned is an `Option<usize>`. A
369 /// `None` here means that either there is no known upper bound, or the
370 /// upper bound is larger than `usize`.
372 /// # Implementation notes
374 /// It is not enforced that an iterator implementation yields the declared
375 /// number of elements. A buggy iterator may yield less than the lower bound
376 /// or more than the upper bound of elements.
378 /// `size_hint()` is primarily intended to be used for optimizations such as
379 /// reserving space for the elements of the iterator, but must not be
380 /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
381 /// implementation of `size_hint()` should not lead to memory safety
384 /// That said, the implementation should provide a correct estimation,
385 /// because otherwise it would be a violation of the trait's protocol.
387 /// The default implementation returns `(0, None)` which is correct for any
395 /// let a = [1, 2, 3];
396 /// let iter = a.iter();
398 /// assert_eq!((3, Some(3)), iter.size_hint());
401 /// A more complex example:
404 /// // The even numbers from zero to ten.
405 /// let iter = (0..10).filter(|x| x % 2 == 0);
407 /// // We might iterate from zero to ten times. Knowing that it's five
408 /// // exactly wouldn't be possible without executing filter().
409 /// assert_eq!((0, Some(10)), iter.size_hint());
411 /// // Let's add one five more numbers with chain()
412 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
414 /// // now both bounds are increased by five
415 /// assert_eq!((5, Some(15)), iter.size_hint());
418 /// Returning `None` for an upper bound:
421 /// // an infinite iterator has no upper bound
424 /// assert_eq!((0, None), iter.size_hint());
427 #[stable(feature = "rust1", since = "1.0.0")]
428 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
430 /// Consumes the iterator, counting the number of iterations and returning it.
432 /// This method will evaluate the iterator until its [`next()`] returns
433 /// `None`. Once `None` is encountered, `count()` returns the number of
434 /// times it called [`next()`].
436 /// [`next()`]: #method.next
438 /// # Overflow Behavior
440 /// The method does no guarding against overflows, so counting elements of
441 /// an iterator with more than `usize::MAX` elements either produces the
442 /// wrong result or panics. If debug assertions are enabled, a panic is
447 /// This function might panic if the iterator has more than `usize::MAX`
455 /// let a = [1, 2, 3];
456 /// assert_eq!(a.iter().count(), 3);
458 /// let a = [1, 2, 3, 4, 5];
459 /// assert_eq!(a.iter().count(), 5);
462 #[stable(feature = "rust1", since = "1.0.0")]
463 fn count(self) -> usize where Self: Sized {
465 self.fold(0, |cnt, _| cnt + 1)
468 /// Consumes the iterator, returning the last element.
470 /// This method will evaluate the iterator until it returns `None`. While
471 /// doing so, it keeps track of the current element. After `None` is
472 /// returned, `last()` will then return the last element it saw.
479 /// let a = [1, 2, 3];
480 /// assert_eq!(a.iter().last(), Some(&3));
482 /// let a = [1, 2, 3, 4, 5];
483 /// assert_eq!(a.iter().last(), Some(&5));
486 #[stable(feature = "rust1", since = "1.0.0")]
487 fn last(self) -> Option<Self::Item> where Self: Sized {
489 for x in self { last = Some(x); }
493 /// Consumes the `n` first elements of the iterator, then returns the
496 /// This method will evaluate the iterator `n` times, discarding those elements.
497 /// After it does so, it will call [`next()`] and return its value.
499 /// [`next()`]: #method.next
501 /// Like most indexing operations, the count starts from zero, so `nth(0)`
502 /// returns the first value, `nth(1)` the second, and so on.
504 /// `nth()` will return `None` if `n` is larger than the length of the
512 /// let a = [1, 2, 3];
513 /// assert_eq!(a.iter().nth(1), Some(&2));
516 /// Calling `nth()` multiple times doesn't rewind the iterator:
519 /// let a = [1, 2, 3];
521 /// let mut iter = a.iter();
523 /// assert_eq!(iter.nth(1), Some(&2));
524 /// assert_eq!(iter.nth(1), None);
527 /// Returning `None` if there are less than `n` elements:
530 /// let a = [1, 2, 3];
531 /// assert_eq!(a.iter().nth(10), None);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
537 if n == 0 { return Some(x) }
543 /// Takes two iterators and creates a new iterator over both in sequence.
545 /// `chain()` will return a new iterator which will first iterate over
546 /// values from the first iterator and then over values from the second
549 /// In other words, it links two iterators together, in a chain. 🔗
556 /// let a1 = [1, 2, 3];
557 /// let a2 = [4, 5, 6];
559 /// let mut iter = a1.iter().chain(a2.iter());
561 /// assert_eq!(iter.next(), Some(&1));
562 /// assert_eq!(iter.next(), Some(&2));
563 /// assert_eq!(iter.next(), Some(&3));
564 /// assert_eq!(iter.next(), Some(&4));
565 /// assert_eq!(iter.next(), Some(&5));
566 /// assert_eq!(iter.next(), Some(&6));
567 /// assert_eq!(iter.next(), None);
570 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
571 /// anything that can be converted into an [`Iterator`], not just an
572 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
573 /// [`IntoIterator`], and so can be passed to `chain()` directly:
575 /// [`IntoIterator`]: trait.IntoIterator.html
576 /// [`Iterator`]: trait.Iterator.html
579 /// let s1 = &[1, 2, 3];
580 /// let s2 = &[4, 5, 6];
582 /// let mut iter = s1.iter().chain(s2);
584 /// assert_eq!(iter.next(), Some(&1));
585 /// assert_eq!(iter.next(), Some(&2));
586 /// assert_eq!(iter.next(), Some(&3));
587 /// assert_eq!(iter.next(), Some(&4));
588 /// assert_eq!(iter.next(), Some(&5));
589 /// assert_eq!(iter.next(), Some(&6));
590 /// assert_eq!(iter.next(), None);
593 #[stable(feature = "rust1", since = "1.0.0")]
594 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
595 Self: Sized, U: IntoIterator<Item=Self::Item>,
597 Chain{a: self, b: other.into_iter(), state: ChainState::Both}
600 /// 'Zips up' two iterators into a single iterator of pairs.
602 /// `zip()` returns a new iterator that will iterate over two other
603 /// iterators, returning a tuple where the first element comes from the
604 /// first iterator, and the second element comes from the second iterator.
606 /// In other words, it zips two iterators together, into a single one.
608 /// When either iterator returns `None`, all further calls to `next()`
609 /// will return `None`.
616 /// let a1 = [1, 2, 3];
617 /// let a2 = [4, 5, 6];
619 /// let mut iter = a1.iter().zip(a2.iter());
621 /// assert_eq!(iter.next(), Some((&1, &4)));
622 /// assert_eq!(iter.next(), Some((&2, &5)));
623 /// assert_eq!(iter.next(), Some((&3, &6)));
624 /// assert_eq!(iter.next(), None);
627 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
628 /// anything that can be converted into an [`Iterator`], not just an
629 /// [`Iterator`] itself. For example, slices (`&[T]`) implement
630 /// [`IntoIterator`], and so can be passed to `zip()` directly:
632 /// [`IntoIterator`]: trait.IntoIterator.html
633 /// [`Iterator`]: trait.Iterator.html
636 /// let s1 = &[1, 2, 3];
637 /// let s2 = &[4, 5, 6];
639 /// let mut iter = s1.iter().zip(s2);
641 /// assert_eq!(iter.next(), Some((&1, &4)));
642 /// assert_eq!(iter.next(), Some((&2, &5)));
643 /// assert_eq!(iter.next(), Some((&3, &6)));
644 /// assert_eq!(iter.next(), None);
647 /// `zip()` is often used to zip an infinite iterator to a finite one.
648 /// This works because the finite iterator will eventually return `None`,
649 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
652 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
654 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
656 /// assert_eq!((0, 'f'), enumerate[0]);
657 /// assert_eq!((0, 'f'), zipper[0]);
659 /// assert_eq!((1, 'o'), enumerate[1]);
660 /// assert_eq!((1, 'o'), zipper[1]);
662 /// assert_eq!((2, 'o'), enumerate[2]);
663 /// assert_eq!((2, 'o'), zipper[2]);
666 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
668 #[stable(feature = "rust1", since = "1.0.0")]
669 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
670 Self: Sized, U: IntoIterator
672 Zip{a: self, b: other.into_iter()}
675 /// Takes a closure and creates an iterator which calls that closure on each
678 /// `map()` transforms one iterator into another, by means of its argument:
679 /// something that implements `FnMut`. It produces a new iterator which
680 /// calls this closure on each element of the original iterator.
682 /// If you are good at thinking in types, you can think of `map()` like this:
683 /// If you have an iterator that gives you elements of some type `A`, and
684 /// you want an iterator of some other type `B`, you can use `map()`,
685 /// passing a closure that takes an `A` and returns a `B`.
687 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
688 /// lazy, it is best used when you're already working with other iterators.
689 /// If you're doing some sort of looping for a side effect, it's considered
690 /// more idiomatic to use [`for`] than `map()`.
692 /// [`for`]: ../../book/loops.html#for
699 /// let a = [1, 2, 3];
701 /// let mut iter = a.into_iter().map(|x| 2 * x);
703 /// assert_eq!(iter.next(), Some(2));
704 /// assert_eq!(iter.next(), Some(4));
705 /// assert_eq!(iter.next(), Some(6));
706 /// assert_eq!(iter.next(), None);
709 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
712 /// # #![allow(unused_must_use)]
713 /// // don't do this:
714 /// (0..5).map(|x| println!("{}", x));
716 /// // it won't even execute, as it is lazy. Rust will warn you about this.
718 /// // Instead, use for:
720 /// println!("{}", x);
724 #[stable(feature = "rust1", since = "1.0.0")]
725 fn map<B, F>(self, f: F) -> Map<Self, F> where
726 Self: Sized, F: FnMut(Self::Item) -> B,
728 Map{iter: self, f: f}
731 /// Creates an iterator which uses a closure to determine if an element
732 /// should be yielded.
734 /// The closure must return `true` or `false`. `filter()` creates an
735 /// iterator which calls this closure on each element. If the closure
736 /// returns `true`, then the element is returned. If the closure returns
737 /// `false`, it will try again, and call the closure on the next element,
738 /// seeing if it passes the test.
745 /// let a = [0i32, 1, 2];
747 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
749 /// assert_eq!(iter.next(), Some(&1));
750 /// assert_eq!(iter.next(), Some(&2));
751 /// assert_eq!(iter.next(), None);
754 /// Because the closure passed to `filter()` takes a reference, and many
755 /// iterators iterate over references, this leads to a possibly confusing
756 /// situation, where the type of the closure is a double reference:
759 /// let a = [0, 1, 2];
761 /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
763 /// assert_eq!(iter.next(), Some(&2));
764 /// assert_eq!(iter.next(), None);
767 /// It's common to instead use destructuring on the argument to strip away
771 /// let a = [0, 1, 2];
773 /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
775 /// assert_eq!(iter.next(), Some(&2));
776 /// assert_eq!(iter.next(), None);
782 /// let a = [0, 1, 2];
784 /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
786 /// assert_eq!(iter.next(), Some(&2));
787 /// assert_eq!(iter.next(), None);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 fn filter<P>(self, predicate: P) -> Filter<Self, P> where
794 Self: Sized, P: FnMut(&Self::Item) -> bool,
796 Filter{iter: self, predicate: predicate}
799 /// Creates an iterator that both filters and maps.
801 /// The closure must return an [`Option<T>`]. `filter_map()` creates an
802 /// iterator which calls this closure on each element. If the closure
803 /// returns `Some(element)`, then that element is returned. If the
804 /// closure returns `None`, it will try again, and call the closure on the
805 /// next element, seeing if it will return `Some`.
807 /// [`Option<T>`]: ../option/enum.Option.html
809 /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
812 /// [`filter()`]: #method.filter
813 /// [`map()`]: #method.map
815 /// > If the closure returns `Some(element)`, then that element is returned.
817 /// In other words, it removes the [`Option<T>`] layer automatically. If your
818 /// mapping is already returning an [`Option<T>`] and you want to skip over
819 /// `None`s, then `filter_map()` is much, much nicer to use.
826 /// let a = ["1", "2", "lol"];
828 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
830 /// assert_eq!(iter.next(), Some(1));
831 /// assert_eq!(iter.next(), Some(2));
832 /// assert_eq!(iter.next(), None);
835 /// Here's the same example, but with [`filter()`] and [`map()`]:
838 /// let a = ["1", "2", "lol"];
840 /// let mut iter = a.iter()
841 /// .map(|s| s.parse().ok())
842 /// .filter(|s| s.is_some());
844 /// assert_eq!(iter.next(), Some(Some(1)));
845 /// assert_eq!(iter.next(), Some(Some(2)));
846 /// assert_eq!(iter.next(), None);
849 /// There's an extra layer of `Some` in there.
851 #[stable(feature = "rust1", since = "1.0.0")]
852 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
853 Self: Sized, F: FnMut(Self::Item) -> Option<B>,
855 FilterMap { iter: self, f: f }
858 /// Creates an iterator which gives the current iteration count as well as
861 /// The iterator returned yields pairs `(i, val)`, where `i` is the
862 /// current index of iteration and `val` is the value returned by the
865 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
866 /// different sized integer, the [`zip()`] function provides similar
869 /// [`usize`]: ../primitive.usize.html
870 /// [`zip()`]: #method.zip
872 /// # Overflow Behavior
874 /// The method does no guarding against overflows, so enumerating more than
875 /// [`usize::MAX`] elements either produces the wrong result or panics. If
876 /// debug assertions are enabled, a panic is guaranteed.
878 /// [`usize::MAX`]: ../usize/constant.MAX.html
882 /// The returned iterator might panic if the to-be-returned index would
883 /// overflow a `usize`.
888 /// let a = [1, 2, 3];
890 /// let mut iter = a.iter().enumerate();
892 /// assert_eq!(iter.next(), Some((0, &1)));
893 /// assert_eq!(iter.next(), Some((1, &2)));
894 /// assert_eq!(iter.next(), Some((2, &3)));
895 /// assert_eq!(iter.next(), None);
898 #[stable(feature = "rust1", since = "1.0.0")]
899 fn enumerate(self) -> Enumerate<Self> where Self: Sized {
900 Enumerate { iter: self, count: 0 }
903 /// Creates an iterator which can look at the `next()` element without
906 /// Adds a [`peek()`] method to an iterator. See its documentation for
907 /// more information.
909 /// [`peek()`]: struct.Peekable.html#method.peek
916 /// let xs = [1, 2, 3];
918 /// let mut iter = xs.iter().peekable();
920 /// // peek() lets us see into the future
921 /// assert_eq!(iter.peek(), Some(&&1));
922 /// assert_eq!(iter.next(), Some(&1));
924 /// assert_eq!(iter.next(), Some(&2));
926 /// // we can peek() multiple times, the iterator won't advance
927 /// assert_eq!(iter.peek(), Some(&&3));
928 /// assert_eq!(iter.peek(), Some(&&3));
930 /// assert_eq!(iter.next(), Some(&3));
932 /// // after the iterator is finished, so is peek()
933 /// assert_eq!(iter.peek(), None);
934 /// assert_eq!(iter.next(), None);
937 #[stable(feature = "rust1", since = "1.0.0")]
938 fn peekable(self) -> Peekable<Self> where Self: Sized {
939 Peekable{iter: self, peeked: None}
942 /// Creates an iterator that [`skip()`]s elements based on a predicate.
944 /// [`skip()`]: #method.skip
946 /// `skip_while()` takes a closure as an argument. It will call this
947 /// closure on each element of the iterator, and ignore elements
948 /// until it returns `false`.
950 /// After `false` is returned, `skip_while()`'s job is over, and the
951 /// rest of the elements are yielded.
958 /// let a = [-1i32, 0, 1];
960 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
962 /// assert_eq!(iter.next(), Some(&0));
963 /// assert_eq!(iter.next(), Some(&1));
964 /// assert_eq!(iter.next(), None);
967 /// Because the closure passed to `skip_while()` takes a reference, and many
968 /// iterators iterate over references, this leads to a possibly confusing
969 /// situation, where the type of the closure is a double reference:
972 /// let a = [-1, 0, 1];
974 /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
976 /// assert_eq!(iter.next(), Some(&0));
977 /// assert_eq!(iter.next(), Some(&1));
978 /// assert_eq!(iter.next(), None);
981 /// Stopping after an initial `false`:
984 /// let a = [-1, 0, 1, -2];
986 /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
988 /// assert_eq!(iter.next(), Some(&0));
989 /// assert_eq!(iter.next(), Some(&1));
991 /// // while this would have been false, since we already got a false,
992 /// // skip_while() isn't used any more
993 /// assert_eq!(iter.next(), Some(&-2));
995 /// assert_eq!(iter.next(), None);
998 #[stable(feature = "rust1", since = "1.0.0")]
999 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
1000 Self: Sized, P: FnMut(&Self::Item) -> bool,
1002 SkipWhile{iter: self, flag: false, predicate: predicate}
1005 /// Creates an iterator that yields elements based on a predicate.
1007 /// `take_while()` takes a closure as an argument. It will call this
1008 /// closure on each element of the iterator, and yield elements
1009 /// while it returns `true`.
1011 /// After `false` is returned, `take_while()`'s job is over, and the
1012 /// rest of the elements are ignored.
1019 /// let a = [-1i32, 0, 1];
1021 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1023 /// assert_eq!(iter.next(), Some(&-1));
1024 /// assert_eq!(iter.next(), None);
1027 /// Because the closure passed to `take_while()` takes a reference, and many
1028 /// iterators iterate over references, this leads to a possibly confusing
1029 /// situation, where the type of the closure is a double reference:
1032 /// let a = [-1, 0, 1];
1034 /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
1036 /// assert_eq!(iter.next(), Some(&-1));
1037 /// assert_eq!(iter.next(), None);
1040 /// Stopping after an initial `false`:
1043 /// let a = [-1, 0, 1, -2];
1045 /// let mut iter = a.into_iter().take_while(|x| **x < 0);
1047 /// assert_eq!(iter.next(), Some(&-1));
1049 /// // We have more elements that are less than zero, but since we already
1050 /// // got a false, take_while() isn't used any more
1051 /// assert_eq!(iter.next(), None);
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
1056 Self: Sized, P: FnMut(&Self::Item) -> bool,
1058 TakeWhile{iter: self, flag: false, predicate: predicate}
1061 /// Creates an iterator that skips the first `n` elements.
1063 /// After they have been consumed, the rest of the elements are yielded.
1070 /// let a = [1, 2, 3];
1072 /// let mut iter = a.iter().skip(2);
1074 /// assert_eq!(iter.next(), Some(&3));
1075 /// assert_eq!(iter.next(), None);
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
1080 Skip{iter: self, n: n}
1083 /// Creates an iterator that yields its first `n` elements.
1090 /// let a = [1, 2, 3];
1092 /// let mut iter = a.iter().take(2);
1094 /// assert_eq!(iter.next(), Some(&1));
1095 /// assert_eq!(iter.next(), Some(&2));
1096 /// assert_eq!(iter.next(), None);
1099 /// `take()` is often used with an infinite iterator, to make it finite:
1102 /// let mut iter = (0..).take(3);
1104 /// assert_eq!(iter.next(), Some(0));
1105 /// assert_eq!(iter.next(), Some(1));
1106 /// assert_eq!(iter.next(), Some(2));
1107 /// assert_eq!(iter.next(), None);
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 fn take(self, n: usize) -> Take<Self> where Self: Sized, {
1112 Take{iter: self, n: n}
1115 /// An iterator adaptor similar to [`fold()`] that holds internal state and
1116 /// produces a new iterator.
1118 /// [`fold()`]: #method.fold
1120 /// `scan()` takes two arguments: an initial value which seeds the internal
1121 /// state, and a closure with two arguments, the first being a mutable
1122 /// reference to the internal state and the second an iterator element.
1123 /// The closure can assign to the internal state to share state between
1126 /// On iteration, the closure will be applied to each element of the
1127 /// iterator and the return value from the closure, an [`Option`], is
1128 /// yielded by the iterator.
1130 /// [`Option`]: ../option/enum.Option.html
1137 /// let a = [1, 2, 3];
1139 /// let mut iter = a.iter().scan(1, |state, &x| {
1140 /// // each iteration, we'll multiply the state by the element
1141 /// *state = *state * x;
1143 /// // the value passed on to the next iteration
1147 /// assert_eq!(iter.next(), Some(1));
1148 /// assert_eq!(iter.next(), Some(2));
1149 /// assert_eq!(iter.next(), Some(6));
1150 /// assert_eq!(iter.next(), None);
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1155 where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
1157 Scan{iter: self, f: f, state: initial_state}
1160 /// Creates an iterator that works like map, but flattens nested structure.
1162 /// The [`map()`] adapter is very useful, but only when the closure
1163 /// argument produces values. If it produces an iterator instead, there's
1164 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1167 /// [`map()`]: #method.map
1169 /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
1170 /// one item for each element, and `flat_map()`'s closure returns an
1171 /// iterator for each element.
1178 /// let words = ["alpha", "beta", "gamma"];
1180 /// // chars() returns an iterator
1181 /// let merged: String = words.iter()
1182 /// .flat_map(|s| s.chars())
1184 /// assert_eq!(merged, "alphabetagamma");
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1189 where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
1191 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
1194 /// Creates an iterator which ends after the first `None`.
1196 /// After an iterator returns `None`, future calls may or may not yield
1197 /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
1198 /// `None` is given, it will always return `None` forever.
1205 /// // an iterator which alternates between Some and None
1206 /// struct Alternate {
1210 /// impl Iterator for Alternate {
1211 /// type Item = i32;
1213 /// fn next(&mut self) -> Option<i32> {
1214 /// let val = self.state;
1215 /// self.state = self.state + 1;
1217 /// // if it's even, Some(i32), else None
1218 /// if val % 2 == 0 {
1226 /// let mut iter = Alternate { state: 0 };
1228 /// // we can see our iterator going back and forth
1229 /// assert_eq!(iter.next(), Some(0));
1230 /// assert_eq!(iter.next(), None);
1231 /// assert_eq!(iter.next(), Some(2));
1232 /// assert_eq!(iter.next(), None);
1234 /// // however, once we fuse it...
1235 /// let mut iter = iter.fuse();
1237 /// assert_eq!(iter.next(), Some(4));
1238 /// assert_eq!(iter.next(), None);
1240 /// // it will always return None after the first time.
1241 /// assert_eq!(iter.next(), None);
1242 /// assert_eq!(iter.next(), None);
1243 /// assert_eq!(iter.next(), None);
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 fn fuse(self) -> Fuse<Self> where Self: Sized {
1248 Fuse{iter: self, done: false}
1251 /// Do something with each element of an iterator, passing the value on.
1253 /// When using iterators, you'll often chain several of them together.
1254 /// While working on such code, you might want to check out what's
1255 /// happening at various parts in the pipeline. To do that, insert
1256 /// a call to `inspect()`.
1258 /// It's much more common for `inspect()` to be used as a debugging tool
1259 /// than to exist in your final code, but never say never.
1266 /// let a = [1, 4, 2, 3];
1268 /// // this iterator sequence is complex.
1269 /// let sum = a.iter()
1271 /// .filter(|&x| x % 2 == 0)
1272 /// .fold(0, |sum, i| sum + i);
1274 /// println!("{}", sum);
1276 /// // let's add some inspect() calls to investigate what's happening
1277 /// let sum = a.iter()
1279 /// .inspect(|x| println!("about to filter: {}", x))
1280 /// .filter(|&x| x % 2 == 0)
1281 /// .inspect(|x| println!("made it through filter: {}", x))
1282 /// .fold(0, |sum, i| sum + i);
1284 /// println!("{}", sum);
1287 /// This will print:
1290 /// about to filter: 1
1291 /// about to filter: 4
1292 /// made it through filter: 4
1293 /// about to filter: 2
1294 /// made it through filter: 2
1295 /// about to filter: 3
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 fn inspect<F>(self, f: F) -> Inspect<Self, F> where
1301 Self: Sized, F: FnMut(&Self::Item),
1303 Inspect{iter: self, f: f}
1306 /// Borrows an iterator, rather than consuming it.
1308 /// This is useful to allow applying iterator adaptors while still
1309 /// retaining ownership of the original iterator.
1316 /// let a = [1, 2, 3];
1318 /// let iter = a.into_iter();
1320 /// let sum: i32 = iter.take(5)
1321 /// .fold(0, |acc, &i| acc + i );
1323 /// assert_eq!(sum, 6);
1325 /// // if we try to use iter again, it won't work. The following line
1326 /// // gives "error: use of moved value: `iter`
1327 /// // assert_eq!(iter.next(), None);
1329 /// // let's try that again
1330 /// let a = [1, 2, 3];
1332 /// let mut iter = a.into_iter();
1334 /// // instead, we add in a .by_ref()
1335 /// let sum: i32 = iter.by_ref()
1337 /// .fold(0, |acc, &i| acc + i );
1339 /// assert_eq!(sum, 3);
1341 /// // now this is just fine:
1342 /// assert_eq!(iter.next(), Some(&3));
1343 /// assert_eq!(iter.next(), None);
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
1348 /// Transforms an iterator into a collection.
1350 /// `collect()` can take anything iterable, and turn it into a relevant
1351 /// collection. This is one of the more powerful methods in the standard
1352 /// library, used in a variety of contexts.
1354 /// The most basic pattern in which `collect()` is used is to turn one
1355 /// collection into another. You take a collection, call `iter()` on it,
1356 /// do a bunch of transformations, and then `collect()` at the end.
1358 /// One of the keys to `collect()`'s power is that many things you might
1359 /// not think of as 'collections' actually are. For example, a [`String`]
1360 /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
1361 /// be thought of as single `Result<Collection<T>, E>`. See the examples
1364 /// [`String`]: ../string/struct.String.html
1365 /// [`Result<T, E>`]: ../result/enum.Result.html
1366 /// [`char`]: ../primitive.char.html
1368 /// Because `collect()` is so general, it can cause problems with type
1369 /// inference. As such, `collect()` is one of the few times you'll see
1370 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1371 /// helps the inference algorithm understand specifically which collection
1372 /// you're trying to collect into.
1379 /// let a = [1, 2, 3];
1381 /// let doubled: Vec<i32> = a.iter()
1382 /// .map(|&x| x * 2)
1385 /// assert_eq!(vec![2, 4, 6], doubled);
1388 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1389 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1391 /// [`VecDeque<T>`]: ../collections/struct.VecDeque.html
1394 /// use std::collections::VecDeque;
1396 /// let a = [1, 2, 3];
1398 /// let doubled: VecDeque<i32> = a.iter()
1399 /// .map(|&x| x * 2)
1402 /// assert_eq!(2, doubled[0]);
1403 /// assert_eq!(4, doubled[1]);
1404 /// assert_eq!(6, doubled[2]);
1407 /// Using the 'turbofish' instead of annotationg `doubled`:
1410 /// let a = [1, 2, 3];
1412 /// let doubled = a.iter()
1413 /// .map(|&x| x * 2)
1414 /// .collect::<Vec<i32>>();
1416 /// assert_eq!(vec![2, 4, 6], doubled);
1419 /// Because `collect()` cares about what you're collecting into, you can
1420 /// still use a partial type hint, `_`, with the turbofish:
1423 /// let a = [1, 2, 3];
1425 /// let doubled = a.iter()
1426 /// .map(|&x| x * 2)
1427 /// .collect::<Vec<_>>();
1429 /// assert_eq!(vec![2, 4, 6], doubled);
1432 /// Using `collect()` to make a [`String`]:
1435 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1437 /// let hello: String = chars.iter()
1438 /// .map(|&x| x as u8)
1439 /// .map(|x| (x + 1) as char)
1442 /// assert_eq!("hello", hello);
1445 /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
1446 /// see if any of them failed:
1449 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
1451 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1453 /// // gives us the first error
1454 /// assert_eq!(Err("nope"), result);
1456 /// let results = [Ok(1), Ok(3)];
1458 /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
1460 /// // gives us the list of answers
1461 /// assert_eq!(Ok(vec![1, 3]), result);
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
1466 FromIterator::from_iter(self)
1469 /// Consumes an iterator, creating two collections from it.
1471 /// The predicate passed to `partition()` can return `true`, or `false`.
1472 /// `partition()` returns a pair, all of the elements for which it returned
1473 /// `true`, and all of the elements for which it returned `false`.
1480 /// let a = [1, 2, 3];
1482 /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
1483 /// .partition(|&n| n % 2 == 0);
1485 /// assert_eq!(even, vec![2]);
1486 /// assert_eq!(odd, vec![1, 3]);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 fn partition<B, F>(self, mut f: F) -> (B, B) where
1491 B: Default + Extend<Self::Item>,
1492 F: FnMut(&Self::Item) -> bool
1494 let mut left: B = Default::default();
1495 let mut right: B = Default::default();
1499 left.extend(Some(x))
1501 right.extend(Some(x))
1508 /// An iterator adaptor that applies a function, producing a single, final value.
1510 /// `fold()` takes two arguments: an initial value, and a closure with two
1511 /// arguments: an 'accumulator', and an element. It returns the value that
1512 /// the accumulator should have for the next iteration.
1514 /// The initial value is the value the accumulator will have on the first
1517 /// After applying this closure to every element of the iterator, `fold()`
1518 /// returns the accumulator.
1520 /// This operation is sometimes called 'reduce' or 'inject'.
1522 /// Folding is useful whenever you have a collection of something, and want
1523 /// to produce a single value from it.
1530 /// let a = [1, 2, 3];
1532 /// // the sum of all of the elements of a
1533 /// let sum = a.iter()
1534 /// .fold(0, |acc, &x| acc + x);
1536 /// assert_eq!(sum, 6);
1539 /// Let's walk through each step of the iteration here:
1541 /// | element | acc | x | result |
1542 /// |---------|-----|---|--------|
1544 /// | 1 | 0 | 1 | 1 |
1545 /// | 2 | 1 | 2 | 3 |
1546 /// | 3 | 3 | 3 | 6 |
1548 /// And so, our final result, `6`.
1550 /// It's common for people who haven't used iterators a lot to
1551 /// use a `for` loop with a list of things to build up a result. Those
1552 /// can be turned into `fold()`s:
1555 /// let numbers = [1, 2, 3, 4, 5];
1557 /// let mut result = 0;
1560 /// for i in &numbers {
1561 /// result = result + i;
1565 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
1567 /// // they're the same
1568 /// assert_eq!(result, result2);
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 fn fold<B, F>(self, init: B, mut f: F) -> B where
1573 Self: Sized, F: FnMut(B, Self::Item) -> B,
1575 let mut accum = init;
1577 accum = f(accum, x);
1582 /// Tests if every element of the iterator matches a predicate.
1584 /// `all()` takes a closure that returns `true` or `false`. It applies
1585 /// this closure to each element of the iterator, and if they all return
1586 /// `true`, then so does `all()`. If any of them return `false`, it
1587 /// returns `false`.
1589 /// `all()` is short-circuting; in other words, it will stop processing
1590 /// as soon as it finds a `false`, given that no matter what else happens,
1591 /// the result will also be `false`.
1593 /// An empty iterator returns `true`.
1600 /// let a = [1, 2, 3];
1602 /// assert!(a.iter().all(|&x| x > 0));
1604 /// assert!(!a.iter().all(|&x| x > 2));
1607 /// Stopping at the first `false`:
1610 /// let a = [1, 2, 3];
1612 /// let mut iter = a.iter();
1614 /// assert!(!iter.all(|&x| x != 2));
1616 /// // we can still use `iter`, as there are more elements.
1617 /// assert_eq!(iter.next(), Some(&3));
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 fn all<F>(&mut self, mut f: F) -> bool where
1622 Self: Sized, F: FnMut(Self::Item) -> bool
1632 /// Tests if any element of the iterator matches a predicate.
1634 /// `any()` takes a closure that returns `true` or `false`. It applies
1635 /// this closure to each element of the iterator, and if any of them return
1636 /// `true`, then so does `any()`. If they all return `false`, it
1637 /// returns `false`.
1639 /// `any()` is short-circuting; in other words, it will stop processing
1640 /// as soon as it finds a `true`, given that no matter what else happens,
1641 /// the result will also be `true`.
1643 /// An empty iterator returns `false`.
1650 /// let a = [1, 2, 3];
1652 /// assert!(a.iter().any(|&x| x > 0));
1654 /// assert!(!a.iter().any(|&x| x > 5));
1657 /// Stopping at the first `true`:
1660 /// let a = [1, 2, 3];
1662 /// let mut iter = a.iter();
1664 /// assert!(iter.any(|&x| x != 2));
1666 /// // we can still use `iter`, as there are more elements.
1667 /// assert_eq!(iter.next(), Some(&2));
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 fn any<F>(&mut self, mut f: F) -> bool where
1673 F: FnMut(Self::Item) -> bool
1683 /// Searches for an element of an iterator that satisfies a predicate.
1685 /// `find()` takes a closure that returns `true` or `false`. It applies
1686 /// this closure to each element of the iterator, and if any of them return
1687 /// `true`, then `find()` returns `Some(element)`. If they all return
1688 /// `false`, it returns `None`.
1690 /// `find()` is short-circuting; in other words, it will stop processing
1691 /// as soon as the closure returns `true`.
1693 /// Because `find()` takes a reference, and many iterators iterate over
1694 /// references, this leads to a possibly confusing situation where the
1695 /// argument is a double reference. You can see this effect in the
1696 /// examples below, with `&&x`.
1703 /// let a = [1, 2, 3];
1705 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
1707 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
1710 /// Stopping at the first `true`:
1713 /// let a = [1, 2, 3];
1715 /// let mut iter = a.iter();
1717 /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
1719 /// // we can still use `iter`, as there are more elements.
1720 /// assert_eq!(iter.next(), Some(&3));
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
1726 P: FnMut(&Self::Item) -> bool,
1729 if predicate(&x) { return Some(x) }
1734 /// Searches for an element in an iterator, returning its index.
1736 /// `position()` takes a closure that returns `true` or `false`. It applies
1737 /// this closure to each element of the iterator, and if one of them
1738 /// returns `true`, then `position()` returns `Some(index)`. If all of
1739 /// them return `false`, it returns `None`.
1741 /// `position()` is short-circuting; in other words, it will stop
1742 /// processing as soon as it finds a `true`.
1744 /// # Overflow Behavior
1746 /// The method does no guarding against overflows, so if there are more
1747 /// than `usize::MAX` non-matching elements, it either produces the wrong
1748 /// result or panics. If debug assertions are enabled, a panic is
1753 /// This function might panic if the iterator has more than `usize::MAX`
1754 /// non-matching elements.
1761 /// let a = [1, 2, 3];
1763 /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
1765 /// assert_eq!(a.iter().position(|&x| x == 5), None);
1768 /// Stopping at the first `true`:
1771 /// let a = [1, 2, 3];
1773 /// let mut iter = a.iter();
1775 /// assert_eq!(iter.position(|&x| x == 2), Some(1));
1777 /// // we can still use `iter`, as there are more elements.
1778 /// assert_eq!(iter.next(), Some(&3));
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
1784 P: FnMut(Self::Item) -> bool,
1786 // `enumerate` might overflow.
1787 for (i, x) in self.enumerate() {
1795 /// Searches for an element in an iterator from the right, returning its
1798 /// `rposition()` takes a closure that returns `true` or `false`. It applies
1799 /// this closure to each element of the iterator, starting from the end,
1800 /// and if one of them returns `true`, then `rposition()` returns
1801 /// `Some(index)`. If all of them return `false`, it returns `None`.
1803 /// `rposition()` is short-circuting; in other words, it will stop
1804 /// processing as soon as it finds a `true`.
1811 /// let a = [1, 2, 3];
1813 /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
1815 /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
1818 /// Stopping at the first `true`:
1821 /// let a = [1, 2, 3];
1823 /// let mut iter = a.iter();
1825 /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
1827 /// // we can still use `iter`, as there are more elements.
1828 /// assert_eq!(iter.next(), Some(&1));
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
1833 P: FnMut(Self::Item) -> bool,
1834 Self: Sized + ExactSizeIterator + DoubleEndedIterator
1836 let mut i = self.len();
1838 while let Some(v) = self.next_back() {
1842 // No need for an overflow check here, because `ExactSizeIterator`
1843 // implies that the number of elements fits into a `usize`.
1849 /// Returns the maximum element of an iterator.
1851 /// If the two elements are equally maximum, the latest element is
1859 /// let a = [1, 2, 3];
1861 /// assert_eq!(a.iter().max(), Some(&3));
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1869 // switch to y even if it is only equal, to preserve
1871 |_, x, _, y| *x <= *y)
1875 /// Returns the minimum element of an iterator.
1877 /// If the two elements are equally minimum, the first element is
1885 /// let a = [1, 2, 3];
1887 /// assert_eq!(a.iter().min(), Some(&1));
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
1895 // only switch to y if it is strictly smaller, to
1896 // preserve stability.
1897 |_, x, _, y| *x > *y)
1901 #[allow(missing_docs)]
1903 #[unstable(feature = "iter_cmp",
1904 reason = "may want to produce an Ordering directly; see #15311",
1906 #[rustc_deprecated(reason = "renamed to max_by_key", since = "1.6.0")]
1907 fn max_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1909 F: FnMut(&Self::Item) -> B,
1914 /// Returns the element that gives the maximum value from the
1915 /// specified function.
1917 /// Returns the rightmost element if the comparison determines two elements
1918 /// to be equally maximum.
1923 /// let a = [-3_i32, 0, 1, 5, -10];
1924 /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
1927 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1928 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1929 where Self: Sized, F: FnMut(&Self::Item) -> B,
1933 // switch to y even if it is only equal, to preserve
1935 |x_p, _, y_p, _| x_p <= y_p)
1940 #[allow(missing_docs)]
1941 #[unstable(feature = "iter_cmp",
1942 reason = "may want to produce an Ordering directly; see #15311",
1944 #[rustc_deprecated(reason = "renamed to min_by_key", since = "1.6.0")]
1945 fn min_by<B: Ord, F>(self, f: F) -> Option<Self::Item> where
1947 F: FnMut(&Self::Item) -> B,
1952 /// Returns the element that gives the minimum value from the
1953 /// specified function.
1955 /// Returns the latest element if the comparison determines two elements
1956 /// to be equally minimum.
1961 /// let a = [-3_i32, 0, 1, 5, -10];
1962 /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
1964 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
1965 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
1966 where Self: Sized, F: FnMut(&Self::Item) -> B,
1970 // only switch to y if it is strictly smaller, to
1971 // preserve stability.
1972 |x_p, _, y_p, _| x_p > y_p)
1976 /// Reverses an iterator's direction.
1978 /// Usually, iterators iterate from left to right. After using `rev()`,
1979 /// an iterator will instead iterate from right to left.
1981 /// This is only possible if the iterator has an end, so `rev()` only
1982 /// works on [`DoubleEndedIterator`]s.
1984 /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
1989 /// let a = [1, 2, 3];
1991 /// let mut iter = a.iter().rev();
1993 /// assert_eq!(iter.next(), Some(&3));
1994 /// assert_eq!(iter.next(), Some(&2));
1995 /// assert_eq!(iter.next(), Some(&1));
1997 /// assert_eq!(iter.next(), None);
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
2005 /// Converts an iterator of pairs into a pair of containers.
2007 /// `unzip()` consumes an entire iterator of pairs, producing two
2008 /// collections: one from the left elements of the pairs, and one
2009 /// from the right elements.
2011 /// This function is, in some sense, the opposite of [`zip()`].
2013 /// [`zip()`]: #method.zip
2020 /// let a = [(1, 2), (3, 4)];
2022 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
2024 /// assert_eq!(left, [1, 3]);
2025 /// assert_eq!(right, [2, 4]);
2027 #[stable(feature = "rust1", since = "1.0.0")]
2028 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
2029 FromA: Default + Extend<A>,
2030 FromB: Default + Extend<B>,
2031 Self: Sized + Iterator<Item=(A, B)>,
2033 struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
2034 impl<A> Iterator for SizeHint<A> {
2037 fn next(&mut self) -> Option<A> { None }
2038 fn size_hint(&self) -> (usize, Option<usize>) {
2043 let (lo, hi) = self.size_hint();
2044 let mut ts: FromA = Default::default();
2045 let mut us: FromB = Default::default();
2047 ts.extend(SizeHint(lo, hi, marker::PhantomData));
2048 us.extend(SizeHint(lo, hi, marker::PhantomData));
2050 for (t, u) in self {
2058 /// Creates an iterator which clone()s all of its elements.
2060 /// This is useful when you have an iterator over `&T`, but you need an
2061 /// iterator over `T`.
2068 /// let a = [1, 2, 3];
2070 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
2072 /// // cloned is the same as .map(|&x| x), for integers
2073 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
2075 /// assert_eq!(v_cloned, vec![1, 2, 3]);
2076 /// assert_eq!(v_map, vec![1, 2, 3]);
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
2080 where Self: Sized + Iterator<Item=&'a T>, T: Clone
2085 /// Repeats an iterator endlessly.
2087 /// Instead of stopping at `None`, the iterator will instead start again,
2088 /// from the beginning. After iterating again, it will start at the
2089 /// beginning again. And again. And again. Forever.
2096 /// let a = [1, 2, 3];
2098 /// let mut it = a.iter().cycle();
2100 /// assert_eq!(it.next(), Some(&1));
2101 /// assert_eq!(it.next(), Some(&2));
2102 /// assert_eq!(it.next(), Some(&3));
2103 /// assert_eq!(it.next(), Some(&1));
2104 /// assert_eq!(it.next(), Some(&2));
2105 /// assert_eq!(it.next(), Some(&3));
2106 /// assert_eq!(it.next(), Some(&1));
2108 #[stable(feature = "rust1", since = "1.0.0")]
2110 fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
2111 Cycle{orig: self.clone(), iter: self}
2114 /// Sums the elements of an iterator.
2116 /// Takes each element, adds them together, and returns the result.
2118 /// An empty iterator returns the zero value of the type.
2125 /// #![feature(iter_arith)]
2127 /// let a = [1, 2, 3];
2128 /// let sum: i32 = a.iter().sum();
2130 /// assert_eq!(sum, 6);
2132 #[unstable(feature = "iter_arith", reason = "bounds recently changed",
2134 fn sum<S>(self) -> S where
2135 S: Add<Self::Item, Output=S> + Zero,
2138 self.fold(Zero::zero(), |s, e| s + e)
2141 /// Iterates over the entire iterator, multiplying all the elements
2143 /// An empty iterator returns the one value of the type.
2148 /// #![feature(iter_arith)]
2150 /// fn factorial(n: u32) -> u32 {
2151 /// (1..).take_while(|&i| i <= n).product()
2153 /// assert_eq!(factorial(0), 1);
2154 /// assert_eq!(factorial(1), 1);
2155 /// assert_eq!(factorial(5), 120);
2157 #[unstable(feature="iter_arith", reason = "bounds recently changed",
2159 fn product<P>(self) -> P where
2160 P: Mul<Self::Item, Output=P> + One,
2163 self.fold(One::one(), |p, e| p * e)
2166 /// Lexicographically compares the elements of this `Iterator` with those
2168 #[stable(feature = "iter_order", since = "1.5.0")]
2169 fn cmp<I>(mut self, other: I) -> Ordering where
2170 I: IntoIterator<Item = Self::Item>,
2174 let mut other = other.into_iter();
2177 match (self.next(), other.next()) {
2178 (None, None) => return Ordering::Equal,
2179 (None, _ ) => return Ordering::Less,
2180 (_ , None) => return Ordering::Greater,
2181 (Some(x), Some(y)) => match x.cmp(&y) {
2182 Ordering::Equal => (),
2183 non_eq => return non_eq,
2189 /// Lexicographically compares the elements of this `Iterator` with those
2191 #[stable(feature = "iter_order", since = "1.5.0")]
2192 fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
2194 Self::Item: PartialOrd<I::Item>,
2197 let mut other = other.into_iter();
2200 match (self.next(), other.next()) {
2201 (None, None) => return Some(Ordering::Equal),
2202 (None, _ ) => return Some(Ordering::Less),
2203 (_ , None) => return Some(Ordering::Greater),
2204 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2205 Some(Ordering::Equal) => (),
2206 non_eq => return non_eq,
2212 /// Determines if the elements of this `Iterator` are equal to those of
2214 #[stable(feature = "iter_order", since = "1.5.0")]
2215 fn eq<I>(mut self, other: I) -> bool where
2217 Self::Item: PartialEq<I::Item>,
2220 let mut other = other.into_iter();
2223 match (self.next(), other.next()) {
2224 (None, None) => return true,
2225 (None, _) | (_, None) => return false,
2226 (Some(x), Some(y)) => if x != y { return false },
2231 /// Determines if the elements of this `Iterator` are unequal to those of
2233 #[stable(feature = "iter_order", since = "1.5.0")]
2234 fn ne<I>(mut self, other: I) -> bool where
2236 Self::Item: PartialEq<I::Item>,
2239 let mut other = other.into_iter();
2242 match (self.next(), other.next()) {
2243 (None, None) => return false,
2244 (None, _) | (_, None) => return true,
2245 (Some(x), Some(y)) => if x.ne(&y) { return true },
2250 /// Determines if the elements of this `Iterator` are lexicographically
2251 /// less than those of another.
2252 #[stable(feature = "iter_order", since = "1.5.0")]
2253 fn lt<I>(mut self, other: I) -> bool where
2255 Self::Item: PartialOrd<I::Item>,
2258 let mut other = other.into_iter();
2261 match (self.next(), other.next()) {
2262 (None, None) => return false,
2263 (None, _ ) => return true,
2264 (_ , None) => return false,
2265 (Some(x), Some(y)) => {
2266 match x.partial_cmp(&y) {
2267 Some(Ordering::Less) => return true,
2268 Some(Ordering::Equal) => {}
2269 Some(Ordering::Greater) => return false,
2270 None => return false,
2277 /// Determines if the elements of this `Iterator` are lexicographically
2278 /// less or equal to those of another.
2279 #[stable(feature = "iter_order", since = "1.5.0")]
2280 fn le<I>(mut self, other: I) -> bool where
2282 Self::Item: PartialOrd<I::Item>,
2285 let mut other = other.into_iter();
2288 match (self.next(), other.next()) {
2289 (None, None) => return true,
2290 (None, _ ) => return true,
2291 (_ , None) => return false,
2292 (Some(x), Some(y)) => {
2293 match x.partial_cmp(&y) {
2294 Some(Ordering::Less) => return true,
2295 Some(Ordering::Equal) => {}
2296 Some(Ordering::Greater) => return false,
2297 None => return false,
2304 /// Determines if the elements of this `Iterator` are lexicographically
2305 /// greater than those of another.
2306 #[stable(feature = "iter_order", since = "1.5.0")]
2307 fn gt<I>(mut self, other: I) -> bool where
2309 Self::Item: PartialOrd<I::Item>,
2312 let mut other = other.into_iter();
2315 match (self.next(), other.next()) {
2316 (None, None) => return false,
2317 (None, _ ) => return false,
2318 (_ , None) => return true,
2319 (Some(x), Some(y)) => {
2320 match x.partial_cmp(&y) {
2321 Some(Ordering::Less) => return false,
2322 Some(Ordering::Equal) => {}
2323 Some(Ordering::Greater) => return true,
2324 None => return false,
2331 /// Determines if the elements of this `Iterator` are lexicographically
2332 /// greater than or equal to those of another.
2333 #[stable(feature = "iter_order", since = "1.5.0")]
2334 fn ge<I>(mut self, other: I) -> bool where
2336 Self::Item: PartialOrd<I::Item>,
2339 let mut other = other.into_iter();
2342 match (self.next(), other.next()) {
2343 (None, None) => return true,
2344 (None, _ ) => return false,
2345 (_ , None) => return true,
2346 (Some(x), Some(y)) => {
2347 match x.partial_cmp(&y) {
2348 Some(Ordering::Less) => return false,
2349 Some(Ordering::Equal) => {}
2350 Some(Ordering::Greater) => return true,
2351 None => return false,
2359 /// Select an element from an iterator based on the given projection
2360 /// and "comparison" function.
2362 /// This is an idiosyncratic helper to try to factor out the
2363 /// commonalities of {max,min}{,_by}. In particular, this avoids
2364 /// having to implement optimizations several times.
2366 fn select_fold1<I,B, FProj, FCmp>(mut it: I,
2368 mut f_cmp: FCmp) -> Option<(B, I::Item)>
2370 FProj: FnMut(&I::Item) -> B,
2371 FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
2373 // start with the first element as our selection. This avoids
2374 // having to use `Option`s inside the loop, translating to a
2375 // sizeable performance gain (6x in one case).
2376 it.next().map(|mut sel| {
2377 let mut sel_p = f_proj(&sel);
2380 let x_p = f_proj(&x);
2381 if f_cmp(&sel_p, &sel, &x_p, &x) {
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
2392 type Item = I::Item;
2393 fn next(&mut self) -> Option<I::Item> { (**self).next() }
2394 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
2397 /// Conversion from an `Iterator`.
2399 /// By implementing `FromIterator` for a type, you define how it will be
2400 /// created from an iterator. This is common for types which describe a
2401 /// collection of some kind.
2403 /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead
2404 /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s
2405 /// documentation for more examples.
2407 /// [`from_iter()`]: #tymethod.from_iter
2408 /// [`Iterator`]: trait.Iterator.html
2409 /// [`collect()`]: trait.Iterator.html#method.collect
2411 /// See also: [`IntoIterator`].
2413 /// [`IntoIterator`]: trait.IntoIterator.html
2420 /// use std::iter::FromIterator;
2422 /// let five_fives = std::iter::repeat(5).take(5);
2424 /// let v = Vec::from_iter(five_fives);
2426 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2429 /// Using [`collect()`] to implicitly use `FromIterator`:
2432 /// let five_fives = std::iter::repeat(5).take(5);
2434 /// let v: Vec<i32> = five_fives.collect();
2436 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2439 /// Implementing `FromIterator` for your type:
2442 /// use std::iter::FromIterator;
2444 /// // A sample collection, that's just a wrapper over Vec<T>
2445 /// #[derive(Debug)]
2446 /// struct MyCollection(Vec<i32>);
2448 /// // Let's give it some methods so we can create one and add things
2450 /// impl MyCollection {
2451 /// fn new() -> MyCollection {
2452 /// MyCollection(Vec::new())
2455 /// fn add(&mut self, elem: i32) {
2456 /// self.0.push(elem);
2460 /// // and we'll implement FromIterator
2461 /// impl FromIterator<i32> for MyCollection {
2462 /// fn from_iter<I: IntoIterator<Item=i32>>(iterator: I) -> Self {
2463 /// let mut c = MyCollection::new();
2465 /// for i in iterator {
2473 /// // Now we can make a new iterator...
2474 /// let iter = (0..5).into_iter();
2476 /// // ... and make a MyCollection out of it
2477 /// let c = MyCollection::from_iter(iter);
2479 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2481 /// // collect works too!
2483 /// let iter = (0..5).into_iter();
2484 /// let c: MyCollection = iter.collect();
2486 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
2490 built from an iterator over elements of type `{A}`"]
2491 pub trait FromIterator<A>: Sized {
2492 /// Creates a value from an iterator.
2494 /// See the [module-level documentation] for more.
2496 /// [module-level documentation]: trait.FromIterator.html
2503 /// use std::iter::FromIterator;
2505 /// let five_fives = std::iter::repeat(5).take(5);
2507 /// let v = Vec::from_iter(five_fives);
2509 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 fn from_iter<T: IntoIterator<Item=A>>(iterator: T) -> Self;
2515 /// Conversion into an `Iterator`.
2517 /// By implementing `IntoIterator` for a type, you define how it will be
2518 /// converted to an iterator. This is common for types which describe a
2519 /// collection of some kind.
2521 /// One benefit of implementing `IntoIterator` is that your type will [work
2522 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
2524 /// See also: [`FromIterator`].
2526 /// [`FromIterator`]: trait.FromIterator.html
2533 /// let v = vec![1, 2, 3];
2535 /// let mut iter = v.into_iter();
2537 /// let n = iter.next();
2538 /// assert_eq!(Some(1), n);
2540 /// let n = iter.next();
2541 /// assert_eq!(Some(2), n);
2543 /// let n = iter.next();
2544 /// assert_eq!(Some(3), n);
2546 /// let n = iter.next();
2547 /// assert_eq!(None, n);
2550 /// Implementing `IntoIterator` for your type:
2553 /// // A sample collection, that's just a wrapper over Vec<T>
2554 /// #[derive(Debug)]
2555 /// struct MyCollection(Vec<i32>);
2557 /// // Let's give it some methods so we can create one and add things
2559 /// impl MyCollection {
2560 /// fn new() -> MyCollection {
2561 /// MyCollection(Vec::new())
2564 /// fn add(&mut self, elem: i32) {
2565 /// self.0.push(elem);
2569 /// // and we'll implement IntoIterator
2570 /// impl IntoIterator for MyCollection {
2571 /// type Item = i32;
2572 /// type IntoIter = ::std::vec::IntoIter<i32>;
2574 /// fn into_iter(self) -> Self::IntoIter {
2575 /// self.0.into_iter()
2579 /// // Now we can make a new collection...
2580 /// let mut c = MyCollection::new();
2582 /// // ... add some stuff to it ...
2587 /// // ... and then turn it into an Iterator:
2588 /// for (i, n) in c.into_iter().enumerate() {
2589 /// assert_eq!(i as i32, n);
2592 #[stable(feature = "rust1", since = "1.0.0")]
2593 pub trait IntoIterator {
2594 /// The type of the elements being iterated over.
2595 #[stable(feature = "rust1", since = "1.0.0")]
2598 /// Which kind of iterator are we turning this into?
2599 #[stable(feature = "rust1", since = "1.0.0")]
2600 type IntoIter: Iterator<Item=Self::Item>;
2602 /// Creates an iterator from a value.
2604 /// See the [module-level documentation] for more.
2606 /// [module-level documentation]: trait.IntoIterator.html
2613 /// let v = vec![1, 2, 3];
2615 /// let mut iter = v.into_iter();
2617 /// let n = iter.next();
2618 /// assert_eq!(Some(1), n);
2620 /// let n = iter.next();
2621 /// assert_eq!(Some(2), n);
2623 /// let n = iter.next();
2624 /// assert_eq!(Some(3), n);
2626 /// let n = iter.next();
2627 /// assert_eq!(None, n);
2629 #[stable(feature = "rust1", since = "1.0.0")]
2630 fn into_iter(self) -> Self::IntoIter;
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl<I: Iterator> IntoIterator for I {
2635 type Item = I::Item;
2638 fn into_iter(self) -> I {
2643 /// Extend a collection with the contents of an iterator.
2645 /// Iterators produce a series of values, and collections can also be thought
2646 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
2647 /// to extend a collection by including the contents of that iterator.
2654 /// // You can extend a String with some chars:
2655 /// let mut message = String::from("The first three letters are: ");
2657 /// message.extend(&['a', 'b', 'c']);
2659 /// assert_eq!("abc", &message[29..32]);
2662 /// Implementing `Extend`:
2665 /// // A sample collection, that's just a wrapper over Vec<T>
2666 /// #[derive(Debug)]
2667 /// struct MyCollection(Vec<i32>);
2669 /// // Let's give it some methods so we can create one and add things
2671 /// impl MyCollection {
2672 /// fn new() -> MyCollection {
2673 /// MyCollection(Vec::new())
2676 /// fn add(&mut self, elem: i32) {
2677 /// self.0.push(elem);
2681 /// // since MyCollection has a list of i32s, we implement Extend for i32
2682 /// impl Extend<i32> for MyCollection {
2684 /// // This is a bit simpler with the concrete type signature: we can call
2685 /// // extend on anything which can be turned into an Iterator which gives
2686 /// // us i32s. Because we need i32s to put into MyCollection.
2687 /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iterable: T) {
2689 /// // The implementation is very straightforward: loop through the
2690 /// // iterator, and add() each element to ourselves.
2691 /// for elem in iterable {
2697 /// let mut c = MyCollection::new();
2703 /// // let's extend our collection with three more numbers
2704 /// c.extend(vec![1, 2, 3]);
2706 /// // we've added these elements onto the end
2707 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 pub trait Extend<A> {
2711 /// Extends a collection with the contents of an iterator.
2713 /// As this is the only method for this trait, the [trait-level] docs
2714 /// contain more details.
2716 /// [trait-level]: trait.Extend.html
2723 /// // You can extend a String with some chars:
2724 /// let mut message = String::from("abc");
2726 /// message.extend(['d', 'e', 'f'].iter());
2728 /// assert_eq!("abcdef", &message);
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
2734 /// An iterator able to yield elements from both ends.
2736 /// Something that implements `DoubleEndedIterator` has one extra capability
2737 /// over something that implements [`Iterator`]: the ability to also take
2738 /// `Item`s from the back, as well as the front.
2740 /// It is important to note that both back and forth work on the same range,
2741 /// and do not cross: iteration is over when they meet in the middle.
2743 /// In a similar fashion to the [`Iterator`] protocol, once a
2744 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
2745 /// may or may not ever return `Some` again. `next()` and `next_back()` are
2746 /// interchangable for this purpose.
2748 /// [`Iterator`]: trait.Iterator.html
2755 /// let numbers = vec![1, 2, 3];
2757 /// let mut iter = numbers.iter();
2759 /// assert_eq!(Some(&1), iter.next());
2760 /// assert_eq!(Some(&3), iter.next_back());
2761 /// assert_eq!(Some(&2), iter.next_back());
2762 /// assert_eq!(None, iter.next());
2763 /// assert_eq!(None, iter.next_back());
2765 #[stable(feature = "rust1", since = "1.0.0")]
2766 pub trait DoubleEndedIterator: Iterator {
2767 /// An iterator able to yield elements from both ends.
2769 /// As this is the only method for this trait, the [trait-level] docs
2770 /// contain more details.
2772 /// [trait-level]: trait.DoubleEndedIterator.html
2779 /// let numbers = vec![1, 2, 3];
2781 /// let mut iter = numbers.iter();
2783 /// assert_eq!(Some(&1), iter.next());
2784 /// assert_eq!(Some(&3), iter.next_back());
2785 /// assert_eq!(Some(&2), iter.next_back());
2786 /// assert_eq!(None, iter.next());
2787 /// assert_eq!(None, iter.next_back());
2789 #[stable(feature = "rust1", since = "1.0.0")]
2790 fn next_back(&mut self) -> Option<Self::Item>;
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
2795 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
2798 /// An iterator that knows its exact length.
2800 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
2801 /// If an iterator knows how many times it can iterate, providing access to
2802 /// that information can be useful. For example, if you want to iterate
2803 /// backwards, a good start is to know where the end is.
2805 /// When implementing an `ExactSizeIterator`, You must also implement
2806 /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must*
2807 /// return the exact size of the iterator.
2809 /// [`Iterator`]: trait.Iterator.html
2810 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2812 /// The [`len()`] method has a default implementation, so you usually shouldn't
2813 /// implement it. However, you may be able to provide a more performant
2814 /// implementation than the default, so overriding it in this case makes sense.
2816 /// [`len()`]: #method.len
2823 /// // a finite range knows exactly how many times it will iterate
2824 /// let five = 0..5;
2826 /// assert_eq!(5, five.len());
2829 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
2830 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
2832 /// [moddocs]: index.html
2835 /// # struct Counter {
2838 /// # impl Counter {
2839 /// # fn new() -> Counter {
2840 /// # Counter { count: 0 }
2843 /// # impl Iterator for Counter {
2844 /// # type Item = usize;
2845 /// # fn next(&mut self) -> Option<usize> {
2846 /// # self.count += 1;
2847 /// # if self.count < 6 {
2848 /// # Some(self.count)
2854 /// impl ExactSizeIterator for Counter {
2855 /// // We already have the number of iterations, so we can use it directly.
2856 /// fn len(&self) -> usize {
2861 /// // And now we can use it!
2863 /// let counter = Counter::new();
2865 /// assert_eq!(0, counter.len());
2867 #[stable(feature = "rust1", since = "1.0.0")]
2868 pub trait ExactSizeIterator: Iterator {
2870 #[stable(feature = "rust1", since = "1.0.0")]
2871 /// Returns the exact number of times the iterator will iterate.
2873 /// This method has a default implementation, so you usually should not
2874 /// implement it directly. However, if you can provide a more efficient
2875 /// implementation, you can do so. See the [trait-level] docs for an
2878 /// This function has the same safety guarantees as the [`size_hint()`]
2881 /// [trait-level]: trait.ExactSizeIterator.html
2882 /// [`size_hint()`]: trait.Iterator.html#method.size_hint
2889 /// // a finite range knows exactly how many times it will iterate
2890 /// let five = 0..5;
2892 /// assert_eq!(5, five.len());
2894 fn len(&self) -> usize {
2895 let (lower, upper) = self.size_hint();
2896 // Note: This assertion is overly defensive, but it checks the invariant
2897 // guaranteed by the trait. If this trait were rust-internal,
2898 // we could use debug_assert!; assert_eq! will check all Rust user
2899 // implementations too.
2900 assert_eq!(upper, Some(lower));
2905 #[stable(feature = "rust1", since = "1.0.0")]
2906 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
2908 // All adaptors that preserve the size of the wrapped iterator are fine
2909 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
2910 #[stable(feature = "rust1", since = "1.0.0")]
2911 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
2912 #[stable(feature = "rust1", since = "1.0.0")]
2913 impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
2916 #[stable(feature = "rust1", since = "1.0.0")]
2917 impl<I> ExactSizeIterator for Rev<I>
2918 where I: ExactSizeIterator + DoubleEndedIterator {}
2919 #[stable(feature = "rust1", since = "1.0.0")]
2920 impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
2921 F: FnMut(I::Item) -> B,
2923 #[stable(feature = "rust1", since = "1.0.0")]
2924 impl<A, B> ExactSizeIterator for Zip<A, B>
2925 where A: ExactSizeIterator, B: ExactSizeIterator {}
2927 /// An double-ended iterator with the direction inverted.
2929 /// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
2930 /// documentation for more.
2932 /// [`rev()`]: trait.Iterator.html#method.rev
2933 /// [`Iterator`]: trait.Iterator.html
2935 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2936 #[stable(feature = "rust1", since = "1.0.0")]
2941 #[stable(feature = "rust1", since = "1.0.0")]
2942 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
2943 type Item = <I as Iterator>::Item;
2946 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
2948 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
2951 #[stable(feature = "rust1", since = "1.0.0")]
2952 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
2954 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
2957 /// An iterator that clones the elements of an underlying iterator.
2959 /// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
2960 /// documentation for more.
2962 /// [`cloned()`]: trait.Iterator.html#method.cloned
2963 /// [`Iterator`]: trait.Iterator.html
2964 #[stable(feature = "iter_cloned", since = "1.1.0")]
2965 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2967 pub struct Cloned<I> {
2971 #[stable(feature = "rust1", since = "1.0.0")]
2972 impl<'a, I, T: 'a> Iterator for Cloned<I>
2973 where I: Iterator<Item=&'a T>, T: Clone
2977 fn next(&mut self) -> Option<T> {
2978 self.it.next().cloned()
2981 fn size_hint(&self) -> (usize, Option<usize>) {
2986 #[stable(feature = "rust1", since = "1.0.0")]
2987 impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
2988 where I: DoubleEndedIterator<Item=&'a T>, T: Clone
2990 fn next_back(&mut self) -> Option<T> {
2991 self.it.next_back().cloned()
2995 #[stable(feature = "rust1", since = "1.0.0")]
2996 impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
2997 where I: ExactSizeIterator<Item=&'a T>, T: Clone
3000 /// An iterator that repeats endlessly.
3002 /// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
3003 /// documentation for more.
3005 /// [`cycle()`]: trait.Iterator.html#method.cycle
3006 /// [`Iterator`]: trait.Iterator.html
3008 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3009 #[stable(feature = "rust1", since = "1.0.0")]
3010 pub struct Cycle<I> {
3015 #[stable(feature = "rust1", since = "1.0.0")]
3016 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
3017 type Item = <I as Iterator>::Item;
3020 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3021 match self.iter.next() {
3022 None => { self.iter = self.orig.clone(); self.iter.next() }
3028 fn size_hint(&self) -> (usize, Option<usize>) {
3029 // the cycle iterator is either empty or infinite
3030 match self.orig.size_hint() {
3031 sz @ (0, Some(0)) => sz,
3032 (0, _) => (0, None),
3033 _ => (usize::MAX, None)
3038 /// An iterator that strings two iterators together.
3040 /// This `struct` is created by the [`chain()`] method on [`Iterator`]. See its
3041 /// documentation for more.
3043 /// [`chain()`]: trait.Iterator.html#method.chain
3044 /// [`Iterator`]: trait.Iterator.html
3046 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3047 #[stable(feature = "rust1", since = "1.0.0")]
3048 pub struct Chain<A, B> {
3054 // The iterator protocol specifies that iteration ends with the return value
3055 // `None` from `.next()` (or `.next_back()`) and it is unspecified what
3056 // further calls return. The chain adaptor must account for this since it uses
3057 // two subiterators.
3059 // It uses three states:
3061 // - Both: `a` and `b` are remaining
3062 // - Front: `a` remaining
3063 // - Back: `b` remaining
3065 // The fourth state (neither iterator is remaining) only occurs after Chain has
3066 // returned None once, so we don't need to store this state.
3069 // both front and back iterator are remaining
3071 // only front is remaining
3073 // only back is remaining
3077 #[stable(feature = "rust1", since = "1.0.0")]
3078 impl<A, B> Iterator for Chain<A, B> where
3080 B: Iterator<Item = A::Item>
3082 type Item = A::Item;
3085 fn next(&mut self) -> Option<A::Item> {
3087 ChainState::Both => match self.a.next() {
3088 elt @ Some(..) => elt,
3090 self.state = ChainState::Back;
3094 ChainState::Front => self.a.next(),
3095 ChainState::Back => self.b.next(),
3100 fn count(self) -> usize {
3102 ChainState::Both => self.a.count() + self.b.count(),
3103 ChainState::Front => self.a.count(),
3104 ChainState::Back => self.b.count(),
3109 fn nth(&mut self, mut n: usize) -> Option<A::Item> {
3111 ChainState::Both | ChainState::Front => {
3112 for x in self.a.by_ref() {
3118 if let ChainState::Both = self.state {
3119 self.state = ChainState::Back;
3122 ChainState::Back => {}
3124 if let ChainState::Back = self.state {
3132 fn last(self) -> Option<A::Item> {
3134 ChainState::Both => {
3135 // Must exhaust a before b.
3136 let a_last = self.a.last();
3137 let b_last = self.b.last();
3140 ChainState::Front => self.a.last(),
3141 ChainState::Back => self.b.last()
3146 fn size_hint(&self) -> (usize, Option<usize>) {
3147 let (a_lower, a_upper) = self.a.size_hint();
3148 let (b_lower, b_upper) = self.b.size_hint();
3150 let lower = a_lower.saturating_add(b_lower);
3152 let upper = match (a_upper, b_upper) {
3153 (Some(x), Some(y)) => x.checked_add(y),
3161 #[stable(feature = "rust1", since = "1.0.0")]
3162 impl<A, B> DoubleEndedIterator for Chain<A, B> where
3163 A: DoubleEndedIterator,
3164 B: DoubleEndedIterator<Item=A::Item>,
3167 fn next_back(&mut self) -> Option<A::Item> {
3169 ChainState::Both => match self.b.next_back() {
3170 elt @ Some(..) => elt,
3172 self.state = ChainState::Front;
3176 ChainState::Front => self.a.next_back(),
3177 ChainState::Back => self.b.next_back(),
3182 /// An iterator that iterates two other iterators simultaneously.
3184 /// This `struct` is created by the [`zip()`] method on [`Iterator`]. See its
3185 /// documentation for more.
3187 /// [`zip()`]: trait.Iterator.html#method.zip
3188 /// [`Iterator`]: trait.Iterator.html
3190 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3191 #[stable(feature = "rust1", since = "1.0.0")]
3192 pub struct Zip<A, B> {
3197 #[stable(feature = "rust1", since = "1.0.0")]
3198 impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
3200 type Item = (A::Item, B::Item);
3203 fn next(&mut self) -> Option<(A::Item, B::Item)> {
3204 self.a.next().and_then(|x| {
3205 self.b.next().and_then(|y| {
3212 fn size_hint(&self) -> (usize, Option<usize>) {
3213 let (a_lower, a_upper) = self.a.size_hint();
3214 let (b_lower, b_upper) = self.b.size_hint();
3216 let lower = cmp::min(a_lower, b_lower);
3218 let upper = match (a_upper, b_upper) {
3219 (Some(x), Some(y)) => Some(cmp::min(x,y)),
3220 (Some(x), None) => Some(x),
3221 (None, Some(y)) => Some(y),
3222 (None, None) => None
3229 #[stable(feature = "rust1", since = "1.0.0")]
3230 impl<A, B> DoubleEndedIterator for Zip<A, B> where
3231 A: DoubleEndedIterator + ExactSizeIterator,
3232 B: DoubleEndedIterator + ExactSizeIterator,
3235 fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
3236 let a_sz = self.a.len();
3237 let b_sz = self.b.len();
3239 // Adjust a, b to equal length
3241 for _ in 0..a_sz - b_sz { self.a.next_back(); }
3243 for _ in 0..b_sz - a_sz { self.b.next_back(); }
3246 match (self.a.next_back(), self.b.next_back()) {
3247 (Some(x), Some(y)) => Some((x, y)),
3248 (None, None) => None,
3249 _ => unreachable!(),
3254 /// An iterator that maps the values of `iter` with `f`.
3256 /// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
3257 /// documentation for more.
3259 /// [`map()`]: trait.Iterator.html#method.map
3260 /// [`Iterator`]: trait.Iterator.html
3261 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3262 #[stable(feature = "rust1", since = "1.0.0")]
3264 pub struct Map<I, F> {
3269 #[stable(feature = "rust1", since = "1.0.0")]
3270 impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
3274 fn next(&mut self) -> Option<B> {
3275 self.iter.next().map(&mut self.f)
3279 fn size_hint(&self) -> (usize, Option<usize>) {
3280 self.iter.size_hint()
3284 #[stable(feature = "rust1", since = "1.0.0")]
3285 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
3286 F: FnMut(I::Item) -> B,
3289 fn next_back(&mut self) -> Option<B> {
3290 self.iter.next_back().map(&mut self.f)
3294 /// An iterator that filters the elements of `iter` with `predicate`.
3296 /// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
3297 /// documentation for more.
3299 /// [`filter()`]: trait.Iterator.html#method.filter
3300 /// [`Iterator`]: trait.Iterator.html
3301 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3302 #[stable(feature = "rust1", since = "1.0.0")]
3304 pub struct Filter<I, P> {
3309 #[stable(feature = "rust1", since = "1.0.0")]
3310 impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
3311 type Item = I::Item;
3314 fn next(&mut self) -> Option<I::Item> {
3315 for x in self.iter.by_ref() {
3316 if (self.predicate)(&x) {
3324 fn size_hint(&self) -> (usize, Option<usize>) {
3325 let (_, upper) = self.iter.size_hint();
3326 (0, upper) // can't know a lower bound, due to the predicate
3330 #[stable(feature = "rust1", since = "1.0.0")]
3331 impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
3332 where P: FnMut(&I::Item) -> bool,
3335 fn next_back(&mut self) -> Option<I::Item> {
3336 for x in self.iter.by_ref().rev() {
3337 if (self.predicate)(&x) {
3345 /// An iterator that uses `f` to both filter and map elements from `iter`.
3347 /// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
3348 /// documentation for more.
3350 /// [`filter_map()`]: trait.Iterator.html#method.filter_map
3351 /// [`Iterator`]: trait.Iterator.html
3352 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3353 #[stable(feature = "rust1", since = "1.0.0")]
3355 pub struct FilterMap<I, F> {
3360 #[stable(feature = "rust1", since = "1.0.0")]
3361 impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
3362 where F: FnMut(I::Item) -> Option<B>,
3367 fn next(&mut self) -> Option<B> {
3368 for x in self.iter.by_ref() {
3369 if let Some(y) = (self.f)(x) {
3377 fn size_hint(&self) -> (usize, Option<usize>) {
3378 let (_, upper) = self.iter.size_hint();
3379 (0, upper) // can't know a lower bound, due to the predicate
3383 #[stable(feature = "rust1", since = "1.0.0")]
3384 impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
3385 where F: FnMut(I::Item) -> Option<B>,
3388 fn next_back(&mut self) -> Option<B> {
3389 for x in self.iter.by_ref().rev() {
3390 if let Some(y) = (self.f)(x) {
3398 /// An iterator that yields the current count and the element during iteration.
3400 /// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
3401 /// documentation for more.
3403 /// [`enumerate()`]: trait.Iterator.html#method.enumerate
3404 /// [`Iterator`]: trait.Iterator.html
3406 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3407 #[stable(feature = "rust1", since = "1.0.0")]
3408 pub struct Enumerate<I> {
3413 #[stable(feature = "rust1", since = "1.0.0")]
3414 impl<I> Iterator for Enumerate<I> where I: Iterator {
3415 type Item = (usize, <I as Iterator>::Item);
3417 /// # Overflow Behavior
3419 /// The method does no guarding against overflows, so enumerating more than
3420 /// `usize::MAX` elements either produces the wrong result or panics. If
3421 /// debug assertions are enabled, a panic is guaranteed.
3425 /// Might panic if the index of the element overflows a `usize`.
3427 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3428 self.iter.next().map(|a| {
3429 let ret = (self.count, a);
3430 // Possible undefined overflow.
3437 fn size_hint(&self) -> (usize, Option<usize>) {
3438 self.iter.size_hint()
3442 fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
3443 self.iter.nth(n).map(|a| {
3444 let i = self.count + n;
3451 fn count(self) -> usize {
3456 #[stable(feature = "rust1", since = "1.0.0")]
3457 impl<I> DoubleEndedIterator for Enumerate<I> where
3458 I: ExactSizeIterator + DoubleEndedIterator
3461 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
3462 self.iter.next_back().map(|a| {
3463 let len = self.iter.len();
3464 // Can safely add, `ExactSizeIterator` promises that the number of
3465 // elements fits into a `usize`.
3466 (self.count + len, a)
3471 /// An iterator with a `peek()` that returns an optional reference to the next
3474 /// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
3475 /// documentation for more.
3477 /// [`peekable()`]: trait.Iterator.html#method.peekable
3478 /// [`Iterator`]: trait.Iterator.html
3480 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3481 #[stable(feature = "rust1", since = "1.0.0")]
3482 pub struct Peekable<I: Iterator> {
3484 peeked: Option<I::Item>,
3487 #[stable(feature = "rust1", since = "1.0.0")]
3488 impl<I: Iterator> Iterator for Peekable<I> {
3489 type Item = I::Item;
3492 fn next(&mut self) -> Option<I::Item> {
3494 Some(_) => self.peeked.take(),
3495 None => self.iter.next(),
3500 fn count(self) -> usize {
3501 (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
3505 fn nth(&mut self, n: usize) -> Option<I::Item> {
3507 Some(_) if n == 0 => self.peeked.take(),
3512 None => self.iter.nth(n)
3517 fn last(self) -> Option<I::Item> {
3518 self.iter.last().or(self.peeked)
3522 fn size_hint(&self) -> (usize, Option<usize>) {
3523 let (lo, hi) = self.iter.size_hint();
3524 if self.peeked.is_some() {
3525 let lo = lo.saturating_add(1);
3526 let hi = hi.and_then(|x| x.checked_add(1));
3534 #[stable(feature = "rust1", since = "1.0.0")]
3535 impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
3537 impl<I: Iterator> Peekable<I> {
3538 /// Returns a reference to the next() value without advancing the iterator.
3540 /// The `peek()` method will return the value that a call to [`next()`] would
3541 /// return, but does not advance the iterator. Like [`next()`], if there is
3542 /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
3543 /// will return `None`.
3545 /// [`next()`]: trait.Iterator.html#tymethod.next
3547 /// Because `peek()` returns reference, and many iterators iterate over
3548 /// references, this leads to a possibly confusing situation where the
3549 /// return value is a double reference. You can see this effect in the
3550 /// examples below, with `&&i32`.
3557 /// let xs = [1, 2, 3];
3559 /// let mut iter = xs.iter().peekable();
3561 /// // peek() lets us see into the future
3562 /// assert_eq!(iter.peek(), Some(&&1));
3563 /// assert_eq!(iter.next(), Some(&1));
3565 /// assert_eq!(iter.next(), Some(&2));
3567 /// // we can peek() multiple times, the iterator won't advance
3568 /// assert_eq!(iter.peek(), Some(&&3));
3569 /// assert_eq!(iter.peek(), Some(&&3));
3571 /// assert_eq!(iter.next(), Some(&3));
3573 /// // after the iterator is finished, so is peek()
3574 /// assert_eq!(iter.peek(), None);
3575 /// assert_eq!(iter.next(), None);
3578 #[stable(feature = "rust1", since = "1.0.0")]
3579 pub fn peek(&mut self) -> Option<&I::Item> {
3580 if self.peeked.is_none() {
3581 self.peeked = self.iter.next();
3584 Some(ref value) => Some(value),
3589 /// Checks if the iterator has finished iterating.
3591 /// Returns `true` if there are no more elements in the iterator, and
3592 /// `false` if there are.
3599 /// #![feature(peekable_is_empty)]
3601 /// let xs = [1, 2, 3];
3603 /// let mut iter = xs.iter().peekable();
3605 /// // there are still elements to iterate over
3606 /// assert_eq!(iter.is_empty(), false);
3608 /// // let's consume the iterator
3613 /// assert_eq!(iter.is_empty(), true);
3615 #[unstable(feature = "peekable_is_empty", issue = "27701")]
3617 pub fn is_empty(&mut self) -> bool {
3618 self.peek().is_none()
3622 /// An iterator that rejects elements while `predicate` is true.
3624 /// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
3625 /// documentation for more.
3627 /// [`skip_while()`]: trait.Iterator.html#method.skip_while
3628 /// [`Iterator`]: trait.Iterator.html
3629 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3630 #[stable(feature = "rust1", since = "1.0.0")]
3632 pub struct SkipWhile<I, P> {
3638 #[stable(feature = "rust1", since = "1.0.0")]
3639 impl<I: Iterator, P> Iterator for SkipWhile<I, P>
3640 where P: FnMut(&I::Item) -> bool
3642 type Item = I::Item;
3645 fn next(&mut self) -> Option<I::Item> {
3646 for x in self.iter.by_ref() {
3647 if self.flag || !(self.predicate)(&x) {
3656 fn size_hint(&self) -> (usize, Option<usize>) {
3657 let (_, upper) = self.iter.size_hint();
3658 (0, upper) // can't know a lower bound, due to the predicate
3662 /// An iterator that only accepts elements while `predicate` is true.
3664 /// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
3665 /// documentation for more.
3667 /// [`take_while()`]: trait.Iterator.html#method.take_while
3668 /// [`Iterator`]: trait.Iterator.html
3669 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3670 #[stable(feature = "rust1", since = "1.0.0")]
3672 pub struct TakeWhile<I, P> {
3678 #[stable(feature = "rust1", since = "1.0.0")]
3679 impl<I: Iterator, P> Iterator for TakeWhile<I, P>
3680 where P: FnMut(&I::Item) -> bool
3682 type Item = I::Item;
3685 fn next(&mut self) -> Option<I::Item> {
3689 self.iter.next().and_then(|x| {
3690 if (self.predicate)(&x) {
3701 fn size_hint(&self) -> (usize, Option<usize>) {
3702 let (_, upper) = self.iter.size_hint();
3703 (0, upper) // can't know a lower bound, due to the predicate
3707 /// An iterator that skips over `n` elements of `iter`.
3709 /// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
3710 /// documentation for more.
3712 /// [`skip()`]: trait.Iterator.html#method.skip
3713 /// [`Iterator`]: trait.Iterator.html
3715 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3716 #[stable(feature = "rust1", since = "1.0.0")]
3717 pub struct Skip<I> {
3722 #[stable(feature = "rust1", since = "1.0.0")]
3723 impl<I> Iterator for Skip<I> where I: Iterator {
3724 type Item = <I as Iterator>::Item;
3727 fn next(&mut self) -> Option<I::Item> {
3733 self.iter.nth(old_n)
3738 fn nth(&mut self, n: usize) -> Option<I::Item> {
3739 // Can't just add n + self.n due to overflow.
3743 let to_skip = self.n;
3746 if self.iter.nth(to_skip-1).is_none() {
3754 fn count(self) -> usize {
3755 self.iter.count().saturating_sub(self.n)
3759 fn last(mut self) -> Option<I::Item> {
3763 let next = self.next();
3765 // recurse. n should be 0.
3766 self.last().or(next)
3774 fn size_hint(&self) -> (usize, Option<usize>) {
3775 let (lower, upper) = self.iter.size_hint();
3777 let lower = lower.saturating_sub(self.n);
3778 let upper = upper.map(|x| x.saturating_sub(self.n));
3784 #[stable(feature = "rust1", since = "1.0.0")]
3785 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
3787 /// An iterator that only iterates over the first `n` iterations of `iter`.
3789 /// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
3790 /// documentation for more.
3792 /// [`take()`]: trait.Iterator.html#method.take
3793 /// [`Iterator`]: trait.Iterator.html
3795 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3796 #[stable(feature = "rust1", since = "1.0.0")]
3797 pub struct Take<I> {
3802 #[stable(feature = "rust1", since = "1.0.0")]
3803 impl<I> Iterator for Take<I> where I: Iterator{
3804 type Item = <I as Iterator>::Item;
3807 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3817 fn nth(&mut self, n: usize) -> Option<I::Item> {
3823 self.iter.nth(self.n - 1);
3831 fn size_hint(&self) -> (usize, Option<usize>) {
3832 let (lower, upper) = self.iter.size_hint();
3834 let lower = cmp::min(lower, self.n);
3836 let upper = match upper {
3837 Some(x) if x < self.n => Some(x),
3845 #[stable(feature = "rust1", since = "1.0.0")]
3846 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
3849 /// An iterator to maintain state while iterating another iterator.
3851 /// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
3852 /// documentation for more.
3854 /// [`scan()`]: trait.Iterator.html#method.scan
3855 /// [`Iterator`]: trait.Iterator.html
3856 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3857 #[stable(feature = "rust1", since = "1.0.0")]
3859 pub struct Scan<I, St, F> {
3865 #[stable(feature = "rust1", since = "1.0.0")]
3866 impl<B, I, St, F> Iterator for Scan<I, St, F> where
3868 F: FnMut(&mut St, I::Item) -> Option<B>,
3873 fn next(&mut self) -> Option<B> {
3874 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
3878 fn size_hint(&self) -> (usize, Option<usize>) {
3879 let (_, upper) = self.iter.size_hint();
3880 (0, upper) // can't know a lower bound, due to the scan function
3884 /// An iterator that maps each element to an iterator, and yields the elements
3885 /// of the produced iterators.
3887 /// This `struct` is created by the [`flat_map()`] method on [`Iterator`]. See its
3888 /// documentation for more.
3890 /// [`flat_map()`]: trait.Iterator.html#method.flat_map
3891 /// [`Iterator`]: trait.Iterator.html
3892 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3893 #[stable(feature = "rust1", since = "1.0.0")]
3895 pub struct FlatMap<I, U: IntoIterator, F> {
3898 frontiter: Option<U::IntoIter>,
3899 backiter: Option<U::IntoIter>,
3902 #[stable(feature = "rust1", since = "1.0.0")]
3903 impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
3904 where F: FnMut(I::Item) -> U,
3906 type Item = U::Item;
3909 fn next(&mut self) -> Option<U::Item> {
3911 if let Some(ref mut inner) = self.frontiter {
3912 if let Some(x) = inner.by_ref().next() {
3916 match self.iter.next().map(&mut self.f) {
3917 None => return self.backiter.as_mut().and_then(|it| it.next()),
3918 next => self.frontiter = next.map(IntoIterator::into_iter),
3924 fn size_hint(&self) -> (usize, Option<usize>) {
3925 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3926 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
3927 let lo = flo.saturating_add(blo);
3928 match (self.iter.size_hint(), fhi, bhi) {
3929 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
3935 #[stable(feature = "rust1", since = "1.0.0")]
3936 impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F> where
3937 F: FnMut(I::Item) -> U,
3939 U::IntoIter: DoubleEndedIterator
3942 fn next_back(&mut self) -> Option<U::Item> {
3944 if let Some(ref mut inner) = self.backiter {
3945 if let Some(y) = inner.next_back() {
3949 match self.iter.next_back().map(&mut self.f) {
3950 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
3951 next => self.backiter = next.map(IntoIterator::into_iter),
3957 /// An iterator that yields `None` forever after the underlying iterator
3958 /// yields `None` once.
3960 /// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
3961 /// documentation for more.
3963 /// [`fuse()`]: trait.Iterator.html#method.fuse
3964 /// [`Iterator`]: trait.Iterator.html
3966 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3967 #[stable(feature = "rust1", since = "1.0.0")]
3968 pub struct Fuse<I> {
3973 #[stable(feature = "rust1", since = "1.0.0")]
3974 impl<I> Iterator for Fuse<I> where I: Iterator {
3975 type Item = <I as Iterator>::Item;
3978 fn next(&mut self) -> Option<<I as Iterator>::Item> {
3982 let next = self.iter.next();
3983 self.done = next.is_none();
3989 fn nth(&mut self, n: usize) -> Option<I::Item> {
3993 let nth = self.iter.nth(n);
3994 self.done = nth.is_none();
4000 fn last(self) -> Option<I::Item> {
4009 fn count(self) -> usize {
4018 fn size_hint(&self) -> (usize, Option<usize>) {
4022 self.iter.size_hint()
4027 #[stable(feature = "rust1", since = "1.0.0")]
4028 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
4030 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
4034 let next = self.iter.next_back();
4035 self.done = next.is_none();
4041 #[stable(feature = "rust1", since = "1.0.0")]
4042 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
4044 /// An iterator that calls a function with a reference to each element before
4047 /// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
4048 /// documentation for more.
4050 /// [`inspect()`]: trait.Iterator.html#method.inspect
4051 /// [`Iterator`]: trait.Iterator.html
4052 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
4053 #[stable(feature = "rust1", since = "1.0.0")]
4055 pub struct Inspect<I, F> {
4060 impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
4062 fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
4063 if let Some(ref a) = elt {
4071 #[stable(feature = "rust1", since = "1.0.0")]
4072 impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
4073 type Item = I::Item;
4076 fn next(&mut self) -> Option<I::Item> {
4077 let next = self.iter.next();
4078 self.do_inspect(next)
4082 fn size_hint(&self) -> (usize, Option<usize>) {
4083 self.iter.size_hint()
4087 #[stable(feature = "rust1", since = "1.0.0")]
4088 impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
4089 where F: FnMut(&I::Item),
4092 fn next_back(&mut self) -> Option<I::Item> {
4093 let next = self.iter.next_back();
4094 self.do_inspect(next)
4098 /// Objects that can be stepped over in both directions.
4100 /// The `steps_between` function provides a way to efficiently compare
4101 /// two `Step` objects.
4102 #[unstable(feature = "step_trait",
4103 reason = "likely to be replaced by finer-grained traits",
4105 pub trait Step: PartialOrd + Sized {
4106 /// Steps `self` if possible.
4107 fn step(&self, by: &Self) -> Option<Self>;
4109 /// Returns the number of steps between two step objects. The count is
4110 /// inclusive of `start` and exclusive of `end`.
4112 /// Returns `None` if it is not possible to calculate `steps_between`
4113 /// without overflow.
4114 fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
4117 macro_rules! step_impl_unsigned {
4119 #[unstable(feature = "step_trait",
4120 reason = "likely to be replaced by finer-grained traits",
4124 fn step(&self, by: &$t) -> Option<$t> {
4125 (*self).checked_add(*by)
4128 #[allow(trivial_numeric_casts)]
4129 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4130 if *by == 0 { return None; }
4132 // Note: We assume $t <= usize here
4133 let diff = (*end - *start) as usize;
4134 let by = *by as usize;
4147 macro_rules! step_impl_signed {
4149 #[unstable(feature = "step_trait",
4150 reason = "likely to be replaced by finer-grained traits",
4154 fn step(&self, by: &$t) -> Option<$t> {
4155 (*self).checked_add(*by)
4158 #[allow(trivial_numeric_casts)]
4159 fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
4160 if *by == 0 { return None; }
4167 // Note: We assume $t <= isize here
4168 // Use .wrapping_sub and cast to usize to compute the
4169 // difference that may not fit inside the range of isize.
4170 diff = (*end as isize).wrapping_sub(*start as isize) as usize;
4171 by_u = *by as usize;
4176 diff = (*start as isize).wrapping_sub(*end as isize) as usize;
4177 by_u = (*by as isize).wrapping_mul(-1) as usize;
4179 if diff % by_u > 0 {
4180 Some(diff / by_u + 1)
4189 macro_rules! step_impl_no_between {
4191 #[unstable(feature = "step_trait",
4192 reason = "likely to be replaced by finer-grained traits",
4196 fn step(&self, by: &$t) -> Option<$t> {
4197 (*self).checked_add(*by)
4200 fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
4207 step_impl_unsigned!(usize u8 u16 u32);
4208 step_impl_signed!(isize i8 i16 i32);
4209 #[cfg(target_pointer_width = "64")]
4210 step_impl_unsigned!(u64);
4211 #[cfg(target_pointer_width = "64")]
4212 step_impl_signed!(i64);
4213 // If the target pointer width is not 64-bits, we
4214 // assume here that it is less than 64-bits.
4215 #[cfg(not(target_pointer_width = "64"))]
4216 step_impl_no_between!(u64 i64);
4218 /// An adapter for stepping range iterators by a custom amount.
4220 /// The resulting iterator handles overflow by stopping. The `A`
4221 /// parameter is the type being iterated over, while `R` is the range
4222 /// type (usually one of `std::ops::{Range, RangeFrom}`.
4224 #[unstable(feature = "step_by", reason = "recent addition",
4226 pub struct StepBy<A, R> {
4231 impl<A: Step> RangeFrom<A> {
4232 /// Creates an iterator starting at the same point, but stepping by
4233 /// the given amount at each iteration.
4238 /// # #![feature(step_by)]
4240 /// for i in (0u8..).step_by(2).take(10) {
4241 /// println!("{}", i);
4245 /// This prints the first ten even natural integers (0 to 18).
4246 #[unstable(feature = "step_by", reason = "recent addition",
4248 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4256 impl<A: Step> ops::Range<A> {
4257 /// Creates an iterator with the same range, but stepping by the
4258 /// given amount at each iteration.
4260 /// The resulting iterator handles overflow by stopping.
4265 /// #![feature(step_by)]
4267 /// for i in (0..10).step_by(2) {
4268 /// println!("{}", i);
4281 #[unstable(feature = "step_by", reason = "recent addition",
4283 pub fn step_by(self, by: A) -> StepBy<A, Self> {
4291 #[stable(feature = "rust1", since = "1.0.0")]
4292 impl<A> Iterator for StepBy<A, RangeFrom<A>> where
4294 for<'a> &'a A: Add<&'a A, Output = A>
4299 fn next(&mut self) -> Option<A> {
4300 let mut n = &self.range.start + &self.step_by;
4301 mem::swap(&mut n, &mut self.range.start);
4306 fn size_hint(&self) -> (usize, Option<usize>) {
4307 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
4311 /// An iterator over the range [start, stop]
4313 #[unstable(feature = "range_inclusive",
4314 reason = "likely to be replaced by range notation and adapters",
4316 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4317 #[allow(deprecated)]
4318 pub struct RangeInclusive<A> {
4319 range: ops::Range<A>,
4323 /// Returns an iterator over the range [start, stop].
4325 #[unstable(feature = "range_inclusive",
4326 reason = "likely to be replaced by range notation and adapters",
4328 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4329 #[allow(deprecated)]
4330 pub fn range_inclusive<A>(start: A, stop: A) -> RangeInclusive<A>
4331 where A: Step + One + Clone
4339 #[unstable(feature = "range_inclusive",
4340 reason = "likely to be replaced by range notation and adapters",
4342 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4343 #[allow(deprecated)]
4344 impl<A> Iterator for RangeInclusive<A> where
4345 A: PartialEq + Step + One + Clone,
4346 for<'a> &'a A: Add<&'a A, Output = A>
4351 fn next(&mut self) -> Option<A> {
4352 self.range.next().or_else(|| {
4353 if !self.done && self.range.start == self.range.end {
4355 Some(self.range.end.clone())
4363 fn size_hint(&self) -> (usize, Option<usize>) {
4364 let (lo, hi) = self.range.size_hint();
4368 let lo = lo.saturating_add(1);
4369 let hi = hi.and_then(|x| x.checked_add(1));
4375 #[unstable(feature = "range_inclusive",
4376 reason = "likely to be replaced by range notation and adapters",
4378 #[rustc_deprecated(since = "1.5.0", reason = "replaced with ... syntax")]
4379 #[allow(deprecated)]
4380 impl<A> DoubleEndedIterator for RangeInclusive<A> where
4381 A: PartialEq + Step + One + Clone,
4382 for<'a> &'a A: Add<&'a A, Output = A>,
4383 for<'a> &'a A: Sub<Output=A>
4386 fn next_back(&mut self) -> Option<A> {
4387 if self.range.end > self.range.start {
4388 let result = self.range.end.clone();
4389 self.range.end = &self.range.end - &A::one();
4391 } else if !self.done && self.range.start == self.range.end {
4393 Some(self.range.end.clone())
4400 #[stable(feature = "rust1", since = "1.0.0")]
4401 impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
4405 fn next(&mut self) -> Option<A> {
4406 let rev = self.step_by < A::zero();
4407 if (rev && self.range.start > self.range.end) ||
4408 (!rev && self.range.start < self.range.end)
4410 match self.range.start.step(&self.step_by) {
4412 mem::swap(&mut self.range.start, &mut n);
4416 let mut n = self.range.end.clone();
4417 mem::swap(&mut self.range.start, &mut n);
4427 fn size_hint(&self) -> (usize, Option<usize>) {
4428 match Step::steps_between(&self.range.start,
4431 Some(hint) => (hint, Some(hint)),
4437 macro_rules! range_exact_iter_impl {
4439 #[stable(feature = "rust1", since = "1.0.0")]
4440 impl ExactSizeIterator for ops::Range<$t> { }
4444 #[stable(feature = "rust1", since = "1.0.0")]
4445 impl<A: Step + One> Iterator for ops::Range<A> where
4446 for<'a> &'a A: Add<&'a A, Output = A>
4451 fn next(&mut self) -> Option<A> {
4452 if self.start < self.end {
4453 let mut n = &self.start + &A::one();
4454 mem::swap(&mut n, &mut self.start);
4462 fn size_hint(&self) -> (usize, Option<usize>) {
4463 match Step::steps_between(&self.start, &self.end, &A::one()) {
4464 Some(hint) => (hint, Some(hint)),
4470 // Ranges of u64 and i64 are excluded because they cannot guarantee having
4471 // a length <= usize::MAX, which is required by ExactSizeIterator.
4472 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
4474 #[stable(feature = "rust1", since = "1.0.0")]
4475 impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
4476 for<'a> &'a A: Add<&'a A, Output = A>,
4477 for<'a> &'a A: Sub<&'a A, Output = A>
4480 fn next_back(&mut self) -> Option<A> {
4481 if self.start < self.end {
4482 self.end = &self.end - &A::one();
4483 Some(self.end.clone())
4490 #[stable(feature = "rust1", since = "1.0.0")]
4491 impl<A: Step + One> Iterator for ops::RangeFrom<A> where
4492 for<'a> &'a A: Add<&'a A, Output = A>
4497 fn next(&mut self) -> Option<A> {
4498 let mut n = &self.start + &A::one();
4499 mem::swap(&mut n, &mut self.start);
4504 /// An iterator that repeats an element endlessly.
4506 /// This `struct` is created by the [`repeat()`] function. See its documentation for more.
4508 /// [`repeat()`]: fn.repeat.html
4510 #[stable(feature = "rust1", since = "1.0.0")]
4511 pub struct Repeat<A> {
4515 #[stable(feature = "rust1", since = "1.0.0")]
4516 impl<A: Clone> Iterator for Repeat<A> {
4520 fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
4522 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
4525 #[stable(feature = "rust1", since = "1.0.0")]
4526 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
4528 fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
4531 /// Creates a new iterator that endlessly repeats a single element.
4533 /// The `repeat()` function repeats a single value over and over and over and
4534 /// over and over and 🔁.
4536 /// Infinite iterators like `repeat()` are often used with adapters like
4537 /// [`take()`], in order to make them finite.
4539 /// [`take()`]: trait.Iterator.html#method.take
4548 /// // the number four 4ever:
4549 /// let mut fours = iter::repeat(4);
4551 /// assert_eq!(Some(4), fours.next());
4552 /// assert_eq!(Some(4), fours.next());
4553 /// assert_eq!(Some(4), fours.next());
4554 /// assert_eq!(Some(4), fours.next());
4555 /// assert_eq!(Some(4), fours.next());
4557 /// // yup, still four
4558 /// assert_eq!(Some(4), fours.next());
4561 /// Going finite with [`take()`]:
4566 /// // that last example was too many fours. Let's only have four fours.
4567 /// let mut four_fours = iter::repeat(4).take(4);
4569 /// assert_eq!(Some(4), four_fours.next());
4570 /// assert_eq!(Some(4), four_fours.next());
4571 /// assert_eq!(Some(4), four_fours.next());
4572 /// assert_eq!(Some(4), four_fours.next());
4574 /// // ... and now we're done
4575 /// assert_eq!(None, four_fours.next());
4578 #[stable(feature = "rust1", since = "1.0.0")]
4579 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
4580 Repeat{element: elt}
4583 /// An iterator that yields nothing.
4585 /// This `struct` is created by the [`empty()`] function. See its documentation for more.
4587 /// [`empty()`]: fn.empty.html
4588 #[stable(feature = "iter_empty", since = "1.2.0")]
4589 pub struct Empty<T>(marker::PhantomData<T>);
4591 #[stable(feature = "iter_empty", since = "1.2.0")]
4592 impl<T> Iterator for Empty<T> {
4595 fn next(&mut self) -> Option<T> {
4599 fn size_hint(&self) -> (usize, Option<usize>){
4604 #[stable(feature = "iter_empty", since = "1.2.0")]
4605 impl<T> DoubleEndedIterator for Empty<T> {
4606 fn next_back(&mut self) -> Option<T> {
4611 #[stable(feature = "iter_empty", since = "1.2.0")]
4612 impl<T> ExactSizeIterator for Empty<T> {
4613 fn len(&self) -> usize {
4618 // not #[derive] because that adds a Clone bound on T,
4619 // which isn't necessary.
4620 #[stable(feature = "iter_empty", since = "1.2.0")]
4621 impl<T> Clone for Empty<T> {
4622 fn clone(&self) -> Empty<T> {
4623 Empty(marker::PhantomData)
4627 // not #[derive] because that adds a Default bound on T,
4628 // which isn't necessary.
4629 #[stable(feature = "iter_empty", since = "1.2.0")]
4630 impl<T> Default for Empty<T> {
4631 fn default() -> Empty<T> {
4632 Empty(marker::PhantomData)
4636 /// Creates an iterator that yields nothing.
4645 /// // this could have been an iterator over i32, but alas, it's just not.
4646 /// let mut nope = iter::empty::<i32>();
4648 /// assert_eq!(None, nope.next());
4650 #[stable(feature = "iter_empty", since = "1.2.0")]
4651 pub fn empty<T>() -> Empty<T> {
4652 Empty(marker::PhantomData)
4655 /// An iterator that yields an element exactly once.
4657 /// This `struct` is created by the [`once()`] function. See its documentation for more.
4659 /// [`once()`]: fn.once.html
4661 #[stable(feature = "iter_once", since = "1.2.0")]
4662 pub struct Once<T> {
4663 inner: ::option::IntoIter<T>
4666 #[stable(feature = "iter_once", since = "1.2.0")]
4667 impl<T> Iterator for Once<T> {
4670 fn next(&mut self) -> Option<T> {
4674 fn size_hint(&self) -> (usize, Option<usize>) {
4675 self.inner.size_hint()
4679 #[stable(feature = "iter_once", since = "1.2.0")]
4680 impl<T> DoubleEndedIterator for Once<T> {
4681 fn next_back(&mut self) -> Option<T> {
4682 self.inner.next_back()
4686 #[stable(feature = "iter_once", since = "1.2.0")]
4687 impl<T> ExactSizeIterator for Once<T> {
4688 fn len(&self) -> usize {
4693 /// Creates an iterator that yields an element exactly once.
4695 /// This is commonly used to adapt a single value into a [`chain()`] of other
4696 /// kinds of iteration. Maybe you have an iterator that covers almost
4697 /// everything, but you need an extra special case. Maybe you have a function
4698 /// which works on iterators, but you only need to process one value.
4700 /// [`chain()`]: trait.Iterator.html#method.chain
4709 /// // one is the loneliest number
4710 /// let mut one = iter::once(1);
4712 /// assert_eq!(Some(1), one.next());
4714 /// // just one, that's all we get
4715 /// assert_eq!(None, one.next());
4718 /// Chaining together with another iterator. Let's say that we want to iterate
4719 /// over each file of the `.foo` directory, but also a configuration file,
4725 /// use std::path::PathBuf;
4727 /// let dirs = fs::read_dir(".foo").unwrap();
4729 /// // we need to convert from an iterator of DirEntry-s to an iterator of
4730 /// // PathBufs, so we use map
4731 /// let dirs = dirs.map(|file| file.unwrap().path());
4733 /// // now, our iterator just for our config file
4734 /// let config = iter::once(PathBuf::from(".foorc"));
4736 /// // chain the two iterators together into one big iterator
4737 /// let files = dirs.chain(config);
4739 /// // this will give us all of the files in .foo as well as .foorc
4740 /// for f in files {
4741 /// println!("{:?}", f);
4744 #[stable(feature = "iter_once", since = "1.2.0")]
4745 pub fn once<T>(value: T) -> Once<T> {
4746 Once { inner: Some(value).into_iter() }