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![1i, 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.
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
89 /// Advance the iterator and return the next value. Return `None` when the end is reached.
91 fn next(&mut self) -> Option<Self::Item>;
93 /// Returns a lower and upper bound on the remaining length of the iterator.
95 /// An upper bound of `None` means either there is no known upper bound, or the upper bound
96 /// does not fit within a `uint`.
99 fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
102 // FIXME(#21363) remove `old_impl_check` when bug is fixed
104 impl<'a, T> Iterator for &'a mut (Iterator<Item=T> + 'a) {
107 fn next(&mut self) -> Option<T> {
112 /// Conversion from an `Iterator`
114 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
115 built from an iterator over elements of type `{A}`"]
116 pub trait FromIterator<A> {
117 /// Build a container with elements from an external iterator.
118 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> Self;
121 /// A type growable from an `Iterator` implementation
123 pub trait Extend<A> {
124 /// Extend a container with the elements yielded by an arbitrary iterator
126 fn extend<T: Iterator<Item=A>>(&mut self, iterator: T);
129 /// An extension trait providing numerous methods applicable to all iterators.
131 pub trait IteratorExt: Iterator + Sized {
132 /// Counts the number of elements in this iterator.
137 /// let a = [1i, 2, 3, 4, 5];
138 /// let mut it = a.iter();
139 /// assert!(it.count() == 5);
143 fn count(self) -> uint {
144 self.fold(0, |cnt, _x| cnt + 1)
147 /// Loops through the entire iterator, returning the last element of the
153 /// let a = [1i, 2, 3, 4, 5];
154 /// assert!(a.iter().last().unwrap() == &5);
158 fn last(mut self) -> Option<Self::Item> {
160 for x in self { last = Some(x); }
164 /// Loops through `n` iterations, returning the `n`th element of the
170 /// let a = [1i, 2, 3, 4, 5];
171 /// let mut it = a.iter();
172 /// assert!(it.nth(2).unwrap() == &3);
173 /// assert!(it.nth(2) == None);
177 fn nth(&mut self, mut n: uint) -> Option<Self::Item> {
179 if n == 0 { return Some(x) }
185 /// Chain this iterator with another, returning a new iterator that will
186 /// finish iterating over the current iterator, and then iterate
187 /// over the other specified iterator.
194 /// let mut it = a.iter().chain(b.iter());
195 /// assert_eq!(it.next().unwrap(), &0);
196 /// assert_eq!(it.next().unwrap(), &1);
197 /// assert!(it.next().is_none());
201 fn chain<U>(self, other: U) -> Chain<Self, U> where
202 U: Iterator<Item=Self::Item>,
204 Chain{a: self, b: other, flag: false}
207 /// Creates an iterator that iterates over both this and the specified
208 /// iterators simultaneously, yielding the two elements as pairs. When
209 /// either iterator returns None, all further invocations of next() will
217 /// let mut it = a.iter().zip(b.iter());
218 /// let (x0, x1) = (0i, 1i);
219 /// assert_eq!(it.next().unwrap(), (&x0, &x1));
220 /// assert!(it.next().is_none());
224 fn zip<B, U>(self, other: U) -> Zip<Self, U> where
227 Zip{a: self, b: other}
230 /// Creates a new iterator that will apply the specified function to each
231 /// element returned by the first, yielding the mapped element instead.
237 /// let mut it = a.iter().map(|&x| 2 * x);
238 /// assert_eq!(it.next().unwrap(), 2);
239 /// assert_eq!(it.next().unwrap(), 4);
240 /// assert!(it.next().is_none());
244 fn map<B, F>(self, f: F) -> Map<Self::Item, B, Self, F> where
245 F: FnMut(Self::Item) -> B,
247 Map{iter: self, f: f}
250 /// Creates an iterator that applies the predicate to each element returned
251 /// by this iterator. Only elements that have the predicate evaluate to
252 /// `true` will be yielded.
258 /// let mut it = a.iter().filter(|&x| *x > 1);
259 /// assert_eq!(it.next().unwrap(), &2);
260 /// assert!(it.next().is_none());
264 fn filter<P>(self, predicate: P) -> Filter<Self::Item, Self, P> where
265 P: FnMut(&Self::Item) -> bool,
267 Filter{iter: self, predicate: predicate}
270 /// Creates an iterator that both filters and maps elements.
271 /// If the specified function returns None, the element is skipped.
272 /// Otherwise the option is unwrapped and the new value is yielded.
278 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
279 /// assert_eq!(it.next().unwrap(), 4);
280 /// assert!(it.next().is_none());
284 fn filter_map<B, F>(self, f: F) -> FilterMap<Self::Item, B, Self, F> where
285 F: FnMut(Self::Item) -> Option<B>,
287 FilterMap { iter: self, f: f }
290 /// Creates an iterator that yields a pair of the value returned by this
291 /// iterator plus the current index of iteration.
296 /// let a = [100i, 200];
297 /// let mut it = a.iter().enumerate();
298 /// let (x100, x200) = (100i, 200i);
299 /// assert_eq!(it.next().unwrap(), (0, &x100));
300 /// assert_eq!(it.next().unwrap(), (1, &x200));
301 /// assert!(it.next().is_none());
305 fn enumerate(self) -> Enumerate<Self> {
306 Enumerate{iter: self, count: 0}
309 /// Creates an iterator that has a `.peek()` method
310 /// that returns an optional reference to the next element.
315 /// let xs = [100i, 200, 300];
316 /// let mut it = xs.iter().map(|x| *x).peekable();
317 /// assert_eq!(*it.peek().unwrap(), 100);
318 /// assert_eq!(it.next().unwrap(), 100);
319 /// assert_eq!(it.next().unwrap(), 200);
320 /// assert_eq!(*it.peek().unwrap(), 300);
321 /// assert_eq!(*it.peek().unwrap(), 300);
322 /// assert_eq!(it.next().unwrap(), 300);
323 /// assert!(it.peek().is_none());
324 /// assert!(it.next().is_none());
328 fn peekable(self) -> Peekable<Self::Item, Self> {
329 Peekable{iter: self, peeked: None}
332 /// Creates an iterator that invokes the predicate on elements
333 /// until it returns false. Once the predicate returns false, that
334 /// element and all further elements are yielded.
339 /// let a = [1i, 2, 3, 2, 1];
340 /// let mut it = a.iter().skip_while(|&a| *a < 3);
341 /// assert_eq!(it.next().unwrap(), &3);
342 /// assert_eq!(it.next().unwrap(), &2);
343 /// assert_eq!(it.next().unwrap(), &1);
344 /// assert!(it.next().is_none());
348 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self::Item, Self, P> where
349 P: FnMut(&Self::Item) -> bool,
351 SkipWhile{iter: self, flag: false, predicate: predicate}
354 /// Creates an iterator that yields elements so long as the predicate
355 /// returns true. After the predicate returns false for the first time, no
356 /// further elements will be yielded.
361 /// let a = [1i, 2, 3, 2, 1];
362 /// let mut it = a.iter().take_while(|&a| *a < 3);
363 /// assert_eq!(it.next().unwrap(), &1);
364 /// assert_eq!(it.next().unwrap(), &2);
365 /// assert!(it.next().is_none());
369 fn take_while<P>(self, predicate: P) -> TakeWhile<Self::Item, Self, P> where
370 P: FnMut(&Self::Item) -> bool,
372 TakeWhile{iter: self, flag: false, predicate: predicate}
375 /// Creates an iterator that skips the first `n` elements of this iterator,
376 /// and then yields all further items.
381 /// let a = [1i, 2, 3, 4, 5];
382 /// let mut it = a.iter().skip(3);
383 /// assert_eq!(it.next().unwrap(), &4);
384 /// assert_eq!(it.next().unwrap(), &5);
385 /// assert!(it.next().is_none());
389 fn skip(self, n: uint) -> Skip<Self> {
390 Skip{iter: self, n: n}
393 /// Creates an iterator that yields the first `n` elements of this
394 /// iterator, and then will always return None.
399 /// let a = [1i, 2, 3, 4, 5];
400 /// let mut it = a.iter().take(3);
401 /// assert_eq!(it.next().unwrap(), &1);
402 /// assert_eq!(it.next().unwrap(), &2);
403 /// assert_eq!(it.next().unwrap(), &3);
404 /// assert!(it.next().is_none());
408 fn take(self, n: uint) -> Take<Self> {
409 Take{iter: self, n: n}
412 /// Creates a new iterator that behaves in a similar fashion to fold.
413 /// There is a state which is passed between each iteration and can be
414 /// mutated as necessary. The yielded values from the closure are yielded
415 /// from the Scan instance when not None.
420 /// let a = [1i, 2, 3, 4, 5];
421 /// let mut it = a.iter().scan(1, |fac, &x| {
425 /// assert_eq!(it.next().unwrap(), 1);
426 /// assert_eq!(it.next().unwrap(), 2);
427 /// assert_eq!(it.next().unwrap(), 6);
428 /// assert_eq!(it.next().unwrap(), 24);
429 /// assert_eq!(it.next().unwrap(), 120);
430 /// assert!(it.next().is_none());
438 ) -> Scan<Self::Item, B, Self, St, F> where
439 F: FnMut(&mut St, Self::Item) -> Option<B>,
441 Scan{iter: self, f: f, state: initial_state}
444 /// Creates an iterator that maps each element to an iterator,
445 /// and yields the elements of the produced iterators
450 /// use std::iter::count;
452 /// let xs = [2u, 3];
453 /// let ys = [0u, 1, 0, 1, 2];
454 /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
455 /// // Check that `it` has the same elements as `ys`
458 /// assert_eq!(x, ys[i]);
464 fn flat_map<B, U, F>(self, f: F) -> FlatMap<Self::Item, B, Self, U, F> where
466 F: FnMut(Self::Item) -> U,
468 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
471 /// Creates an iterator that yields `None` forever after the underlying
472 /// iterator yields `None`. Random-access iterator behavior is not
473 /// affected, only single and double-ended iterator behavior.
478 /// fn process<U: Iterator<Item=int>>(it: U) -> int {
479 /// let mut it = it.fuse();
487 /// // did we exhaust the iterator?
488 /// if it.next().is_none() {
493 /// let x = vec![1i,2,3,7,8,9];
494 /// assert_eq!(process(x.into_iter()), 6);
495 /// let x = vec![1i,2,3];
496 /// assert_eq!(process(x.into_iter()), 1006);
500 fn fuse(self) -> Fuse<Self> {
501 Fuse{iter: self, done: false}
504 /// Creates an iterator that calls a function with a reference to each
505 /// element before yielding it. This is often useful for debugging an
506 /// iterator pipeline.
511 /// use std::iter::AdditiveIterator;
513 /// let xs = [1u, 4, 2, 3, 8, 9, 6];
514 /// let sum = xs.iter()
516 /// .inspect(|&x| println!("filtering {}", x))
517 /// .filter(|&x| x % 2 == 0)
518 /// .inspect(|&x| println!("{} made it through", x))
520 /// println!("{}", sum);
524 fn inspect<F>(self, f: F) -> Inspect<Self::Item, Self, F> where
525 F: FnMut(&Self::Item),
527 Inspect{iter: self, f: f}
530 /// Creates a wrapper around a mutable reference to the iterator.
532 /// This is useful to allow applying iterator adaptors while still
533 /// retaining ownership of the original iterator value.
538 /// let mut xs = range(0u, 10);
539 /// // sum the first five values
540 /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
541 /// assert!(partial_sum == 10);
542 /// // xs.next() is now `5`
543 /// assert!(xs.next() == Some(5));
546 fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
550 /// Loops through the entire iterator, collecting all of the elements into
551 /// a container implementing `FromIterator`.
556 /// let a = [1i, 2, 3, 4, 5];
557 /// let b: Vec<int> = a.iter().map(|&x| x).collect();
558 /// assert!(a.as_slice() == b.as_slice());
562 fn collect<B: FromIterator<Self::Item>>(self) -> B {
563 FromIterator::from_iter(self)
566 /// Loops through the entire iterator, collecting all of the elements into
567 /// one of two containers, depending on a predicate. The elements of the
568 /// first container satisfy the predicate, while the elements of the second
572 /// let vec = vec![1i, 2i, 3i, 4i];
573 /// let (even, odd): (Vec<int>, Vec<int>) = vec.into_iter().partition(|&n| n % 2 == 0);
574 /// assert_eq!(even, vec![2, 4]);
575 /// assert_eq!(odd, vec![1, 3]);
577 #[unstable = "recently added as part of collections reform"]
578 fn partition<B, F>(mut self, mut f: F) -> (B, B) where
579 B: Default + Extend<Self::Item>,
580 F: FnMut(&Self::Item) -> bool
582 let mut left: B = Default::default();
583 let mut right: B = Default::default();
587 left.extend(Some(x).into_iter())
589 right.extend(Some(x).into_iter())
596 /// Performs a fold operation over the entire iterator, returning the
597 /// eventual state at the end of the iteration.
602 /// let a = [1i, 2, 3, 4, 5];
603 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
607 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
608 F: FnMut(B, Self::Item) -> B,
610 let mut accum = init;
617 /// Tests whether the predicate holds true for all elements in the iterator.
622 /// let a = [1i, 2, 3, 4, 5];
623 /// assert!(a.iter().all(|x| *x > 0));
624 /// assert!(!a.iter().all(|x| *x > 2));
628 fn all<F>(mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
629 for x in self { if !f(x) { return false; } }
633 /// Tests whether any element of an iterator satisfies the specified
639 /// let a = [1i, 2, 3, 4, 5];
640 /// let mut it = a.iter();
641 /// assert!(it.any(|x| *x == 3));
642 /// assert!(!it.any(|x| *x == 3));
646 fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
647 for x in *self { if f(x) { return true; } }
651 /// Returns the first element satisfying the specified predicate.
653 /// Does not consume the iterator past the first found element.
656 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
657 P: FnMut(&Self::Item) -> bool,
660 if predicate(&x) { return Some(x) }
665 /// Return the index of the first element satisfying the specified predicate
668 fn position<P>(&mut self, mut predicate: P) -> Option<uint> where
669 P: FnMut(Self::Item) -> bool,
681 /// Return the index of the last element satisfying the specified predicate
683 /// If no element matches, None is returned.
686 fn rposition<P>(&mut self, mut predicate: P) -> Option<uint> where
687 P: FnMut(Self::Item) -> bool,
688 Self: ExactSizeIterator + DoubleEndedIterator
690 let len = self.len();
691 for i in range(0, len).rev() {
692 if predicate(self.next_back().expect("rposition: incorrect ExactSizeIterator")) {
699 /// Consumes the entire iterator to return the maximum element.
704 /// let a = [1i, 2, 3, 4, 5];
705 /// assert!(a.iter().max().unwrap() == &5);
709 fn max(self) -> Option<Self::Item> where Self::Item: Ord
711 self.fold(None, |max, x| {
714 Some(y) => Some(cmp::max(x, y))
719 /// Consumes the entire iterator to return the minimum element.
724 /// let a = [1i, 2, 3, 4, 5];
725 /// assert!(a.iter().min().unwrap() == &1);
729 fn min(self) -> Option<Self::Item> where Self::Item: Ord
731 self.fold(None, |min, x| {
734 Some(y) => Some(cmp::min(x, y))
739 /// `min_max` finds the minimum and maximum elements in the iterator.
741 /// The return type `MinMaxResult` is an enum of three variants:
743 /// - `NoElements` if the iterator is empty.
744 /// - `OneElement(x)` if the iterator has exactly one element.
745 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
746 /// values are equal if and only if there is more than one
747 /// element in the iterator and all elements are equal.
749 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
750 /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons.
755 /// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax};
757 /// let v: [int; 0] = [];
758 /// assert_eq!(v.iter().min_max(), NoElements);
761 /// assert!(v.iter().min_max() == OneElement(&1));
763 /// let v = [1i, 2, 3, 4, 5];
764 /// assert!(v.iter().min_max() == MinMax(&1, &5));
766 /// let v = [1i, 2, 3, 4, 5, 6];
767 /// assert!(v.iter().min_max() == MinMax(&1, &6));
769 /// let v = [1i, 1, 1, 1];
770 /// assert!(v.iter().min_max() == MinMax(&1, &1));
772 #[unstable = "return type may change"]
773 fn min_max(mut self) -> MinMaxResult<Self::Item> where Self::Item: Ord
775 let (mut min, mut max) = match self.next() {
776 None => return NoElements,
779 None => return OneElement(x),
780 Some(y) => if x < y {(x, y)} else {(y,x)}
786 // `first` and `second` are the two next elements we want to look at.
787 // We first compare `first` and `second` (#1). The smaller one is then compared to
788 // current minimum (#2). The larger one is compared to current maximum (#3). This
789 // way we do 3 comparisons for 2 elements.
790 let first = match self.next() {
794 let second = match self.next() {
798 } else if first > max {
806 if first < min {min = first;}
807 if max < second {max = second;}
809 if second < min {min = second;}
810 if max < first {max = first;}
817 /// Return the element that gives the maximum value from the
818 /// specified function.
823 /// use core::num::SignedInt;
825 /// let xs = [-3i, 0, 1, 5, -10];
826 /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
829 #[unstable = "may want to produce an Ordering directly; see #15311"]
830 fn max_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
831 F: FnMut(&Self::Item) -> B,
833 self.fold(None, |max: Option<(Self::Item, B)>, x| {
836 None => Some((x, x_val)),
837 Some((y, y_val)) => if x_val > y_val {
846 /// Return the element that gives the minimum value from the
847 /// specified function.
852 /// use core::num::SignedInt;
854 /// let xs = [-3i, 0, 1, 5, -10];
855 /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
858 #[unstable = "may want to produce an Ordering directly; see #15311"]
859 fn min_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
860 F: FnMut(&Self::Item) -> B,
862 self.fold(None, |min: Option<(Self::Item, B)>, x| {
865 None => Some((x, x_val)),
866 Some((y, y_val)) => if x_val < y_val {
875 /// Change the direction of the iterator
877 /// The flipped iterator swaps the ends on an iterator that can already
878 /// be iterated from the front and from the back.
881 /// If the iterator also implements RandomAccessIterator, the flipped
882 /// iterator is also random access, with the indices starting at the back
883 /// of the original iterator.
885 /// Note: Random access with flipped indices still only applies to the first
886 /// `uint::MAX` elements of the original iterator.
889 fn rev(self) -> Rev<Self> {
893 /// Converts an iterator of pairs into a pair of containers.
895 /// Loops through the entire iterator, collecting the first component of
896 /// each item into one new container, and the second component into another.
897 #[unstable = "recent addition"]
898 fn unzip<A, B, FromA, FromB>(mut self) -> (FromA, FromB) where
899 FromA: Default + Extend<A>,
900 FromB: Default + Extend<B>,
901 Self: Iterator<Item=(A, B)>,
903 struct SizeHint<A>(uint, Option<uint>);
904 impl<A> Iterator for SizeHint<A> {
907 fn next(&mut self) -> Option<A> { None }
908 fn size_hint(&self) -> (uint, Option<uint>) {
913 let (lo, hi) = self.size_hint();
914 let mut ts: FromA = Default::default();
915 let mut us: FromB = Default::default();
917 ts.extend(SizeHint(lo, hi));
918 us.extend(SizeHint(lo, hi));
921 ts.extend(Some(t).into_iter());
922 us.extend(Some(u).into_iter());
928 /// Creates an iterator that clones the elements it yields. Useful for converting an
929 /// Iterator<&T> to an Iterator<T>.
930 #[unstable = "recent addition"]
931 fn cloned<T, D>(self) -> Cloned<Self> where
932 Self: Iterator<Item=D>,
939 /// Repeats an iterator endlessly
944 /// use std::iter::count;
946 /// let a = count(1i,1i).take(1);
947 /// let mut cy = a.cycle();
948 /// assert_eq!(cy.next(), Some(1));
949 /// assert_eq!(cy.next(), Some(1));
953 fn cycle(self) -> Cycle<Self> where Self: Clone {
954 Cycle{orig: self.clone(), iter: self}
957 /// Use an iterator to reverse a container in place.
958 #[unstable = "uncertain about placement or widespread use"]
959 fn reverse_in_place<'a, T: 'a>(&mut self) where
960 Self: Iterator<Item=&'a mut T> + DoubleEndedIterator
963 match (self.next(), self.next_back()) {
964 (Some(x), Some(y)) => mem::swap(x, y),
972 impl<I> IteratorExt for I where I: Iterator {}
974 /// A range iterator able to yield elements from both ends
976 /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust
977 /// elements from the *same* range, and do not work independently of each other.
979 pub trait DoubleEndedIterator: Iterator {
980 /// Yield an element from the end of the range, returning `None` if the range is empty.
982 fn next_back(&mut self) -> Option<Self::Item>;
985 /// An object implementing random access indexing by `uint`
987 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
988 /// Calling `next()` or `next_back()` on a `RandomAccessIterator`
989 /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)`
990 /// after `it.next()` is called.
991 #[unstable = "not widely used, may be better decomposed into Index and ExactSizeIterator"]
992 pub trait RandomAccessIterator: Iterator {
993 /// Return the number of indexable elements. At most `std::uint::MAX`
994 /// elements are indexable, even if the iterator represents a longer range.
995 fn indexable(&self) -> uint;
997 /// Return an element at an index, or `None` if the index is out of bounds
998 fn idx(&mut self, index: uint) -> Option<Self::Item>;
1001 /// An iterator that knows its exact length
1003 /// This trait is a helper for iterators like the vector iterator, so that
1004 /// it can support double-ended enumeration.
1006 /// `Iterator::size_hint` *must* return the exact size of the iterator.
1007 /// Note that the size must fit in `uint`.
1009 pub trait ExactSizeIterator: Iterator {
1011 /// Return the exact length of the iterator.
1012 fn len(&self) -> uint {
1013 let (lower, upper) = self.size_hint();
1014 // Note: This assertion is overly defensive, but it checks the invariant
1015 // guaranteed by the trait. If this trait were rust-internal,
1016 // we could use debug_assert!; assert_eq! will check all Rust user
1017 // implementations too.
1018 assert_eq!(upper, Some(lower));
1023 // All adaptors that preserve the size of the wrapped iterator are fine
1024 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
1026 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1028 impl<A, I, F> ExactSizeIterator for Inspect<A, I, F> where
1029 I: ExactSizeIterator<Item=A>,
1033 impl<I> ExactSizeIterator for Rev<I> where I: ExactSizeIterator + DoubleEndedIterator {}
1035 impl<A, B, I, F> ExactSizeIterator for Map<A, B, I, F> where
1036 I: ExactSizeIterator<Item=A>,
1040 impl<A, B> ExactSizeIterator for Zip<A, B> where A: ExactSizeIterator, B: ExactSizeIterator {}
1042 /// An double-ended iterator with the direction inverted
1044 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1051 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
1052 type Item = <I as Iterator>::Item;
1055 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1057 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
1061 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
1063 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1066 #[unstable = "trait is experimental"]
1067 impl<I> RandomAccessIterator for Rev<I> where I: DoubleEndedIterator + RandomAccessIterator {
1069 fn indexable(&self) -> uint { self.iter.indexable() }
1071 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1072 let amt = self.indexable();
1073 self.iter.idx(amt - index - 1)
1077 /// A mutable reference to an iterator
1078 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1080 pub struct ByRef<'a, I:'a> {
1085 impl<'a, I> Iterator for ByRef<'a, I> where I: 'a + Iterator {
1086 type Item = <I as Iterator>::Item;
1089 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1091 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
1095 impl<'a, I> DoubleEndedIterator for ByRef<'a, I> where I: 'a + DoubleEndedIterator {
1097 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1100 /// A trait for iterators over elements which can be added together
1101 #[unstable = "needs to be re-evaluated as part of numerics reform"]
1102 pub trait AdditiveIterator<A> {
1103 /// Iterates over the entire iterator, summing up all the elements
1108 /// use std::iter::AdditiveIterator;
1110 /// let a = [1i, 2, 3, 4, 5];
1111 /// let mut it = a.iter().map(|&x| x);
1112 /// assert!(it.sum() == 15);
1117 macro_rules! impl_additive {
1118 ($A:ty, $init:expr) => {
1119 #[unstable = "trait is experimental"]
1120 impl<T: Iterator<Item=$A>> AdditiveIterator<$A> for T {
1122 fn sum(self) -> $A {
1123 self.fold($init, |acc, x| acc + x)
1128 impl_additive! { i8, 0 }
1129 impl_additive! { i16, 0 }
1130 impl_additive! { i32, 0 }
1131 impl_additive! { i64, 0 }
1132 impl_additive! { int, 0 }
1133 impl_additive! { u8, 0 }
1134 impl_additive! { u16, 0 }
1135 impl_additive! { u32, 0 }
1136 impl_additive! { u64, 0 }
1137 impl_additive! { uint, 0 }
1138 impl_additive! { f32, 0.0 }
1139 impl_additive! { f64, 0.0 }
1141 /// A trait for iterators over elements which can be multiplied together.
1142 #[unstable = "needs to be re-evaluated as part of numerics reform"]
1143 pub trait MultiplicativeIterator<A> {
1144 /// Iterates over the entire iterator, multiplying all the elements
1149 /// use std::iter::{count, MultiplicativeIterator};
1151 /// fn factorial(n: uint) -> uint {
1152 /// count(1u, 1).take_while(|&i| i <= n).product()
1154 /// assert!(factorial(0) == 1);
1155 /// assert!(factorial(1) == 1);
1156 /// assert!(factorial(5) == 120);
1158 fn product(self) -> A;
1161 macro_rules! impl_multiplicative {
1162 ($A:ty, $init:expr) => {
1163 #[unstable = "trait is experimental"]
1164 impl<T: Iterator<Item=$A>> MultiplicativeIterator<$A> for T {
1166 fn product(self) -> $A {
1167 self.fold($init, |acc, x| acc * x)
1172 impl_multiplicative! { i8, 1 }
1173 impl_multiplicative! { i16, 1 }
1174 impl_multiplicative! { i32, 1 }
1175 impl_multiplicative! { i64, 1 }
1176 impl_multiplicative! { int, 1 }
1177 impl_multiplicative! { u8, 1 }
1178 impl_multiplicative! { u16, 1 }
1179 impl_multiplicative! { u32, 1 }
1180 impl_multiplicative! { u64, 1 }
1181 impl_multiplicative! { uint, 1 }
1182 impl_multiplicative! { f32, 1.0 }
1183 impl_multiplicative! { f64, 1.0 }
1185 /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
1186 #[derive(Clone, PartialEq, Show)]
1187 #[unstable = "unclear whether such a fine-grained result is widely useful"]
1188 pub enum MinMaxResult<T> {
1192 /// Iterator with one element, so the minimum and maximum are the same
1195 /// More than one element in the iterator, the first element is not larger than the second
1199 impl<T: Clone> MinMaxResult<T> {
1200 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1201 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1202 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1203 /// performing this operation will make one clone of `x`.
1208 /// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
1210 /// let r: MinMaxResult<int> = NoElements;
1211 /// assert_eq!(r.into_option(), None);
1213 /// let r = OneElement(1i);
1214 /// assert_eq!(r.into_option(), Some((1,1)));
1216 /// let r = MinMax(1i,2i);
1217 /// assert_eq!(r.into_option(), Some((1,2)));
1219 #[unstable = "type is unstable"]
1220 pub fn into_option(self) -> Option<(T,T)> {
1223 OneElement(x) => Some((x.clone(), x)),
1224 MinMax(x, y) => Some((x, y))
1229 /// An iterator that clones the elements of an underlying iterator
1230 #[unstable = "recent addition"]
1231 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1233 pub struct Cloned<I> {
1238 impl<T, D, I> Iterator for Cloned<I> where
1241 I: Iterator<Item=D>,
1245 fn next(&mut self) -> Option<T> {
1246 self.it.next().cloned()
1249 fn size_hint(&self) -> (uint, Option<uint>) {
1255 impl<T, D, I> DoubleEndedIterator for Cloned<I> where
1258 I: DoubleEndedIterator<Item=D>,
1260 fn next_back(&mut self) -> Option<T> {
1261 self.it.next_back().cloned()
1266 impl<T, D, I> ExactSizeIterator for Cloned<I> where
1269 I: ExactSizeIterator<Item=D>,
1272 /// An iterator that repeats endlessly
1273 #[derive(Clone, Copy)]
1274 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1276 pub struct Cycle<I> {
1282 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
1283 type Item = <I as Iterator>::Item;
1286 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1287 match self.iter.next() {
1288 None => { self.iter = self.orig.clone(); self.iter.next() }
1294 fn size_hint(&self) -> (uint, Option<uint>) {
1295 // the cycle iterator is either empty or infinite
1296 match self.orig.size_hint() {
1297 sz @ (0, Some(0)) => sz,
1298 (0, _) => (0, None),
1299 _ => (uint::MAX, None)
1304 #[unstable = "trait is experimental"]
1305 impl<I> RandomAccessIterator for Cycle<I> where
1306 I: Clone + RandomAccessIterator,
1309 fn indexable(&self) -> uint {
1310 if self.orig.indexable() > 0 {
1318 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1319 let liter = self.iter.indexable();
1320 let lorig = self.orig.indexable();
1323 } else if index < liter {
1324 self.iter.idx(index)
1326 self.orig.idx((index - liter) % lorig)
1331 /// An iterator that strings two iterators together
1333 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1335 pub struct Chain<A, B> {
1342 impl<T, A, B> Iterator for Chain<A, B> where A: Iterator<Item=T>, B: Iterator<Item=T> {
1346 fn next(&mut self) -> Option<T> {
1350 match self.a.next() {
1351 Some(x) => return Some(x),
1360 fn size_hint(&self) -> (uint, Option<uint>) {
1361 let (a_lower, a_upper) = self.a.size_hint();
1362 let (b_lower, b_upper) = self.b.size_hint();
1364 let lower = a_lower.saturating_add(b_lower);
1366 let upper = match (a_upper, b_upper) {
1367 (Some(x), Some(y)) => x.checked_add(y),
1376 impl<T, A, B> DoubleEndedIterator for Chain<A, B> where
1377 A: DoubleEndedIterator<Item=T>,
1378 B: DoubleEndedIterator<Item=T>,
1381 fn next_back(&mut self) -> Option<T> {
1382 match self.b.next_back() {
1384 None => self.a.next_back()
1389 #[unstable = "trait is experimental"]
1390 impl<T, A, B> RandomAccessIterator for Chain<A, B> where
1391 A: RandomAccessIterator<Item=T>,
1392 B: RandomAccessIterator<Item=T>,
1395 fn indexable(&self) -> uint {
1396 let (a, b) = (self.a.indexable(), self.b.indexable());
1401 fn idx(&mut self, index: uint) -> Option<T> {
1402 let len = self.a.indexable();
1406 self.b.idx(index - len)
1411 /// An iterator that iterates two other iterators simultaneously
1413 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1415 pub struct Zip<A, B> {
1421 impl<T, U, A, B> Iterator for Zip<A, B> where
1422 A: Iterator<Item = T>,
1423 B: Iterator<Item = U>,
1428 fn next(&mut self) -> Option<(T, U)> {
1429 match self.a.next() {
1431 Some(x) => match self.b.next() {
1433 Some(y) => Some((x, y))
1439 fn size_hint(&self) -> (uint, Option<uint>) {
1440 let (a_lower, a_upper) = self.a.size_hint();
1441 let (b_lower, b_upper) = self.b.size_hint();
1443 let lower = cmp::min(a_lower, b_lower);
1445 let upper = match (a_upper, b_upper) {
1446 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1447 (Some(x), None) => Some(x),
1448 (None, Some(y)) => Some(y),
1449 (None, None) => None
1457 impl<T, U, A, B> DoubleEndedIterator for Zip<A, B> where
1458 A: DoubleEndedIterator + ExactSizeIterator<Item=T>,
1459 B: DoubleEndedIterator + ExactSizeIterator<Item=U>,
1462 fn next_back(&mut self) -> Option<(T, U)> {
1463 let a_sz = self.a.len();
1464 let b_sz = self.b.len();
1466 // Adjust a, b to equal length
1468 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1470 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1473 match (self.a.next_back(), self.b.next_back()) {
1474 (Some(x), Some(y)) => Some((x, y)),
1475 (None, None) => None,
1476 _ => unreachable!(),
1481 #[unstable = "trait is experimental"]
1482 impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where
1483 A: RandomAccessIterator<Item=T>,
1484 B: RandomAccessIterator<Item=U>,
1487 fn indexable(&self) -> uint {
1488 cmp::min(self.a.indexable(), self.b.indexable())
1492 fn idx(&mut self, index: uint) -> Option<(T, U)> {
1493 match self.a.idx(index) {
1495 Some(x) => match self.b.idx(index) {
1497 Some(y) => Some((x, y))
1503 /// An iterator that maps the values of `iter` with `f`
1504 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1506 pub struct Map<A, B, I: Iterator<Item=A>, F: FnMut(A) -> B> {
1511 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1513 impl<A, B, I, F> Clone for Map<A, B, I, F> where
1514 I: Clone + Iterator<Item=A>,
1515 F: Clone + FnMut(A) -> B,
1517 fn clone(&self) -> Map<A, B, I, F> {
1519 iter: self.iter.clone(),
1525 impl<A, B, I, F> Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1527 fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1529 Some(a) => Some((self.f)(a)),
1536 impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1540 fn next(&mut self) -> Option<B> {
1541 let next = self.iter.next();
1546 fn size_hint(&self) -> (uint, Option<uint>) {
1547 self.iter.size_hint()
1552 impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where
1553 I: DoubleEndedIterator<Item=A>,
1557 fn next_back(&mut self) -> Option<B> {
1558 let next = self.iter.next_back();
1563 #[unstable = "trait is experimental"]
1564 impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where
1565 I: RandomAccessIterator<Item=A>,
1569 fn indexable(&self) -> uint {
1570 self.iter.indexable()
1574 fn idx(&mut self, index: uint) -> Option<B> {
1575 let elt = self.iter.idx(index);
1580 /// An iterator that filters the elements of `iter` with `predicate`
1581 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1583 pub struct Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1588 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1590 impl<A, I, P> Clone for Filter<A, I, P> where
1591 I: Clone + Iterator<Item=A>,
1592 P: Clone + FnMut(&A) -> bool,
1594 fn clone(&self) -> Filter<A, I, P> {
1596 iter: self.iter.clone(),
1597 predicate: self.predicate.clone(),
1603 impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1607 fn next(&mut self) -> Option<A> {
1608 for x in self.iter {
1609 if (self.predicate)(&x) {
1619 fn size_hint(&self) -> (uint, Option<uint>) {
1620 let (_, upper) = self.iter.size_hint();
1621 (0, upper) // can't know a lower bound, due to the predicate
1626 impl<A, I, P> DoubleEndedIterator for Filter<A, I, P> where
1627 I: DoubleEndedIterator<Item=A>,
1628 P: FnMut(&A) -> bool,
1631 fn next_back(&mut self) -> Option<A> {
1632 for x in self.iter.by_ref().rev() {
1633 if (self.predicate)(&x) {
1641 /// An iterator that uses `f` to both filter and map elements from `iter`
1642 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1644 pub struct FilterMap<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> Option<B> {
1649 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1651 impl<A, B, I, F> Clone for FilterMap<A, B, I, F> where
1652 I: Clone + Iterator<Item=A>,
1653 F: Clone + FnMut(A) -> Option<B>,
1655 fn clone(&self) -> FilterMap<A, B, I, F> {
1657 iter: self.iter.clone(),
1664 impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where
1665 I: Iterator<Item=A>,
1666 F: FnMut(A) -> Option<B>,
1671 fn next(&mut self) -> Option<B> {
1672 for x in self.iter {
1674 Some(y) => return Some(y),
1682 fn size_hint(&self) -> (uint, Option<uint>) {
1683 let (_, upper) = self.iter.size_hint();
1684 (0, upper) // can't know a lower bound, due to the predicate
1689 impl<A, B, I, F> DoubleEndedIterator for FilterMap<A, B, I, F> where
1690 I: DoubleEndedIterator<Item=A>,
1691 F: FnMut(A) -> Option<B>,
1694 fn next_back(&mut self) -> Option<B> {
1695 for x in self.iter.by_ref().rev() {
1697 Some(y) => return Some(y),
1705 /// An iterator that yields the current count and the element during iteration
1707 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1709 pub struct Enumerate<I> {
1715 impl<I> Iterator for Enumerate<I> where I: Iterator {
1716 type Item = (uint, <I as Iterator>::Item);
1719 fn next(&mut self) -> Option<(uint, <I as Iterator>::Item)> {
1720 match self.iter.next() {
1722 let ret = Some((self.count, a));
1731 fn size_hint(&self) -> (uint, Option<uint>) {
1732 self.iter.size_hint()
1737 impl<I> DoubleEndedIterator for Enumerate<I> where
1738 I: ExactSizeIterator + DoubleEndedIterator
1741 fn next_back(&mut self) -> Option<(uint, <I as Iterator>::Item)> {
1742 match self.iter.next_back() {
1744 let len = self.iter.len();
1745 Some((self.count + len, a))
1752 #[unstable = "trait is experimental"]
1753 impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator {
1755 fn indexable(&self) -> uint {
1756 self.iter.indexable()
1760 fn idx(&mut self, index: uint) -> Option<(uint, <I as Iterator>::Item)> {
1761 match self.iter.idx(index) {
1762 Some(a) => Some((self.count + index, a)),
1768 /// An iterator with a `peek()` that returns an optional reference to the next element.
1769 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1772 pub struct Peekable<T, I> where I: Iterator<Item=T> {
1778 impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> {
1782 fn next(&mut self) -> Option<T> {
1783 if self.peeked.is_some() { self.peeked.take() }
1784 else { self.iter.next() }
1788 fn size_hint(&self) -> (uint, Option<uint>) {
1789 let (lo, hi) = self.iter.size_hint();
1790 if self.peeked.is_some() {
1791 let lo = lo.saturating_add(1);
1793 Some(x) => x.checked_add(1),
1804 impl<T, I> Peekable<T, I> where I: Iterator<Item=T> {
1805 /// Return a reference to the next element of the iterator with out advancing it,
1806 /// or None if the iterator is exhausted.
1808 pub fn peek(&mut self) -> Option<&T> {
1809 if self.peeked.is_none() {
1810 self.peeked = self.iter.next();
1813 Some(ref value) => Some(value),
1818 /// Check whether peekable iterator is empty or not.
1820 pub fn is_empty(&mut self) -> bool {
1821 self.peek().is_none()
1825 /// An iterator that rejects elements while `predicate` is true
1826 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1828 pub struct SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1834 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1836 impl<A, I, P> Clone for SkipWhile<A, I, P> where
1837 I: Clone + Iterator<Item=A>,
1838 P: Clone + FnMut(&A) -> bool,
1840 fn clone(&self) -> SkipWhile<A, I, P> {
1842 iter: self.iter.clone(),
1844 predicate: self.predicate.clone(),
1850 impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1854 fn next(&mut self) -> Option<A> {
1855 for x in self.iter {
1856 if self.flag || !(self.predicate)(&x) {
1865 fn size_hint(&self) -> (uint, Option<uint>) {
1866 let (_, upper) = self.iter.size_hint();
1867 (0, upper) // can't know a lower bound, due to the predicate
1871 /// An iterator that only accepts elements while `predicate` is true
1872 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1874 pub struct TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1880 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1882 impl<A, I, P> Clone for TakeWhile<A, I, P> where
1883 I: Clone + Iterator<Item=A>,
1884 P: Clone + FnMut(&A) -> bool,
1886 fn clone(&self) -> TakeWhile<A, I, P> {
1888 iter: self.iter.clone(),
1890 predicate: self.predicate.clone(),
1896 impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1900 fn next(&mut self) -> Option<A> {
1904 match self.iter.next() {
1906 if (self.predicate)(&x) {
1919 fn size_hint(&self) -> (uint, Option<uint>) {
1920 let (_, upper) = self.iter.size_hint();
1921 (0, upper) // can't know a lower bound, due to the predicate
1925 /// An iterator that skips over `n` elements of `iter`.
1927 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1929 pub struct Skip<I> {
1935 impl<I> Iterator for Skip<I> where I: Iterator {
1936 type Item = <I as Iterator>::Item;
1939 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1940 let mut next = self.iter.next();
1949 next = self.iter.next();
1964 fn size_hint(&self) -> (uint, Option<uint>) {
1965 let (lower, upper) = self.iter.size_hint();
1967 let lower = lower.saturating_sub(self.n);
1969 let upper = match upper {
1970 Some(x) => Some(x.saturating_sub(self.n)),
1978 #[unstable = "trait is experimental"]
1979 impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{
1981 fn indexable(&self) -> uint {
1982 self.iter.indexable().saturating_sub(self.n)
1986 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1987 if index >= self.indexable() {
1990 self.iter.idx(index + self.n)
1995 /// An iterator that only iterates over the first `n` iterations of `iter`.
1997 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1999 pub struct Take<I> {
2005 impl<I> Iterator for Take<I> where I: Iterator{
2006 type Item = <I as Iterator>::Item;
2009 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2019 fn size_hint(&self) -> (uint, Option<uint>) {
2020 let (lower, upper) = self.iter.size_hint();
2022 let lower = cmp::min(lower, self.n);
2024 let upper = match upper {
2025 Some(x) if x < self.n => Some(x),
2033 #[unstable = "trait is experimental"]
2034 impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{
2036 fn indexable(&self) -> uint {
2037 cmp::min(self.iter.indexable(), self.n)
2041 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
2042 if index >= self.n {
2045 self.iter.idx(index)
2051 /// An iterator to maintain state while iterating another iterator
2052 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2054 pub struct Scan<A, B, I, St, F> where I: Iterator, F: FnMut(&mut St, A) -> Option<B> {
2058 /// The current internal state to be passed to the closure next.
2062 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2064 impl<A, B, I, St, F> Clone for Scan<A, B, I, St, F> where
2065 I: Clone + Iterator<Item=A>,
2067 F: Clone + FnMut(&mut St, A) -> Option<B>,
2069 fn clone(&self) -> Scan<A, B, I, St, F> {
2071 iter: self.iter.clone(),
2073 state: self.state.clone(),
2079 impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where
2080 I: Iterator<Item=A>,
2081 F: FnMut(&mut St, A) -> Option<B>,
2086 fn next(&mut self) -> Option<B> {
2087 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2091 fn size_hint(&self) -> (uint, Option<uint>) {
2092 let (_, upper) = self.iter.size_hint();
2093 (0, upper) // can't know a lower bound, due to the scan function
2097 /// An iterator that maps each element to an iterator,
2098 /// and yields the elements of the produced iterators
2100 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2102 pub struct FlatMap<A, B, I, U, F> where
2103 I: Iterator<Item=A>,
2104 U: Iterator<Item=B>,
2109 frontiter: Option<U>,
2110 backiter: Option<U>,
2113 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2115 impl<A, B, I, U, F> Clone for FlatMap<A, B, I, U, F> where
2116 I: Clone + Iterator<Item=A>,
2117 U: Clone + Iterator<Item=B>,
2118 F: Clone + FnMut(A) -> U,
2120 fn clone(&self) -> FlatMap<A, B, I, U, F> {
2122 iter: self.iter.clone(),
2124 frontiter: self.frontiter.clone(),
2125 backiter: self.backiter.clone(),
2131 impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where
2132 I: Iterator<Item=A>,
2133 U: Iterator<Item=B>,
2139 fn next(&mut self) -> Option<B> {
2141 for inner in self.frontiter.iter_mut() {
2146 match self.iter.next().map(|x| (self.f)(x)) {
2147 None => return self.backiter.as_mut().and_then(|it| it.next()),
2148 next => self.frontiter = next,
2154 fn size_hint(&self) -> (uint, Option<uint>) {
2155 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2156 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2157 let lo = flo.saturating_add(blo);
2158 match (self.iter.size_hint(), fhi, bhi) {
2159 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2166 impl<A, B, I, U, F> DoubleEndedIterator for FlatMap<A, B, I, U, F> where
2167 I: DoubleEndedIterator<Item=A>,
2168 U: DoubleEndedIterator<Item=B>,
2172 fn next_back(&mut self) -> Option<B> {
2174 for inner in self.backiter.iter_mut() {
2175 match inner.next_back() {
2180 match self.iter.next_back().map(|x| (self.f)(x)) {
2181 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2182 next => self.backiter = next,
2188 /// An iterator that yields `None` forever after the underlying iterator
2189 /// yields `None` once.
2191 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2193 pub struct Fuse<I> {
2199 impl<I> Iterator for Fuse<I> where I: Iterator {
2200 type Item = <I as Iterator>::Item;
2203 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2207 match self.iter.next() {
2218 fn size_hint(&self) -> (uint, Option<uint>) {
2222 self.iter.size_hint()
2228 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2230 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2234 match self.iter.next_back() {
2245 // Allow RandomAccessIterators to be fused without affecting random-access behavior
2246 #[unstable = "trait is experimental"]
2247 impl<I> RandomAccessIterator for Fuse<I> where I: RandomAccessIterator {
2249 fn indexable(&self) -> uint {
2250 self.iter.indexable()
2254 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
2255 self.iter.idx(index)
2260 /// Resets the fuse such that the next call to .next() or .next_back() will
2261 /// call the underlying iterator again even if it previously returned None.
2263 #[unstable = "seems marginal"]
2264 pub fn reset_fuse(&mut self) {
2269 /// An iterator that calls a function with a reference to each
2270 /// element before yielding it.
2271 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2273 pub struct Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2278 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2280 impl<A, I, F> Clone for Inspect<A, I, F> where
2281 I: Clone + Iterator<Item=A>,
2282 F: Clone + FnMut(&A),
2284 fn clone(&self) -> Inspect<A, I, F> {
2286 iter: self.iter.clone(),
2292 impl<A, I, F> Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2294 fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
2296 Some(ref a) => (self.f)(a),
2305 impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2309 fn next(&mut self) -> Option<A> {
2310 let next = self.iter.next();
2311 self.do_inspect(next)
2315 fn size_hint(&self) -> (uint, Option<uint>) {
2316 self.iter.size_hint()
2321 impl<A, I, F> DoubleEndedIterator for Inspect<A, I, F> where
2322 I: DoubleEndedIterator<Item=A>,
2326 fn next_back(&mut self) -> Option<A> {
2327 let next = self.iter.next_back();
2328 self.do_inspect(next)
2332 #[unstable = "trait is experimental"]
2333 impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where
2334 I: RandomAccessIterator<Item=A>,
2338 fn indexable(&self) -> uint {
2339 self.iter.indexable()
2343 fn idx(&mut self, index: uint) -> Option<A> {
2344 let element = self.iter.idx(index);
2345 self.do_inspect(element)
2349 /// An iterator that passes mutable state to a closure and yields the result.
2351 /// # Example: The Fibonacci Sequence
2353 /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2356 /// use std::iter::Unfold;
2357 /// use std::num::Int; // For `.checked_add()`
2359 /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2360 /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2361 /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| {
2362 /// // Attempt to get the next Fibonacci number
2363 /// // `x1` will be `None` if previously overflowed.
2364 /// let next = match (*x2, *x1) {
2365 /// (Some(x2), Some(x1)) => x2.checked_add(x1),
2369 /// // Shift left: ret <- x2 <- x1 <- next
2377 /// for i in fibonacci {
2378 /// println!("{}", i);
2382 pub struct Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2384 /// Internal state that will be passed to the closure on the next iteration
2388 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2390 impl<A, St, F> Clone for Unfold<A, St, F> where
2391 F: Clone + FnMut(&mut St) -> Option<A>,
2394 fn clone(&self) -> Unfold<A, St, F> {
2397 state: self.state.clone(),
2403 impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2404 /// Creates a new iterator with the specified closure as the "iterator
2405 /// function" and an initial state to eventually pass to the closure
2407 pub fn new(initial_state: St, f: F) -> Unfold<A, St, F> {
2410 state: initial_state
2416 impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2420 fn next(&mut self) -> Option<A> {
2421 (self.f)(&mut self.state)
2425 fn size_hint(&self) -> (uint, Option<uint>) {
2426 // no possible known bounds at this point
2431 /// An infinite iterator starting at `start` and advancing by `step` with each
2433 #[derive(Clone, Copy)]
2434 #[unstable = "may be renamed or replaced by range notation adapaters"]
2435 pub struct Counter<A> {
2436 /// The current state the counter is at (next value to be yielded)
2438 /// The amount that this iterator is stepping by
2442 /// Creates a new counter with the specified start/step
2444 #[unstable = "may be renamed or replaced by range notation adapaters"]
2445 pub fn count<A>(start: A, step: A) -> Counter<A> {
2446 Counter{state: start, step: step}
2450 impl<A: Add<Output=A> + Clone> Iterator for Counter<A> {
2454 fn next(&mut self) -> Option<A> {
2455 let result = self.state.clone();
2456 self.state = self.state.clone() + self.step.clone();
2461 fn size_hint(&self) -> (uint, Option<uint>) {
2462 (uint::MAX, None) // Too bad we can't specify an infinite lower bound
2466 /// An iterator over the range [start, stop)
2467 #[derive(Clone, Copy)]
2468 #[unstable = "will be replaced by range notation"]
2469 pub struct Range<A> {
2475 /// Returns an iterator over the given range [start, stop) (that is, starting
2476 /// at start (inclusive), and ending at stop (exclusive)).
2481 /// let array = [0, 1, 2, 3, 4];
2483 /// for i in range(0, 5u) {
2484 /// println!("{}", i);
2485 /// assert_eq!(i, array[i]);
2489 #[unstable = "will be replaced by range notation"]
2490 pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
2498 // FIXME: #10414: Unfortunate type bound
2499 #[unstable = "will be replaced by range notation"]
2500 impl<A: Int + ToPrimitive> Iterator for Range<A> {
2504 fn next(&mut self) -> Option<A> {
2505 if self.state < self.stop {
2506 let result = self.state.clone();
2507 self.state = self.state + self.one;
2515 fn size_hint(&self) -> (uint, Option<uint>) {
2516 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
2517 // handle cases like range(huge, huger)). We don't use uint/int because the difference of
2518 // the i64/u64 might lie within their range.
2519 let bound = match self.state.to_i64() {
2521 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
2523 Some(Some(bound)) => bound.to_uint(),
2527 None => match self.state.to_u64() {
2529 let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
2531 Some(Some(bound)) => bound.to_uint(),
2540 Some(b) => (b, Some(b)),
2541 // Standard fallback for unbounded/unrepresentable bounds
2547 /// `Int` is required to ensure the range will be the same regardless of
2548 /// the direction it is consumed.
2549 #[unstable = "will be replaced by range notation"]
2550 impl<A: Int + ToPrimitive> DoubleEndedIterator for Range<A> {
2552 fn next_back(&mut self) -> Option<A> {
2553 if self.stop > self.state {
2554 self.stop = self.stop - self.one;
2555 Some(self.stop.clone())
2562 /// An iterator over the range [start, stop]
2564 #[unstable = "likely to be replaced by range notation and adapters"]
2565 pub struct RangeInclusive<A> {
2570 /// Return an iterator over the range [start, stop]
2572 #[unstable = "likely to be replaced by range notation and adapters"]
2573 pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
2575 range: range(start, stop),
2580 #[unstable = "likely to be replaced by range notation and adapters"]
2581 impl<A: Int + ToPrimitive> Iterator for RangeInclusive<A> {
2585 fn next(&mut self) -> Option<A> {
2586 match self.range.next() {
2589 if !self.done && self.range.state == self.range.stop {
2591 Some(self.range.stop.clone())
2600 fn size_hint(&self) -> (uint, Option<uint>) {
2601 let (lo, hi) = self.range.size_hint();
2605 let lo = lo.saturating_add(1);
2607 Some(x) => x.checked_add(1),
2615 #[unstable = "likely to be replaced by range notation and adapters"]
2616 impl<A: Int + ToPrimitive> DoubleEndedIterator for RangeInclusive<A> {
2618 fn next_back(&mut self) -> Option<A> {
2619 if self.range.stop > self.range.state {
2620 let result = self.range.stop.clone();
2621 self.range.stop = self.range.stop - self.range.one;
2623 } else if !self.done && self.range.state == self.range.stop {
2625 Some(self.range.stop.clone())
2632 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2634 #[unstable = "likely to be replaced by range notation and adapters"]
2635 pub struct RangeStep<A> {
2642 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2644 #[unstable = "likely to be replaced by range notation and adapters"]
2645 pub fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
2646 let rev = step < Int::zero();
2647 RangeStep{state: start, stop: stop, step: step, rev: rev}
2650 #[unstable = "likely to be replaced by range notation and adapters"]
2651 impl<A: Int> Iterator for RangeStep<A> {
2655 fn next(&mut self) -> Option<A> {
2656 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2657 let result = self.state;
2658 match self.state.checked_add(self.step) {
2659 Some(x) => self.state = x,
2660 None => self.state = self.stop.clone()
2669 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2671 #[unstable = "likely to be replaced by range notation and adapters"]
2672 pub struct RangeStepInclusive<A> {
2680 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2682 #[unstable = "likely to be replaced by range notation and adapters"]
2683 pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
2684 let rev = step < Int::zero();
2685 RangeStepInclusive {
2694 #[unstable = "likely to be replaced by range notation and adapters"]
2695 impl<A: Int> Iterator for RangeStepInclusive<A> {
2699 fn next(&mut self) -> Option<A> {
2700 if !self.done && ((self.rev && self.state >= self.stop) ||
2701 (!self.rev && self.state <= self.stop)) {
2702 let result = self.state;
2703 match self.state.checked_add(self.step) {
2704 Some(x) => self.state = x,
2705 None => self.done = true
2715 /// The `Step` trait identifies objects which can be stepped over in both
2716 /// directions. The `steps_between` function provides a way to
2717 /// compare two Step objects (it could be provided using `step()` and `Ord`,
2718 /// but the implementation would be so inefficient as to be useless).
2719 #[unstable = "design of range notation/iteration is in flux"]
2720 pub trait Step: Ord {
2721 /// Change self to the next object.
2723 /// Change self to the previous object.
2724 fn step_back(&mut self);
2725 /// The steps_between two step objects.
2726 /// start should always be less than end, so the result should never be negative.
2727 /// Return None if it is not possible to calculate steps_between without
2729 fn steps_between(start: &Self, end: &Self) -> Option<uint>;
2732 macro_rules! step_impl {
2734 #[unstable = "Trait is unstable."]
2737 fn step(&mut self) { *self += 1; }
2739 fn step_back(&mut self) { *self -= 1; }
2741 fn steps_between(start: &$t, end: &$t) -> Option<uint> {
2742 debug_assert!(end >= start);
2743 Some((*end - *start) as uint)
2749 macro_rules! step_impl_no_between {
2751 #[unstable = "Trait is unstable."]
2754 fn step(&mut self) { *self += 1; }
2756 fn step_back(&mut self) { *self -= 1; }
2758 fn steps_between(_start: &$t, _end: &$t) -> Option<uint> {
2765 step_impl!(uint u8 u16 u32 int i8 i16 i32);
2766 #[cfg(target_pointer_width = "64")]
2767 step_impl!(u64 i64);
2768 #[cfg(target_pointer_width = "32")]
2769 step_impl_no_between!(u64 i64);
2772 /// An iterator that repeats an element endlessly
2775 pub struct Repeat<A> {
2780 impl<A: Clone> Iterator for Repeat<A> {
2784 fn next(&mut self) -> Option<A> { self.idx(0) }
2786 fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2790 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
2792 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2795 #[unstable = "trait is experimental"]
2796 impl<A: Clone> RandomAccessIterator for Repeat<A> {
2798 fn indexable(&self) -> uint { uint::MAX }
2800 fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
2803 type IterateState<T, F> = (F, Option<T>, bool);
2805 /// An iterator that repeatedly applies a given function, starting
2806 /// from a given seed value.
2808 pub type Iterate<T, F> = Unfold<T, IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>;
2810 /// Create a new iterator that produces an infinite sequence of
2811 /// repeated applications of the given function `f`.
2813 pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where
2817 fn next<T, F>(st: &mut IterateState<T, F>) -> Option<T> where
2821 let &mut (ref mut f, ref mut val, ref mut first) = st;
2827 *val = Some((*f)(x))
2835 // coerce to a fn pointer
2836 let next: fn(&mut IterateState<T,F>) -> Option<T> = next;
2838 Unfold::new((f, Some(seed), true), next)
2841 /// Create a new iterator that endlessly repeats the element `elt`.
2844 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
2845 Repeat{element: elt}
2848 /// Functions for lexicographical ordering of sequences.
2850 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2851 /// that the elements implement both `PartialEq` and `PartialOrd`.
2853 /// If two sequences are equal up until the point where one ends,
2854 /// the shorter sequence compares less.
2855 #[unstable = "needs review and revision"]
2858 use cmp::{Eq, Ord, PartialOrd, PartialEq};
2859 use cmp::Ordering::{Equal, Less, Greater};
2861 use option::Option::{Some, None};
2862 use super::Iterator;
2864 /// Compare `a` and `b` for equality using `Eq`
2865 pub fn equals<A, T, S>(mut a: T, mut b: S) -> bool where
2867 T: Iterator<Item=A>,
2868 S: Iterator<Item=A>,
2871 match (a.next(), b.next()) {
2872 (None, None) => return true,
2873 (None, _) | (_, None) => return false,
2874 (Some(x), Some(y)) => if x != y { return false },
2879 /// Order `a` and `b` lexicographically using `Ord`
2880 pub fn cmp<A, T, S>(mut a: T, mut b: S) -> cmp::Ordering where
2882 T: Iterator<Item=A>,
2883 S: Iterator<Item=A>,
2886 match (a.next(), b.next()) {
2887 (None, None) => return Equal,
2888 (None, _ ) => return Less,
2889 (_ , None) => return Greater,
2890 (Some(x), Some(y)) => match x.cmp(&y) {
2892 non_eq => return non_eq,
2898 /// Order `a` and `b` lexicographically using `PartialOrd`
2899 pub fn partial_cmp<A, T, S>(mut a: T, mut b: S) -> Option<cmp::Ordering> where
2901 T: Iterator<Item=A>,
2902 S: Iterator<Item=A>,
2905 match (a.next(), b.next()) {
2906 (None, None) => return Some(Equal),
2907 (None, _ ) => return Some(Less),
2908 (_ , None) => return Some(Greater),
2909 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2911 non_eq => return non_eq,
2917 /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
2918 pub fn eq<A, B, L, R>(mut a: L, mut b: R) -> bool where
2920 L: Iterator<Item=A>,
2921 R: Iterator<Item=B>,
2924 match (a.next(), b.next()) {
2925 (None, None) => return true,
2926 (None, _) | (_, None) => return false,
2927 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2932 /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`)
2933 pub fn ne<A, B, L, R>(mut a: L, mut b: R) -> bool where
2935 L: Iterator<Item=A>,
2936 R: Iterator<Item=B>,
2939 match (a.next(), b.next()) {
2940 (None, None) => return false,
2941 (None, _) | (_, None) => return true,
2942 (Some(x), Some(y)) => if x.ne(&y) { return true },
2947 /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`)
2948 pub fn lt<A, T, S>(mut a: T, mut b: S) -> bool where
2950 T: Iterator<Item=A>,
2951 S: Iterator<Item=A>,
2954 match (a.next(), b.next()) {
2955 (None, None) => return false,
2956 (None, _ ) => return true,
2957 (_ , None) => return false,
2958 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2963 /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
2964 pub fn le<A, T, S>(mut a: T, mut b: S) -> bool where
2966 T: Iterator<Item=A>,
2967 S: Iterator<Item=A>,
2970 match (a.next(), b.next()) {
2971 (None, None) => return true,
2972 (None, _ ) => return true,
2973 (_ , None) => return false,
2974 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2979 /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`)
2980 pub fn gt<A, T, S>(mut a: T, mut b: S) -> bool where
2982 T: Iterator<Item=A>,
2983 S: Iterator<Item=A>,
2986 match (a.next(), b.next()) {
2987 (None, None) => return false,
2988 (None, _ ) => return false,
2989 (_ , None) => return true,
2990 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2995 /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
2996 pub fn ge<A, T, S>(mut a: T, mut b: S) -> bool where
2998 T: Iterator<Item=A>,
2999 S: Iterator<Item=A>,
3002 match (a.next(), b.next()) {
3003 (None, None) => return true,
3004 (None, _ ) => return false,
3005 (_ , None) => return true,
3006 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },