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 iterators
13 //! # The `Iterator` trait
15 //! This module defines Rust's core iteration trait. The `Iterator` trait has one
16 //! unimplemented method, `next`. All other methods are derived through default
17 //! methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.
19 //! The goal of this module is to unify iteration across all containers in Rust.
20 //! An iterator can be considered as a state machine which is used to track which
21 //! element will be yielded next.
23 //! There are various extensions also defined in this module to assist with various
24 //! types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
25 //! the `FromIterator` trait for creating a container from an iterator, and much
28 //! ## Rust's `for` loop
30 //! The special syntax used by rust's `for` loop is based around the `Iterator`
31 //! trait defined in this module. For loops can be viewed as a syntactical expansion
32 //! into a `loop`, for example, the `for` loop in this example is essentially
33 //! translated to the `loop` below.
36 //! let values = vec![1, 2, 3];
38 //! // "Syntactical sugar" taking advantage of an iterator
39 //! for &x in values.iter() {
40 //! println!("{}", x);
43 //! // Rough translation of the iteration without a `for` iterator.
44 //! let mut it = values.iter();
48 //! println!("{}", x);
55 //! This `for` loop syntax can be applied to any iterator over any type.
57 #![stable(feature = "rust1", since = "1.0.0")]
59 use self::MinMaxResult::*;
66 use num::{ToPrimitive, Int};
67 use ops::{Add, Deref, FnMut};
69 use option::Option::{Some, None};
70 use std::marker::Sized;
73 /// An interface for dealing with "external iterators". These types of iterators
74 /// can be resumed at any time as all state is stored internally as opposed to
75 /// being located on the call stack.
77 /// The Iterator protocol states that an iterator yields a (potentially-empty,
78 /// potentially-infinite) sequence of values, and returns `None` to signal that
79 /// it's finished. The Iterator protocol does not define behavior after `None`
80 /// is returned. A concrete Iterator implementation may choose to behave however
81 /// it wishes, either by returning `None` infinitely, or by doing something
84 #[stable(feature = "rust1", since = "1.0.0")]
85 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling `.iter()` or a similar \
88 #[stable(feature = "rust1", since = "1.0.0")]
91 /// Advance the iterator and return the next value. Return `None` when the end is reached.
92 #[stable(feature = "rust1", since = "1.0.0")]
93 fn next(&mut self) -> Option<Self::Item>;
95 /// Returns a lower and upper bound on the remaining length of the iterator.
97 /// An upper bound of `None` means either there is no known upper bound, or the upper bound
98 /// does not fit within a `usize`.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
104 impl<'a, T> Iterator for &'a mut (Iterator<Item=T> + 'a) {
107 fn next(&mut self) -> Option<T> {
111 fn size_hint(&self) -> (usize, Option<usize>) {
116 /// Conversion from an `Iterator`
117 #[stable(feature = "rust1", since = "1.0.0")]
118 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
119 built from an iterator over elements of type `{A}`"]
120 pub trait FromIterator<A> {
121 /// Build a container with elements from an external iterator.
122 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> Self;
125 /// Conversion into an `Iterator`
126 pub trait IntoIterator {
129 /// Consumes `Self` and returns an iterator over it
130 fn into_iter(self) -> Self::Iter;
133 impl<I> IntoIterator for I where I: Iterator {
136 fn into_iter(self) -> I {
141 /// A type growable from an `Iterator` implementation
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub trait Extend<A> {
144 /// Extend a container with the elements yielded by an arbitrary iterator
145 #[stable(feature = "rust1", since = "1.0.0")]
146 fn extend<T: Iterator<Item=A>>(&mut self, iterator: T);
149 /// An extension trait providing numerous methods applicable to all iterators.
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub trait IteratorExt: Iterator + Sized {
152 /// Counts the number of elements in this iterator.
157 /// let a = [1, 2, 3, 4, 5];
158 /// assert_eq!(a.iter().count(), 5);
161 #[stable(feature = "rust1", since = "1.0.0")]
162 fn count(self) -> usize {
163 self.fold(0, |cnt, _x| cnt + 1)
166 /// Loops through the entire iterator, returning the last element of the
172 /// let a = [1, 2, 3, 4, 5];
173 /// assert!(a.iter().last().unwrap() == &5);
176 #[stable(feature = "rust1", since = "1.0.0")]
177 fn last(mut self) -> Option<Self::Item> {
179 for x in self { last = Some(x); }
183 /// Loops through `n` iterations, returning the `n`th element of the
189 /// let a = [1, 2, 3, 4, 5];
190 /// let mut it = a.iter();
191 /// assert!(it.nth(2).unwrap() == &3);
192 /// assert!(it.nth(2) == None);
195 #[stable(feature = "rust1", since = "1.0.0")]
196 fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
197 for x in self.by_ref() {
198 if n == 0 { return Some(x) }
204 /// Chain this iterator with another, returning a new iterator that will
205 /// finish iterating over the current iterator, and then iterate
206 /// over the other specified iterator.
213 /// let mut it = a.iter().chain(b.iter());
214 /// assert_eq!(it.next().unwrap(), &0);
215 /// assert_eq!(it.next().unwrap(), &1);
216 /// assert!(it.next().is_none());
219 #[stable(feature = "rust1", since = "1.0.0")]
220 fn chain<U>(self, other: U) -> Chain<Self, U> where
221 U: Iterator<Item=Self::Item>,
223 Chain{a: self, b: other, flag: false}
226 /// Creates an iterator that iterates over both this and the specified
227 /// iterators simultaneously, yielding the two elements as pairs. When
228 /// either iterator returns None, all further invocations of next() will
236 /// let mut it = a.iter().zip(b.iter());
237 /// assert_eq!(it.next().unwrap(), (&0, &1));
238 /// assert!(it.next().is_none());
241 #[stable(feature = "rust1", since = "1.0.0")]
242 fn zip<B, U>(self, other: U) -> Zip<Self, U> where
245 Zip{a: self, b: other}
248 /// Creates a new iterator that will apply the specified function to each
249 /// element returned by the first, yielding the mapped element instead.
255 /// let mut it = a.iter().map(|&x| 2 * x);
256 /// assert_eq!(it.next().unwrap(), 2);
257 /// assert_eq!(it.next().unwrap(), 4);
258 /// assert!(it.next().is_none());
261 #[stable(feature = "rust1", since = "1.0.0")]
262 fn map<B, F>(self, f: F) -> Map<Self::Item, B, Self, F> where
263 F: FnMut(Self::Item) -> B,
265 Map{iter: self, f: f}
268 /// Creates an iterator that applies the predicate to each element returned
269 /// by this iterator. The only elements that will be yieled are those that
270 /// make the predicate evaluate to `true`.
276 /// let mut it = a.iter().filter(|&x| *x > 1);
277 /// assert_eq!(it.next().unwrap(), &2);
278 /// assert!(it.next().is_none());
281 #[stable(feature = "rust1", since = "1.0.0")]
282 fn filter<P>(self, predicate: P) -> Filter<Self::Item, Self, P> where
283 P: FnMut(&Self::Item) -> bool,
285 Filter{iter: self, predicate: predicate}
288 /// Creates an iterator that both filters and maps elements.
289 /// If the specified function returns None, the element is skipped.
290 /// Otherwise the option is unwrapped and the new value is yielded.
296 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
297 /// assert_eq!(it.next().unwrap(), 4);
298 /// assert!(it.next().is_none());
301 #[stable(feature = "rust1", since = "1.0.0")]
302 fn filter_map<B, F>(self, f: F) -> FilterMap<Self::Item, B, Self, F> where
303 F: FnMut(Self::Item) -> Option<B>,
305 FilterMap { iter: self, f: f }
308 /// Creates an iterator that yields a pair of the value returned by this
309 /// iterator plus the current index of iteration.
314 /// let a = [100, 200];
315 /// let mut it = a.iter().enumerate();
316 /// assert_eq!(it.next().unwrap(), (0, &100));
317 /// assert_eq!(it.next().unwrap(), (1, &200));
318 /// assert!(it.next().is_none());
321 #[stable(feature = "rust1", since = "1.0.0")]
322 fn enumerate(self) -> Enumerate<Self> {
323 Enumerate{iter: self, count: 0}
326 /// Creates an iterator that has a `.peek()` method
327 /// that returns an optional reference to the next element.
332 /// let xs = [100, 200, 300];
333 /// let mut it = xs.iter().map(|x| *x).peekable();
334 /// assert_eq!(*it.peek().unwrap(), 100);
335 /// assert_eq!(it.next().unwrap(), 100);
336 /// assert_eq!(it.next().unwrap(), 200);
337 /// assert_eq!(*it.peek().unwrap(), 300);
338 /// assert_eq!(*it.peek().unwrap(), 300);
339 /// assert_eq!(it.next().unwrap(), 300);
340 /// assert!(it.peek().is_none());
341 /// assert!(it.next().is_none());
344 #[stable(feature = "rust1", since = "1.0.0")]
345 fn peekable(self) -> Peekable<Self::Item, Self> {
346 Peekable{iter: self, peeked: None}
349 /// Creates an iterator that invokes the predicate on elements
350 /// until it returns false. Once the predicate returns false, that
351 /// element and all further elements are yielded.
356 /// let a = [1, 2, 3, 4, 5];
357 /// let mut it = a.iter().skip_while(|&a| *a < 3);
358 /// assert_eq!(it.next().unwrap(), &3);
359 /// assert_eq!(it.next().unwrap(), &4);
360 /// assert_eq!(it.next().unwrap(), &5);
361 /// assert!(it.next().is_none());
364 #[stable(feature = "rust1", since = "1.0.0")]
365 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self::Item, Self, P> where
366 P: FnMut(&Self::Item) -> bool,
368 SkipWhile{iter: self, flag: false, predicate: predicate}
371 /// Creates an iterator that yields elements so long as the predicate
372 /// returns true. After the predicate returns false for the first time, no
373 /// further elements will be yielded.
378 /// let a = [1, 2, 3, 4, 5];
379 /// let mut it = a.iter().take_while(|&a| *a < 3);
380 /// assert_eq!(it.next().unwrap(), &1);
381 /// assert_eq!(it.next().unwrap(), &2);
382 /// assert!(it.next().is_none());
385 #[stable(feature = "rust1", since = "1.0.0")]
386 fn take_while<P>(self, predicate: P) -> TakeWhile<Self::Item, Self, P> where
387 P: FnMut(&Self::Item) -> bool,
389 TakeWhile{iter: self, flag: false, predicate: predicate}
392 /// Creates an iterator that skips the first `n` elements of this iterator,
393 /// and then yields all further items.
398 /// let a = [1, 2, 3, 4, 5];
399 /// let mut it = a.iter().skip(3);
400 /// assert_eq!(it.next().unwrap(), &4);
401 /// assert_eq!(it.next().unwrap(), &5);
402 /// assert!(it.next().is_none());
405 #[stable(feature = "rust1", since = "1.0.0")]
406 fn skip(self, n: usize) -> Skip<Self> {
407 Skip{iter: self, n: n}
410 /// Creates an iterator that yields the first `n` elements of this
416 /// let a = [1, 2, 3, 4, 5];
417 /// let mut it = a.iter().take(3);
418 /// assert_eq!(it.next().unwrap(), &1);
419 /// assert_eq!(it.next().unwrap(), &2);
420 /// assert_eq!(it.next().unwrap(), &3);
421 /// assert!(it.next().is_none());
424 #[stable(feature = "rust1", since = "1.0.0")]
425 fn take(self, n: usize) -> Take<Self> {
426 Take{iter: self, n: n}
429 /// Creates a new iterator that behaves in a similar fashion to fold.
430 /// There is a state which is passed between each iteration and can be
431 /// mutated as necessary. The yielded values from the closure are yielded
432 /// from the Scan instance when not None.
437 /// let a = [1, 2, 3, 4, 5];
438 /// let mut it = a.iter().scan(1, |fac, &x| {
442 /// assert_eq!(it.next().unwrap(), 1);
443 /// assert_eq!(it.next().unwrap(), 2);
444 /// assert_eq!(it.next().unwrap(), 6);
445 /// assert_eq!(it.next().unwrap(), 24);
446 /// assert_eq!(it.next().unwrap(), 120);
447 /// assert!(it.next().is_none());
450 #[stable(feature = "rust1", since = "1.0.0")]
455 ) -> Scan<Self::Item, B, Self, St, F> where
456 F: FnMut(&mut St, Self::Item) -> Option<B>,
458 Scan{iter: self, f: f, state: initial_state}
461 /// Creates an iterator that maps each element to an iterator,
462 /// and yields the elements of the produced iterators.
468 /// let ys = [0, 1, 0, 1, 2];
469 /// let it = xs.iter().flat_map(|&x| std::iter::count(0, 1).take(x));
470 /// // Check that `it` has the same elements as `ys`
471 /// for (i, x) in it.enumerate() {
472 /// assert_eq!(x, ys[i]);
476 #[stable(feature = "rust1", since = "1.0.0")]
477 fn flat_map<B, U, F>(self, f: F) -> FlatMap<Self::Item, B, Self, U, F> where
479 F: FnMut(Self::Item) -> U,
481 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
484 /// Creates an iterator that yields `None` forever after the underlying
485 /// iterator yields `None`. Random-access iterator behavior is not
486 /// affected, only single and double-ended iterator behavior.
491 /// fn process<U: Iterator<Item=isize>>(it: U) -> isize {
492 /// let mut it = it.fuse();
494 /// for x in it.by_ref() {
500 /// // did we exhaust the iterator?
501 /// if it.next().is_none() {
506 /// let x = vec![1, 2, 3, 7, 8, 9];
507 /// assert_eq!(process(x.into_iter()), 6);
508 /// let x = vec![1, 2, 3];
509 /// assert_eq!(process(x.into_iter()), 1006);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 fn fuse(self) -> Fuse<Self> {
514 Fuse{iter: self, done: false}
517 /// Creates an iterator that calls a function with a reference to each
518 /// element before yielding it. This is often useful for debugging an
519 /// iterator pipeline.
524 /// use std::iter::AdditiveIterator;
526 /// let a = [1, 4, 2, 3, 8, 9, 6];
527 /// let sum = a.iter()
529 /// .inspect(|&x| println!("filtering {}", x))
530 /// .filter(|&x| x % 2 == 0)
531 /// .inspect(|&x| println!("{} made it through", x))
533 /// println!("{}", sum);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 fn inspect<F>(self, f: F) -> Inspect<Self::Item, Self, F> where
538 F: FnMut(&Self::Item),
540 Inspect{iter: self, f: f}
543 /// Creates a wrapper around a mutable reference to the iterator.
545 /// This is useful to allow applying iterator adaptors while still
546 /// retaining ownership of the original iterator value.
551 /// let mut it = 0..10;
552 /// // sum the first five values
553 /// let partial_sum = it.by_ref().take(5).fold(0, |a, b| a + b);
554 /// assert!(partial_sum == 10);
555 /// assert!(it.next() == Some(5));
557 #[stable(feature = "rust1", since = "1.0.0")]
558 fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
562 /// Loops through the entire iterator, collecting all of the elements into
563 /// a container implementing `FromIterator`.
568 /// let a = [1, 2, 3, 4, 5];
569 /// let b: Vec<_> = a.iter().map(|&x| x).collect();
570 /// assert_eq!(a, b);
573 #[stable(feature = "rust1", since = "1.0.0")]
574 fn collect<B: FromIterator<Self::Item>>(self) -> B {
575 FromIterator::from_iter(self)
578 /// Loops through the entire iterator, collecting all of the elements into
579 /// one of two containers, depending on a predicate. The elements of the
580 /// first container satisfy the predicate, while the elements of the second
584 /// let vec = vec![1, 2, 3, 4];
585 /// let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0);
586 /// assert_eq!(even, vec![2, 4]);
587 /// assert_eq!(odd, vec![1, 3]);
589 #[unstable(feature = "core",
590 reason = "recently added as part of collections reform")]
591 fn partition<B, F>(mut self, mut f: F) -> (B, B) where
592 B: Default + Extend<Self::Item>,
593 F: FnMut(&Self::Item) -> bool
595 let mut left: B = Default::default();
596 let mut right: B = Default::default();
600 left.extend(Some(x).into_iter())
602 right.extend(Some(x).into_iter())
609 /// Performs a fold operation over the entire iterator, returning the
610 /// eventual state at the end of the iteration.
615 /// let a = [1, 2, 3, 4, 5];
616 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
619 #[stable(feature = "rust1", since = "1.0.0")]
620 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
621 F: FnMut(B, Self::Item) -> B,
623 let mut accum = init;
630 /// Tests whether the predicate holds true for all elements in the iterator.
635 /// let a = [1, 2, 3, 4, 5];
636 /// assert!(a.iter().all(|x| *x > 0));
637 /// assert!(!a.iter().all(|x| *x > 2));
640 #[stable(feature = "rust1", since = "1.0.0")]
641 fn all<F>(mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
642 for x in self { if !f(x) { return false; } }
646 /// Tests whether any element of an iterator satisfies the specified predicate.
648 /// Does not consume the iterator past the first found element.
653 /// let a = [1, 2, 3, 4, 5];
654 /// let mut it = a.iter();
655 /// assert!(it.any(|x| *x == 3));
656 /// assert_eq!(it.as_slice(), [4, 5]);
660 #[stable(feature = "rust1", since = "1.0.0")]
661 fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
662 for x in self.by_ref() { if f(x) { return true; } }
666 /// Returns the first element satisfying the specified predicate.
668 /// Does not consume the iterator past the first found element.
673 /// let a = [1, 2, 3, 4, 5];
674 /// let mut it = a.iter();
675 /// assert_eq!(it.find(|&x| *x == 3).unwrap(), &3);
676 /// assert_eq!(it.as_slice(), [4, 5]);
678 #[stable(feature = "rust1", since = "1.0.0")]
679 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
680 P: FnMut(&Self::Item) -> bool,
682 for x in self.by_ref() {
683 if predicate(&x) { return Some(x) }
688 /// Return the index of the first element satisfying the specified predicate
690 /// Does not consume the iterator past the first found element.
695 /// let a = [1, 2, 3, 4, 5];
696 /// let mut it = a.iter();
697 /// assert_eq!(it.position(|x| *x == 3).unwrap(), 2);
698 /// assert_eq!(it.as_slice(), [4, 5]);
700 #[stable(feature = "rust1", since = "1.0.0")]
701 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
702 P: FnMut(Self::Item) -> bool,
705 for x in self.by_ref() {
714 /// Return the index of the last element satisfying the specified predicate
716 /// If no element matches, None is returned.
718 /// Does not consume the iterator *before* the first found element.
723 /// let a = [1, 2, 2, 4, 5];
724 /// let mut it = a.iter();
725 /// assert_eq!(it.rposition(|x| *x == 2).unwrap(), 2);
726 /// assert_eq!(it.as_slice(), [1, 2]);
728 #[stable(feature = "rust1", since = "1.0.0")]
729 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
730 P: FnMut(Self::Item) -> bool,
731 Self: ExactSizeIterator + DoubleEndedIterator
733 let len = self.len();
734 for i in (0..len).rev() {
735 if predicate(self.next_back().expect("rposition: incorrect ExactSizeIterator")) {
742 /// Consumes the entire iterator to return the maximum element.
747 /// let a = [1, 2, 3, 4, 5];
748 /// assert!(a.iter().max().unwrap() == &5);
751 #[stable(feature = "rust1", since = "1.0.0")]
752 fn max(self) -> Option<Self::Item> where Self::Item: Ord
754 self.fold(None, |max, x| {
757 Some(y) => Some(cmp::max(x, y))
762 /// Consumes the entire iterator to return the minimum element.
767 /// let a = [1, 2, 3, 4, 5];
768 /// assert!(a.iter().min().unwrap() == &1);
771 #[stable(feature = "rust1", since = "1.0.0")]
772 fn min(self) -> Option<Self::Item> where Self::Item: Ord
774 self.fold(None, |min, x| {
777 Some(y) => Some(cmp::min(x, y))
782 /// `min_max` finds the minimum and maximum elements in the iterator.
784 /// The return type `MinMaxResult` is an enum of three variants:
786 /// - `NoElements` if the iterator is empty.
787 /// - `OneElement(x)` if the iterator has exactly one element.
788 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
789 /// values are equal if and only if there is more than one
790 /// element in the iterator and all elements are equal.
792 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
793 /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons.
798 /// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax};
800 /// let a: [isize; 0] = [];
801 /// assert_eq!(a.iter().min_max(), NoElements);
804 /// assert!(a.iter().min_max() == OneElement(&1));
806 /// let a = [1, 2, 3, 4, 5];
807 /// assert!(a.iter().min_max() == MinMax(&1, &5));
809 /// let a = [1, 1, 1, 1];
810 /// assert!(a.iter().min_max() == MinMax(&1, &1));
812 #[unstable(feature = "core", reason = "return type may change")]
813 fn min_max(mut self) -> MinMaxResult<Self::Item> where Self::Item: Ord
815 let (mut min, mut max) = match self.next() {
816 None => return NoElements,
819 None => return OneElement(x),
820 Some(y) => if x < y {(x, y)} else {(y,x)}
826 // `first` and `second` are the two next elements we want to look at.
827 // We first compare `first` and `second` (#1). The smaller one is then compared to
828 // current minimum (#2). The larger one is compared to current maximum (#3). This
829 // way we do 3 comparisons for 2 elements.
830 let first = match self.next() {
834 let second = match self.next() {
838 } else if first > max {
846 if first < min {min = first;}
847 if max < second {max = second;}
849 if second < min {min = second;}
850 if max < first {max = first;}
857 /// Return the element that gives the maximum value from the
858 /// specified function.
863 /// use core::num::SignedInt;
865 /// let a = [-3, 0, 1, 5, -10];
866 /// assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10);
869 #[unstable(feature = "core",
870 reason = "may want to produce an Ordering directly; see #15311")]
871 fn max_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
872 F: FnMut(&Self::Item) -> B,
874 self.fold(None, |max: Option<(Self::Item, B)>, x| {
877 None => Some((x, x_val)),
878 Some((y, y_val)) => if x_val > y_val {
887 /// Return the element that gives the minimum value from the
888 /// specified function.
893 /// use core::num::SignedInt;
895 /// let a = [-3, 0, 1, 5, -10];
896 /// assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0);
899 #[unstable(feature = "core",
900 reason = "may want to produce an Ordering directly; see #15311")]
901 fn min_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
902 F: FnMut(&Self::Item) -> B,
904 self.fold(None, |min: Option<(Self::Item, B)>, x| {
907 None => Some((x, x_val)),
908 Some((y, y_val)) => if x_val < y_val {
917 /// Change the direction of the iterator
919 /// The flipped iterator swaps the ends on an iterator that can already
920 /// be iterated from the front and from the back.
923 /// If the iterator also implements RandomAccessIterator, the flipped
924 /// iterator is also random access, with the indices starting at the back
925 /// of the original iterator.
927 /// Note: Random access with flipped indices still only applies to the first
928 /// `std::usize::MAX` elements of the original iterator.
930 #[stable(feature = "rust1", since = "1.0.0")]
931 fn rev(self) -> Rev<Self> {
935 /// Converts an iterator of pairs into a pair of containers.
937 /// Loops through the entire iterator, collecting the first component of
938 /// each item into one new container, and the second component into another.
943 /// let a = [(1, 2), (3, 4)];
944 /// let (left, right): (Vec<_>, Vec<_>) = a.iter().map(|&x| x).unzip();
945 /// assert_eq!([1, 3], left);
946 /// assert_eq!([2, 4], right);
948 #[unstable(feature = "core", reason = "recent addition")]
949 fn unzip<A, B, FromA, FromB>(mut self) -> (FromA, FromB) where
950 FromA: Default + Extend<A>,
951 FromB: Default + Extend<B>,
952 Self: Iterator<Item=(A, B)>,
954 struct SizeHint<A>(usize, Option<usize>);
955 impl<A> Iterator for SizeHint<A> {
958 fn next(&mut self) -> Option<A> { None }
959 fn size_hint(&self) -> (usize, Option<usize>) {
964 let (lo, hi) = self.size_hint();
965 let mut ts: FromA = Default::default();
966 let mut us: FromB = Default::default();
968 ts.extend(SizeHint(lo, hi));
969 us.extend(SizeHint(lo, hi));
972 ts.extend(Some(t).into_iter());
973 us.extend(Some(u).into_iter());
979 /// Creates an iterator that clones the elements it yields. Useful for converting an
980 /// Iterator<&T> to an Iterator<T>.
981 #[unstable(feature = "core", reason = "recent addition")]
982 fn cloned<T, D>(self) -> Cloned<Self> where
983 Self: Iterator<Item=D>,
990 /// Repeats an iterator endlessly
996 /// let mut it = a.iter().cycle();
997 /// assert_eq!(it.next().unwrap(), &1);
998 /// assert_eq!(it.next().unwrap(), &2);
999 /// assert_eq!(it.next().unwrap(), &1);
1001 #[stable(feature = "rust1", since = "1.0.0")]
1003 fn cycle(self) -> Cycle<Self> where Self: Clone {
1004 Cycle{orig: self.clone(), iter: self}
1007 /// Use an iterator to reverse a container in place.
1008 #[unstable(feature = "core",
1009 reason = "uncertain about placement or widespread use")]
1010 fn reverse_in_place<'a, T: 'a>(&mut self) where
1011 Self: Iterator<Item=&'a mut T> + DoubleEndedIterator
1014 match (self.next(), self.next_back()) {
1015 (Some(x), Some(y)) => mem::swap(x, y),
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<I> IteratorExt for I where I: Iterator {}
1025 /// A range iterator able to yield elements from both ends
1027 /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust
1028 /// elements from the *same* range, and do not work independently of each other.
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub trait DoubleEndedIterator: Iterator {
1031 /// Yield an element from the end of the range, returning `None` if the range is empty.
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 fn next_back(&mut self) -> Option<Self::Item>;
1036 /// An object implementing random access indexing by `usize`
1038 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
1039 /// Calling `next()` or `next_back()` on a `RandomAccessIterator`
1040 /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)`
1041 /// after `it.next()` is called.
1042 #[unstable(feature = "core",
1043 reason = "not widely used, may be better decomposed into Index and ExactSizeIterator")]
1044 pub trait RandomAccessIterator: Iterator {
1045 /// Return the number of indexable elements. At most `std::usize::MAX`
1046 /// elements are indexable, even if the iterator represents a longer range.
1047 fn indexable(&self) -> usize;
1049 /// Return an element at an index, or `None` if the index is out of bounds
1050 fn idx(&mut self, index: usize) -> Option<Self::Item>;
1053 /// An iterator that knows its exact length
1055 /// This trait is a helper for iterators like the vector iterator, so that
1056 /// it can support double-ended enumeration.
1058 /// `Iterator::size_hint` *must* return the exact size of the iterator.
1059 /// Note that the size must fit in `usize`.
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub trait ExactSizeIterator: Iterator {
1063 /// Return the exact length of the iterator.
1064 fn len(&self) -> usize {
1065 let (lower, upper) = self.size_hint();
1066 // Note: This assertion is overly defensive, but it checks the invariant
1067 // guaranteed by the trait. If this trait were rust-internal,
1068 // we could use debug_assert!; assert_eq! will check all Rust user
1069 // implementations too.
1070 assert_eq!(upper, Some(lower));
1075 // All adaptors that preserve the size of the wrapped iterator are fine
1076 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<A, I, F> ExactSizeIterator for Inspect<A, I, F> where
1081 I: ExactSizeIterator<Item=A>,
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 impl<I> ExactSizeIterator for Rev<I> where I: ExactSizeIterator + DoubleEndedIterator {}
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 impl<A, B, I, F> ExactSizeIterator for Map<A, B, I, F> where
1088 I: ExactSizeIterator<Item=A>,
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<A, B> ExactSizeIterator for Zip<A, B> where A: ExactSizeIterator, B: ExactSizeIterator {}
1094 /// An double-ended iterator with the direction inverted
1096 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1097 #[stable(feature = "rust1", since = "1.0.0")]
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
1104 type Item = <I as Iterator>::Item;
1107 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1109 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
1115 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1118 #[unstable(feature = "core", reason = "trait is experimental")]
1119 impl<I> RandomAccessIterator for Rev<I> where I: DoubleEndedIterator + RandomAccessIterator {
1121 fn indexable(&self) -> usize { self.iter.indexable() }
1123 fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> {
1124 let amt = self.indexable();
1125 self.iter.idx(amt - index - 1)
1129 /// A mutable reference to an iterator
1130 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub struct ByRef<'a, I:'a> {
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<'a, I> Iterator for ByRef<'a, I> where I: 'a + Iterator {
1138 type Item = <I as Iterator>::Item;
1141 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1143 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<'a, I> DoubleEndedIterator for ByRef<'a, I> where I: 'a + DoubleEndedIterator {
1149 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<'a, I> ExactSizeIterator for ByRef<'a, I> where I: 'a + ExactSizeIterator {}
1155 /// A trait for iterators over elements which can be added together
1156 #[unstable(feature = "core",
1157 reason = "needs to be re-evaluated as part of numerics reform")]
1158 pub trait AdditiveIterator<A> {
1159 /// Iterates over the entire iterator, summing up all the elements
1164 /// use std::iter::AdditiveIterator;
1166 /// let a = [1i32, 2, 3, 4, 5];
1167 /// let mut it = a.iter().map(|&x| x);
1168 /// assert!(it.sum() == 15);
1173 macro_rules! impl_additive {
1174 ($A:ty, $init:expr) => {
1175 #[unstable(feature = "core", reason = "trait is experimental")]
1176 impl<T: Iterator<Item=$A>> AdditiveIterator<$A> for T {
1178 fn sum(self) -> $A {
1179 self.fold($init, |acc, x| acc + x)
1184 impl_additive! { i8, 0 }
1185 impl_additive! { i16, 0 }
1186 impl_additive! { i32, 0 }
1187 impl_additive! { i64, 0 }
1188 impl_additive! { isize, 0 }
1189 impl_additive! { u8, 0 }
1190 impl_additive! { u16, 0 }
1191 impl_additive! { u32, 0 }
1192 impl_additive! { u64, 0 }
1193 impl_additive! { usize, 0 }
1194 impl_additive! { f32, 0.0 }
1195 impl_additive! { f64, 0.0 }
1197 /// A trait for iterators over elements which can be multiplied together.
1198 #[unstable(feature = "core",
1199 reason = "needs to be re-evaluated as part of numerics reform")]
1200 pub trait MultiplicativeIterator<A> {
1201 /// Iterates over the entire iterator, multiplying all the elements
1206 /// use std::iter::{count, MultiplicativeIterator};
1208 /// fn factorial(n: usize) -> usize {
1209 /// count(1, 1).take_while(|&i| i <= n).product()
1211 /// assert!(factorial(0) == 1);
1212 /// assert!(factorial(1) == 1);
1213 /// assert!(factorial(5) == 120);
1215 fn product(self) -> A;
1218 macro_rules! impl_multiplicative {
1219 ($A:ty, $init:expr) => {
1220 #[unstable(feature = "core", reason = "trait is experimental")]
1221 impl<T: Iterator<Item=$A>> MultiplicativeIterator<$A> for T {
1223 fn product(self) -> $A {
1224 self.fold($init, |acc, x| acc * x)
1229 impl_multiplicative! { i8, 1 }
1230 impl_multiplicative! { i16, 1 }
1231 impl_multiplicative! { i32, 1 }
1232 impl_multiplicative! { i64, 1 }
1233 impl_multiplicative! { isize, 1 }
1234 impl_multiplicative! { u8, 1 }
1235 impl_multiplicative! { u16, 1 }
1236 impl_multiplicative! { u32, 1 }
1237 impl_multiplicative! { u64, 1 }
1238 impl_multiplicative! { usize, 1 }
1239 impl_multiplicative! { f32, 1.0 }
1240 impl_multiplicative! { f64, 1.0 }
1242 /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
1243 #[derive(Clone, PartialEq, Debug)]
1244 #[unstable(feature = "core",
1245 reason = "unclear whether such a fine-grained result is widely useful")]
1246 pub enum MinMaxResult<T> {
1250 /// Iterator with one element, so the minimum and maximum are the same
1253 /// More than one element in the iterator, the first element is not larger than the second
1257 impl<T: Clone> MinMaxResult<T> {
1258 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1259 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1260 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1261 /// performing this operation will make one clone of `x`.
1266 /// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
1268 /// let r: MinMaxResult<isize> = NoElements;
1269 /// assert_eq!(r.into_option(), None);
1271 /// let r = OneElement(1);
1272 /// assert_eq!(r.into_option(), Some((1, 1)));
1274 /// let r = MinMax(1, 2);
1275 /// assert_eq!(r.into_option(), Some((1, 2)));
1277 #[unstable(feature = "core", reason = "type is unstable")]
1278 pub fn into_option(self) -> Option<(T,T)> {
1281 OneElement(x) => Some((x.clone(), x)),
1282 MinMax(x, y) => Some((x, y))
1287 /// An iterator that clones the elements of an underlying iterator
1288 #[unstable(feature = "core", reason = "recent addition")]
1289 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1291 pub struct Cloned<I> {
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 impl<T, D, I> Iterator for Cloned<I> where
1299 I: Iterator<Item=D>,
1303 fn next(&mut self) -> Option<T> {
1304 self.it.next().cloned()
1307 fn size_hint(&self) -> (usize, Option<usize>) {
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<T, D, I> DoubleEndedIterator for Cloned<I> where
1316 I: DoubleEndedIterator<Item=D>,
1318 fn next_back(&mut self) -> Option<T> {
1319 self.it.next_back().cloned()
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<T, D, I> ExactSizeIterator for Cloned<I> where
1327 I: ExactSizeIterator<Item=D>,
1330 /// An iterator that repeats endlessly
1332 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub struct Cycle<I> {
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
1341 type Item = <I as Iterator>::Item;
1344 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1345 match self.iter.next() {
1346 None => { self.iter = self.orig.clone(); self.iter.next() }
1352 fn size_hint(&self) -> (usize, Option<usize>) {
1353 // the cycle iterator is either empty or infinite
1354 match self.orig.size_hint() {
1355 sz @ (0, Some(0)) => sz,
1356 (0, _) => (0, None),
1357 _ => (usize::MAX, None)
1362 #[unstable(feature = "core", reason = "trait is experimental")]
1363 impl<I> RandomAccessIterator for Cycle<I> where
1364 I: Clone + RandomAccessIterator,
1367 fn indexable(&self) -> usize {
1368 if self.orig.indexable() > 0 {
1376 fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> {
1377 let liter = self.iter.indexable();
1378 let lorig = self.orig.indexable();
1381 } else if index < liter {
1382 self.iter.idx(index)
1384 self.orig.idx((index - liter) % lorig)
1389 /// An iterator that strings two iterators together
1391 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 pub struct Chain<A, B> {
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 impl<T, A, B> Iterator for Chain<A, B> where A: Iterator<Item=T>, B: Iterator<Item=T> {
1404 fn next(&mut self) -> Option<T> {
1408 match self.a.next() {
1409 Some(x) => return Some(x),
1418 fn size_hint(&self) -> (usize, Option<usize>) {
1419 let (a_lower, a_upper) = self.a.size_hint();
1420 let (b_lower, b_upper) = self.b.size_hint();
1422 let lower = a_lower.saturating_add(b_lower);
1424 let upper = match (a_upper, b_upper) {
1425 (Some(x), Some(y)) => x.checked_add(y),
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T, A, B> DoubleEndedIterator for Chain<A, B> where
1435 A: DoubleEndedIterator<Item=T>,
1436 B: DoubleEndedIterator<Item=T>,
1439 fn next_back(&mut self) -> Option<T> {
1440 match self.b.next_back() {
1442 None => self.a.next_back()
1447 #[unstable(feature = "core", reason = "trait is experimental")]
1448 impl<T, A, B> RandomAccessIterator for Chain<A, B> where
1449 A: RandomAccessIterator<Item=T>,
1450 B: RandomAccessIterator<Item=T>,
1453 fn indexable(&self) -> usize {
1454 let (a, b) = (self.a.indexable(), self.b.indexable());
1459 fn idx(&mut self, index: usize) -> Option<T> {
1460 let len = self.a.indexable();
1464 self.b.idx(index - len)
1469 /// An iterator that iterates two other iterators simultaneously
1471 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 pub struct Zip<A, B> {
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<T, U, A, B> Iterator for Zip<A, B> where
1480 A: Iterator<Item = T>,
1481 B: Iterator<Item = U>,
1486 fn next(&mut self) -> Option<(T, U)> {
1487 match self.a.next() {
1489 Some(x) => match self.b.next() {
1491 Some(y) => Some((x, y))
1497 fn size_hint(&self) -> (usize, Option<usize>) {
1498 let (a_lower, a_upper) = self.a.size_hint();
1499 let (b_lower, b_upper) = self.b.size_hint();
1501 let lower = cmp::min(a_lower, b_lower);
1503 let upper = match (a_upper, b_upper) {
1504 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1505 (Some(x), None) => Some(x),
1506 (None, Some(y)) => Some(y),
1507 (None, None) => None
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<T, U, A, B> DoubleEndedIterator for Zip<A, B> where
1516 A: DoubleEndedIterator + ExactSizeIterator<Item=T>,
1517 B: DoubleEndedIterator + ExactSizeIterator<Item=U>,
1520 fn next_back(&mut self) -> Option<(T, U)> {
1521 let a_sz = self.a.len();
1522 let b_sz = self.b.len();
1524 // Adjust a, b to equal length
1526 for _ in 0..a_sz - b_sz { self.a.next_back(); }
1528 for _ in 0..b_sz - a_sz { self.b.next_back(); }
1531 match (self.a.next_back(), self.b.next_back()) {
1532 (Some(x), Some(y)) => Some((x, y)),
1533 (None, None) => None,
1534 _ => unreachable!(),
1539 #[unstable(feature = "core", reason = "trait is experimental")]
1540 impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where
1541 A: RandomAccessIterator<Item=T>,
1542 B: RandomAccessIterator<Item=U>,
1545 fn indexable(&self) -> usize {
1546 cmp::min(self.a.indexable(), self.b.indexable())
1550 fn idx(&mut self, index: usize) -> Option<(T, U)> {
1551 match self.a.idx(index) {
1553 Some(x) => match self.b.idx(index) {
1555 Some(y) => Some((x, y))
1561 /// An iterator that maps the values of `iter` with `f`
1562 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 pub struct Map<A, B, I: Iterator<Item=A>, F: FnMut(A) -> B> {
1569 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl<A, B, I, F> Clone for Map<A, B, I, F> where
1572 I: Clone + Iterator<Item=A>,
1573 F: Clone + FnMut(A) -> B,
1575 fn clone(&self) -> Map<A, B, I, F> {
1577 iter: self.iter.clone(),
1583 impl<A, B, I, F> Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1585 fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1587 Some(a) => Some((self.f)(a)),
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1598 fn next(&mut self) -> Option<B> {
1599 let next = self.iter.next();
1604 fn size_hint(&self) -> (usize, Option<usize>) {
1605 self.iter.size_hint()
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where
1611 I: DoubleEndedIterator<Item=A>,
1615 fn next_back(&mut self) -> Option<B> {
1616 let next = self.iter.next_back();
1621 #[unstable(feature = "core", reason = "trait is experimental")]
1622 impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where
1623 I: RandomAccessIterator<Item=A>,
1627 fn indexable(&self) -> usize {
1628 self.iter.indexable()
1632 fn idx(&mut self, index: usize) -> Option<B> {
1633 let elt = self.iter.idx(index);
1638 /// An iterator that filters the elements of `iter` with `predicate`
1639 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 pub struct Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1646 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<A, I, P> Clone for Filter<A, I, P> where
1649 I: Clone + Iterator<Item=A>,
1650 P: Clone + FnMut(&A) -> bool,
1652 fn clone(&self) -> Filter<A, I, P> {
1654 iter: self.iter.clone(),
1655 predicate: self.predicate.clone(),
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1665 fn next(&mut self) -> Option<A> {
1666 for x in self.iter.by_ref() {
1667 if (self.predicate)(&x) {
1677 fn size_hint(&self) -> (usize, Option<usize>) {
1678 let (_, upper) = self.iter.size_hint();
1679 (0, upper) // can't know a lower bound, due to the predicate
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 impl<A, I, P> DoubleEndedIterator for Filter<A, I, P> where
1685 I: DoubleEndedIterator<Item=A>,
1686 P: FnMut(&A) -> bool,
1689 fn next_back(&mut self) -> Option<A> {
1690 for x in self.iter.by_ref().rev() {
1691 if (self.predicate)(&x) {
1699 /// An iterator that uses `f` to both filter and map elements from `iter`
1700 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 pub struct FilterMap<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> Option<B> {
1707 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<A, B, I, F> Clone for FilterMap<A, B, I, F> where
1710 I: Clone + Iterator<Item=A>,
1711 F: Clone + FnMut(A) -> Option<B>,
1713 fn clone(&self) -> FilterMap<A, B, I, F> {
1715 iter: self.iter.clone(),
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where
1723 I: Iterator<Item=A>,
1724 F: FnMut(A) -> Option<B>,
1729 fn next(&mut self) -> Option<B> {
1730 for x in self.iter.by_ref() {
1732 Some(y) => return Some(y),
1740 fn size_hint(&self) -> (usize, Option<usize>) {
1741 let (_, upper) = self.iter.size_hint();
1742 (0, upper) // can't know a lower bound, due to the predicate
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<A, B, I, F> DoubleEndedIterator for FilterMap<A, B, I, F> where
1748 I: DoubleEndedIterator<Item=A>,
1749 F: FnMut(A) -> Option<B>,
1752 fn next_back(&mut self) -> Option<B> {
1753 for x in self.iter.by_ref().rev() {
1755 Some(y) => return Some(y),
1763 /// An iterator that yields the current count and the element during iteration
1765 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 pub struct Enumerate<I> {
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 impl<I> Iterator for Enumerate<I> where I: Iterator {
1774 type Item = (usize, <I as Iterator>::Item);
1777 fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1778 match self.iter.next() {
1780 let ret = Some((self.count, a));
1789 fn size_hint(&self) -> (usize, Option<usize>) {
1790 self.iter.size_hint()
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl<I> DoubleEndedIterator for Enumerate<I> where
1796 I: ExactSizeIterator + DoubleEndedIterator
1799 fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
1800 match self.iter.next_back() {
1802 let len = self.iter.len();
1803 Some((self.count + len, a))
1810 #[unstable(feature = "core", reason = "trait is experimental")]
1811 impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator {
1813 fn indexable(&self) -> usize {
1814 self.iter.indexable()
1818 fn idx(&mut self, index: usize) -> Option<(usize, <I as Iterator>::Item)> {
1819 match self.iter.idx(index) {
1820 Some(a) => Some((self.count + index, a)),
1826 /// An iterator with a `peek()` that returns an optional reference to the next element.
1828 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 pub struct Peekable<T, I> where I: Iterator<Item=T> {
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> {
1840 fn next(&mut self) -> Option<T> {
1841 if self.peeked.is_some() { self.peeked.take() }
1842 else { self.iter.next() }
1846 fn size_hint(&self) -> (usize, Option<usize>) {
1847 let (lo, hi) = self.iter.size_hint();
1848 if self.peeked.is_some() {
1849 let lo = lo.saturating_add(1);
1851 Some(x) => x.checked_add(1),
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 impl<T, I> ExactSizeIterator for Peekable<T, I> where I: ExactSizeIterator<Item = T> {}
1864 #[stable(feature = "rust1", since = "1.0.0")]
1865 impl<T, I> Peekable<T, I> where I: Iterator<Item=T> {
1866 /// Return a reference to the next element of the iterator with out advancing it,
1867 /// or None if the iterator is exhausted.
1869 pub fn peek(&mut self) -> Option<&T> {
1870 if self.peeked.is_none() {
1871 self.peeked = self.iter.next();
1874 Some(ref value) => Some(value),
1879 /// Check whether peekable iterator is empty or not.
1881 pub fn is_empty(&mut self) -> bool {
1882 self.peek().is_none()
1886 /// An iterator that rejects elements while `predicate` is true
1887 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 pub struct SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1895 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 impl<A, I, P> Clone for SkipWhile<A, I, P> where
1898 I: Clone + Iterator<Item=A>,
1899 P: Clone + FnMut(&A) -> bool,
1901 fn clone(&self) -> SkipWhile<A, I, P> {
1903 iter: self.iter.clone(),
1905 predicate: self.predicate.clone(),
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1915 fn next(&mut self) -> Option<A> {
1916 for x in self.iter.by_ref() {
1917 if self.flag || !(self.predicate)(&x) {
1926 fn size_hint(&self) -> (usize, Option<usize>) {
1927 let (_, upper) = self.iter.size_hint();
1928 (0, upper) // can't know a lower bound, due to the predicate
1932 /// An iterator that only accepts elements while `predicate` is true
1933 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 pub struct TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1941 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl<A, I, P> Clone for TakeWhile<A, I, P> where
1944 I: Clone + Iterator<Item=A>,
1945 P: Clone + FnMut(&A) -> bool,
1947 fn clone(&self) -> TakeWhile<A, I, P> {
1949 iter: self.iter.clone(),
1951 predicate: self.predicate.clone(),
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1961 fn next(&mut self) -> Option<A> {
1965 match self.iter.next() {
1967 if (self.predicate)(&x) {
1980 fn size_hint(&self) -> (usize, Option<usize>) {
1981 let (_, upper) = self.iter.size_hint();
1982 (0, upper) // can't know a lower bound, due to the predicate
1986 /// An iterator that skips over `n` elements of `iter`.
1988 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 pub struct Skip<I> {
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl<I> Iterator for Skip<I> where I: Iterator {
1997 type Item = <I as Iterator>::Item;
2000 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2001 let mut next = self.iter.next();
2010 next = self.iter.next();
2025 fn size_hint(&self) -> (usize, Option<usize>) {
2026 let (lower, upper) = self.iter.size_hint();
2028 let lower = lower.saturating_sub(self.n);
2030 let upper = match upper {
2031 Some(x) => Some(x.saturating_sub(self.n)),
2039 #[unstable(feature = "core", reason = "trait is experimental")]
2040 impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{
2042 fn indexable(&self) -> usize {
2043 self.iter.indexable().saturating_sub(self.n)
2047 fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> {
2048 if index >= self.indexable() {
2051 self.iter.idx(index + self.n)
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
2059 /// An iterator that only iterates over the first `n` iterations of `iter`.
2061 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 pub struct Take<I> {
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 impl<I> Iterator for Take<I> where I: Iterator{
2070 type Item = <I as Iterator>::Item;
2073 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2083 fn size_hint(&self) -> (usize, Option<usize>) {
2084 let (lower, upper) = self.iter.size_hint();
2086 let lower = cmp::min(lower, self.n);
2088 let upper = match upper {
2089 Some(x) if x < self.n => Some(x),
2097 #[unstable(feature = "core", reason = "trait is experimental")]
2098 impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{
2100 fn indexable(&self) -> usize {
2101 cmp::min(self.iter.indexable(), self.n)
2105 fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> {
2106 if index >= self.n {
2109 self.iter.idx(index)
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
2118 /// An iterator to maintain state while iterating another iterator
2119 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2120 #[stable(feature = "rust1", since = "1.0.0")]
2121 pub struct Scan<A, B, I, St, F> where I: Iterator, F: FnMut(&mut St, A) -> Option<B> {
2125 /// The current internal state to be passed to the closure next.
2129 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2130 #[stable(feature = "rust1", since = "1.0.0")]
2131 impl<A, B, I, St, F> Clone for Scan<A, B, I, St, F> where
2132 I: Clone + Iterator<Item=A>,
2134 F: Clone + FnMut(&mut St, A) -> Option<B>,
2136 fn clone(&self) -> Scan<A, B, I, St, F> {
2138 iter: self.iter.clone(),
2140 state: self.state.clone(),
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where
2147 I: Iterator<Item=A>,
2148 F: FnMut(&mut St, A) -> Option<B>,
2153 fn next(&mut self) -> Option<B> {
2154 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2158 fn size_hint(&self) -> (usize, Option<usize>) {
2159 let (_, upper) = self.iter.size_hint();
2160 (0, upper) // can't know a lower bound, due to the scan function
2164 /// An iterator that maps each element to an iterator,
2165 /// and yields the elements of the produced iterators
2167 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 pub struct FlatMap<A, B, I, U, F> where
2170 I: Iterator<Item=A>,
2171 U: Iterator<Item=B>,
2176 frontiter: Option<U>,
2177 backiter: Option<U>,
2180 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2181 #[stable(feature = "rust1", since = "1.0.0")]
2182 impl<A, B, I, U, F> Clone for FlatMap<A, B, I, U, F> where
2183 I: Clone + Iterator<Item=A>,
2184 U: Clone + Iterator<Item=B>,
2185 F: Clone + FnMut(A) -> U,
2187 fn clone(&self) -> FlatMap<A, B, I, U, F> {
2189 iter: self.iter.clone(),
2191 frontiter: self.frontiter.clone(),
2192 backiter: self.backiter.clone(),
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where
2199 I: Iterator<Item=A>,
2200 U: Iterator<Item=B>,
2206 fn next(&mut self) -> Option<B> {
2208 if let Some(ref mut inner) = self.frontiter {
2209 for x in inner.by_ref() {
2213 match self.iter.next().map(|x| (self.f)(x)) {
2214 None => return self.backiter.as_mut().and_then(|it| it.next()),
2215 next => self.frontiter = next,
2221 fn size_hint(&self) -> (usize, Option<usize>) {
2222 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2223 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2224 let lo = flo.saturating_add(blo);
2225 match (self.iter.size_hint(), fhi, bhi) {
2226 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 impl<A, B, I, U, F> DoubleEndedIterator for FlatMap<A, B, I, U, F> where
2234 I: DoubleEndedIterator<Item=A>,
2235 U: DoubleEndedIterator<Item=B>,
2239 fn next_back(&mut self) -> Option<B> {
2241 if let Some(ref mut inner) = self.backiter {
2242 match inner.next_back() {
2247 match self.iter.next_back().map(|x| (self.f)(x)) {
2248 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2249 next => self.backiter = next,
2255 /// An iterator that yields `None` forever after the underlying iterator
2256 /// yields `None` once.
2258 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2259 #[stable(feature = "rust1", since = "1.0.0")]
2260 pub struct Fuse<I> {
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 impl<I> Iterator for Fuse<I> where I: Iterator {
2267 type Item = <I as Iterator>::Item;
2270 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2274 match self.iter.next() {
2285 fn size_hint(&self) -> (usize, Option<usize>) {
2289 self.iter.size_hint()
2294 #[stable(feature = "rust1", since = "1.0.0")]
2295 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2297 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2301 match self.iter.next_back() {
2312 // Allow RandomAccessIterators to be fused without affecting random-access behavior
2313 #[unstable(feature = "core", reason = "trait is experimental")]
2314 impl<I> RandomAccessIterator for Fuse<I> where I: RandomAccessIterator {
2316 fn indexable(&self) -> usize {
2317 self.iter.indexable()
2321 fn idx(&mut self, index: usize) -> Option<<I as Iterator>::Item> {
2322 self.iter.idx(index)
2326 #[stable(feature = "rust1", since = "1.0.0")]
2327 impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
2330 /// Resets the fuse such that the next call to .next() or .next_back() will
2331 /// call the underlying iterator again even if it previously returned None.
2333 #[unstable(feature = "core", reason = "seems marginal")]
2334 pub fn reset_fuse(&mut self) {
2339 /// An iterator that calls a function with a reference to each
2340 /// element before yielding it.
2341 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 pub struct Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2348 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<A, I, F> Clone for Inspect<A, I, F> where
2351 I: Clone + Iterator<Item=A>,
2352 F: Clone + FnMut(&A),
2354 fn clone(&self) -> Inspect<A, I, F> {
2356 iter: self.iter.clone(),
2362 impl<A, I, F> Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2364 fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
2366 Some(ref a) => (self.f)(a),
2374 #[stable(feature = "rust1", since = "1.0.0")]
2375 impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2379 fn next(&mut self) -> Option<A> {
2380 let next = self.iter.next();
2381 self.do_inspect(next)
2385 fn size_hint(&self) -> (usize, Option<usize>) {
2386 self.iter.size_hint()
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl<A, I, F> DoubleEndedIterator for Inspect<A, I, F> where
2392 I: DoubleEndedIterator<Item=A>,
2396 fn next_back(&mut self) -> Option<A> {
2397 let next = self.iter.next_back();
2398 self.do_inspect(next)
2402 #[unstable(feature = "core", reason = "trait is experimental")]
2403 impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where
2404 I: RandomAccessIterator<Item=A>,
2408 fn indexable(&self) -> usize {
2409 self.iter.indexable()
2413 fn idx(&mut self, index: usize) -> Option<A> {
2414 let element = self.iter.idx(index);
2415 self.do_inspect(element)
2419 /// An iterator that passes mutable state to a closure and yields the result.
2421 /// # Example: The Fibonacci Sequence
2423 /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2426 /// use std::iter::Unfold;
2427 /// use std::num::Int; // For `.checked_add()`
2429 /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2430 /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2431 /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| {
2432 /// // Attempt to get the next Fibonacci number
2433 /// // `x1` will be `None` if previously overflowed.
2434 /// let next = match (*x2, *x1) {
2435 /// (Some(x2), Some(x1)) => x2.checked_add(x1),
2439 /// // Shift left: ret <- x2 <- x1 <- next
2447 /// for i in fibonacci {
2448 /// println!("{}", i);
2451 #[unstable(feature = "core")]
2452 pub struct Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2454 /// Internal state that will be passed to the closure on the next iteration
2458 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2459 #[stable(feature = "rust1", since = "1.0.0")]
2460 impl<A, St, F> Clone for Unfold<A, St, F> where
2461 F: Clone + FnMut(&mut St) -> Option<A>,
2464 fn clone(&self) -> Unfold<A, St, F> {
2467 state: self.state.clone(),
2472 #[unstable(feature = "core")]
2473 impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2474 /// Creates a new iterator with the specified closure as the "iterator
2475 /// function" and an initial state to eventually pass to the closure
2477 pub fn new(initial_state: St, f: F) -> Unfold<A, St, F> {
2480 state: initial_state
2485 #[stable(feature = "rust1", since = "1.0.0")]
2486 impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2490 fn next(&mut self) -> Option<A> {
2491 (self.f)(&mut self.state)
2495 fn size_hint(&self) -> (usize, Option<usize>) {
2496 // no possible known bounds at this point
2501 /// An infinite iterator starting at `start` and advancing by `step` with each
2504 #[unstable(feature = "core",
2505 reason = "may be renamed or replaced by range notation adapaters")]
2506 pub struct Counter<A> {
2507 /// The current state the counter is at (next value to be yielded)
2509 /// The amount that this iterator is stepping by
2513 /// Creates a new counter with the specified start/step
2515 #[unstable(feature = "core",
2516 reason = "may be renamed or replaced by range notation adapaters")]
2517 pub fn count<A>(start: A, step: A) -> Counter<A> {
2518 Counter{state: start, step: step}
2521 #[stable(feature = "rust1", since = "1.0.0")]
2522 impl<A: Add<Output=A> + Clone> Iterator for Counter<A> {
2526 fn next(&mut self) -> Option<A> {
2527 let result = self.state.clone();
2528 self.state = self.state.clone() + self.step.clone();
2533 fn size_hint(&self) -> (usize, Option<usize>) {
2534 (usize::MAX, None) // Too bad we can't specify an infinite lower bound
2538 /// An iterator over the range [start, stop)
2540 #[unstable(feature = "core",
2541 reason = "will be replaced by range notation")]
2542 pub struct Range<A> {
2548 /// Returns an iterator over the given range [start, stop) (that is, starting
2549 /// at start (inclusive), and ending at stop (exclusive)).
2554 /// let array = [0, 1, 2, 3, 4];
2556 /// for i in range(0, 5) {
2557 /// println!("{}", i);
2558 /// assert_eq!(i, array[i]);
2562 #[unstable(feature = "core",
2563 reason = "will be replaced by range notation")]
2564 pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
2572 // FIXME: #10414: Unfortunate type bound
2573 #[unstable(feature = "core",
2574 reason = "will be replaced by range notation")]
2575 impl<A: Int + ToPrimitive> Iterator for Range<A> {
2579 fn next(&mut self) -> Option<A> {
2580 if self.state < self.stop {
2581 let result = self.state.clone();
2582 self.state = self.state + self.one;
2590 fn size_hint(&self) -> (usize, Option<usize>) {
2591 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
2592 // handle cases like range(huge, huger)). We don't use usize/isize because the difference of
2593 // the i64/u64 might lie within their range.
2594 let bound = match self.state.to_i64() {
2596 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
2598 Some(Some(bound)) => bound.to_uint(),
2602 None => match self.state.to_u64() {
2604 let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
2606 Some(Some(bound)) => bound.to_uint(),
2615 Some(b) => (b, Some(b)),
2616 // Standard fallback for unbounded/unrepresentable bounds
2622 /// `Int` is required to ensure the range will be the same regardless of
2623 /// the direction it is consumed.
2624 #[unstable(feature = "core",
2625 reason = "will be replaced by range notation")]
2626 impl<A: Int + ToPrimitive> DoubleEndedIterator for Range<A> {
2628 fn next_back(&mut self) -> Option<A> {
2629 if self.stop > self.state {
2630 self.stop = self.stop - self.one;
2631 Some(self.stop.clone())
2638 /// An iterator over the range [start, stop]
2640 #[unstable(feature = "core",
2641 reason = "likely to be replaced by range notation and adapters")]
2642 pub struct RangeInclusive<A> {
2647 /// Return an iterator over the range [start, stop]
2649 #[unstable(feature = "core",
2650 reason = "likely to be replaced by range notation and adapters")]
2651 pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
2653 range: range(start, stop),
2658 #[unstable(feature = "core",
2659 reason = "likely to be replaced by range notation and adapters")]
2660 impl<A: Int + ToPrimitive> Iterator for RangeInclusive<A> {
2664 fn next(&mut self) -> Option<A> {
2665 match self.range.next() {
2668 if !self.done && self.range.state == self.range.stop {
2670 Some(self.range.stop.clone())
2679 fn size_hint(&self) -> (usize, Option<usize>) {
2680 let (lo, hi) = self.range.size_hint();
2684 let lo = lo.saturating_add(1);
2686 Some(x) => x.checked_add(1),
2694 #[unstable(feature = "core",
2695 reason = "likely to be replaced by range notation and adapters")]
2696 impl<A: Int + ToPrimitive> DoubleEndedIterator for RangeInclusive<A> {
2698 fn next_back(&mut self) -> Option<A> {
2699 if self.range.stop > self.range.state {
2700 let result = self.range.stop.clone();
2701 self.range.stop = self.range.stop - self.range.one;
2703 } else if !self.done && self.range.state == self.range.stop {
2705 Some(self.range.stop.clone())
2712 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2714 #[unstable(feature = "core",
2715 reason = "likely to be replaced by range notation and adapters")]
2716 pub struct RangeStep<A> {
2723 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2725 #[unstable(feature = "core",
2726 reason = "likely to be replaced by range notation and adapters")]
2727 pub fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
2728 let rev = step < Int::zero();
2729 RangeStep{state: start, stop: stop, step: step, rev: rev}
2732 #[unstable(feature = "core",
2733 reason = "likely to be replaced by range notation and adapters")]
2734 impl<A: Int> Iterator for RangeStep<A> {
2738 fn next(&mut self) -> Option<A> {
2739 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2740 let result = self.state;
2741 match self.state.checked_add(self.step) {
2742 Some(x) => self.state = x,
2743 None => self.state = self.stop.clone()
2752 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2754 #[unstable(feature = "core",
2755 reason = "likely to be replaced by range notation and adapters")]
2756 pub struct RangeStepInclusive<A> {
2764 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2766 #[unstable(feature = "core",
2767 reason = "likely to be replaced by range notation and adapters")]
2768 pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
2769 let rev = step < Int::zero();
2770 RangeStepInclusive {
2779 #[unstable(feature = "core",
2780 reason = "likely to be replaced by range notation and adapters")]
2781 impl<A: Int> Iterator for RangeStepInclusive<A> {
2785 fn next(&mut self) -> Option<A> {
2786 if !self.done && ((self.rev && self.state >= self.stop) ||
2787 (!self.rev && self.state <= self.stop)) {
2788 let result = self.state;
2789 match self.state.checked_add(self.step) {
2790 Some(x) => self.state = x,
2791 None => self.done = true
2800 macro_rules! range_exact_iter_impl {
2802 #[stable(feature = "rust1", since = "1.0.0")]
2803 impl ExactSizeIterator for ::ops::Range<$t> {
2805 fn len(&self) -> usize {
2806 debug_assert!(self.end >= self.start);
2807 (self.end - self.start) as usize
2813 #[stable(feature = "rust1", since = "1.0.0")]
2814 impl<A: Int> Iterator for ::ops::Range<A> {
2818 fn next(&mut self) -> Option<A> {
2819 if self.start < self.end {
2820 let result = self.start;
2821 self.start = self.start + Int::one();
2829 fn size_hint(&self) -> (usize, Option<usize>) {
2830 debug_assert!(self.end >= self.start);
2831 let hint = (self.end - self.start).to_uint();
2832 (hint.unwrap_or(0), hint)
2836 range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
2837 #[cfg(target_pointer_width = "64")]
2838 range_exact_iter_impl!(u64 i64);
2840 #[stable(feature = "rust1", since = "1.0.0")]
2841 impl<A: Int> DoubleEndedIterator for ::ops::Range<A> {
2843 fn next_back(&mut self) -> Option<A> {
2844 if self.start < self.end {
2845 self.end = self.end - Int::one();
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 impl<A: Int> Iterator for ::ops::RangeFrom<A> {
2858 fn next(&mut self) -> Option<A> {
2859 let result = self.start;
2860 self.start = self.start + Int::one();
2861 debug_assert!(result < self.start);
2866 /// An iterator that repeats an element endlessly
2868 #[stable(feature = "rust1", since = "1.0.0")]
2869 pub struct Repeat<A> {
2873 #[stable(feature = "rust1", since = "1.0.0")]
2874 impl<A: Clone> Iterator for Repeat<A> {
2878 fn next(&mut self) -> Option<A> { self.idx(0) }
2880 fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
2883 #[stable(feature = "rust1", since = "1.0.0")]
2884 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
2886 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2889 #[unstable(feature = "core", reason = "trait is experimental")]
2890 impl<A: Clone> RandomAccessIterator for Repeat<A> {
2892 fn indexable(&self) -> usize { usize::MAX }
2894 fn idx(&mut self, _: usize) -> Option<A> { Some(self.element.clone()) }
2897 type IterateState<T, F> = (F, Option<T>, bool);
2899 /// An iterator that repeatedly applies a given function, starting
2900 /// from a given seed value.
2901 #[unstable(feature = "core")]
2902 pub type Iterate<T, F> = Unfold<T, IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>;
2904 /// Create a new iterator that produces an infinite sequence of
2905 /// repeated applications of the given function `f`.
2906 #[unstable(feature = "core")]
2907 pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where
2911 fn next<T, F>(st: &mut IterateState<T, F>) -> Option<T> where
2915 let &mut (ref mut f, ref mut val, ref mut first) = st;
2921 *val = Some((*f)(x))
2929 // coerce to a fn pointer
2930 let next: fn(&mut IterateState<T,F>) -> Option<T> = next;
2932 Unfold::new((f, Some(seed), true), next)
2935 /// Create a new iterator that endlessly repeats the element `elt`.
2937 #[stable(feature = "rust1", since = "1.0.0")]
2938 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
2939 Repeat{element: elt}
2942 /// Functions for lexicographical ordering of sequences.
2944 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2945 /// that the elements implement both `PartialEq` and `PartialOrd`.
2947 /// If two sequences are equal up until the point where one ends,
2948 /// the shorter sequence compares less.
2949 #[unstable(feature = "core", reason = "needs review and revision")]
2952 use cmp::{Eq, Ord, PartialOrd, PartialEq};
2953 use cmp::Ordering::{Equal, Less, Greater};
2955 use option::Option::{Some, None};
2956 use super::Iterator;
2958 /// Compare `a` and `b` for equality using `Eq`
2959 pub fn equals<A, T, S>(mut a: T, mut b: S) -> bool where
2961 T: Iterator<Item=A>,
2962 S: Iterator<Item=A>,
2965 match (a.next(), b.next()) {
2966 (None, None) => return true,
2967 (None, _) | (_, None) => return false,
2968 (Some(x), Some(y)) => if x != y { return false },
2973 /// Order `a` and `b` lexicographically using `Ord`
2974 pub fn cmp<A, T, S>(mut a: T, mut b: S) -> cmp::Ordering where
2976 T: Iterator<Item=A>,
2977 S: Iterator<Item=A>,
2980 match (a.next(), b.next()) {
2981 (None, None) => return Equal,
2982 (None, _ ) => return Less,
2983 (_ , None) => return Greater,
2984 (Some(x), Some(y)) => match x.cmp(&y) {
2986 non_eq => return non_eq,
2992 /// Order `a` and `b` lexicographically using `PartialOrd`
2993 pub fn partial_cmp<A, T, S>(mut a: T, mut b: S) -> Option<cmp::Ordering> where
2995 T: Iterator<Item=A>,
2996 S: Iterator<Item=A>,
2999 match (a.next(), b.next()) {
3000 (None, None) => return Some(Equal),
3001 (None, _ ) => return Some(Less),
3002 (_ , None) => return Some(Greater),
3003 (Some(x), Some(y)) => match x.partial_cmp(&y) {
3005 non_eq => return non_eq,
3011 /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
3012 pub fn eq<A, B, L, R>(mut a: L, mut b: R) -> bool where
3014 L: Iterator<Item=A>,
3015 R: Iterator<Item=B>,
3018 match (a.next(), b.next()) {
3019 (None, None) => return true,
3020 (None, _) | (_, None) => return false,
3021 (Some(x), Some(y)) => if !x.eq(&y) { return false },
3026 /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`)
3027 pub fn ne<A, B, L, R>(mut a: L, mut b: R) -> bool where
3029 L: Iterator<Item=A>,
3030 R: Iterator<Item=B>,
3033 match (a.next(), b.next()) {
3034 (None, None) => return false,
3035 (None, _) | (_, None) => return true,
3036 (Some(x), Some(y)) => if x.ne(&y) { return true },
3041 /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`)
3042 pub fn lt<A, T, S>(mut a: T, mut b: S) -> bool where
3044 T: Iterator<Item=A>,
3045 S: Iterator<Item=A>,
3048 match (a.next(), b.next()) {
3049 (None, None) => return false,
3050 (None, _ ) => return true,
3051 (_ , None) => return false,
3052 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
3057 /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
3058 pub fn le<A, T, S>(mut a: T, mut b: S) -> bool where
3060 T: Iterator<Item=A>,
3061 S: Iterator<Item=A>,
3064 match (a.next(), b.next()) {
3065 (None, None) => return true,
3066 (None, _ ) => return true,
3067 (_ , None) => return false,
3068 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
3073 /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`)
3074 pub fn gt<A, T, S>(mut a: T, mut b: S) -> bool where
3076 T: Iterator<Item=A>,
3077 S: Iterator<Item=A>,
3080 match (a.next(), b.next()) {
3081 (None, None) => return false,
3082 (None, _ ) => return false,
3083 (_ , None) => return true,
3084 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
3089 /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
3090 pub fn ge<A, T, S>(mut a: T, mut b: S) -> bool where
3092 T: Iterator<Item=A>,
3093 S: Iterator<Item=A>,
3096 match (a.next(), b.next()) {
3097 (None, None) => return true,
3098 (None, _ ) => return false,
3099 (_ , None) => return true,
3100 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },