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
85 #[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling `.iter()` or a similar \
91 /// Advance the iterator and return the next value. Return `None` when the end is reached.
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 `uint`.
101 fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
104 // FIXME(#21363) remove `old_impl_check` when bug is fixed
106 impl<'a, T> Iterator for &'a mut (Iterator<Item=T> + 'a) {
109 fn next(&mut self) -> Option<T> {
113 fn size_hint(&self) -> (usize, Option<usize>) {
118 /// Conversion from an `Iterator`
120 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
121 built from an iterator over elements of type `{A}`"]
122 pub trait FromIterator<A> {
123 /// Build a container with elements from an external iterator.
124 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> Self;
127 /// A type growable from an `Iterator` implementation
129 pub trait Extend<A> {
130 /// Extend a container with the elements yielded by an arbitrary iterator
132 fn extend<T: Iterator<Item=A>>(&mut self, iterator: T);
135 /// An extension trait providing numerous methods applicable to all iterators.
137 pub trait IteratorExt: Iterator + Sized {
138 /// Counts the number of elements in this iterator.
143 /// let a = [1i, 2, 3, 4, 5];
144 /// let mut it = a.iter();
145 /// assert!(it.count() == 5);
149 fn count(self) -> uint {
150 self.fold(0, |cnt, _x| cnt + 1)
153 /// Loops through the entire iterator, returning the last element of the
159 /// let a = [1i, 2, 3, 4, 5];
160 /// assert!(a.iter().last().unwrap() == &5);
164 fn last(mut self) -> Option<Self::Item> {
166 for x in self { last = Some(x); }
170 /// Loops through `n` iterations, returning the `n`th element of the
176 /// let a = [1i, 2, 3, 4, 5];
177 /// let mut it = a.iter();
178 /// assert!(it.nth(2).unwrap() == &3);
179 /// assert!(it.nth(2) == None);
183 fn nth(&mut self, mut n: uint) -> Option<Self::Item> {
185 if n == 0 { return Some(x) }
191 /// Chain this iterator with another, returning a new iterator that will
192 /// finish iterating over the current iterator, and then iterate
193 /// over the other specified iterator.
200 /// let mut it = a.iter().chain(b.iter());
201 /// assert_eq!(it.next().unwrap(), &0);
202 /// assert_eq!(it.next().unwrap(), &1);
203 /// assert!(it.next().is_none());
207 fn chain<U>(self, other: U) -> Chain<Self, U> where
208 U: Iterator<Item=Self::Item>,
210 Chain{a: self, b: other, flag: false}
213 /// Creates an iterator that iterates over both this and the specified
214 /// iterators simultaneously, yielding the two elements as pairs. When
215 /// either iterator returns None, all further invocations of next() will
223 /// let mut it = a.iter().zip(b.iter());
224 /// let (x0, x1) = (0i, 1i);
225 /// assert_eq!(it.next().unwrap(), (&x0, &x1));
226 /// assert!(it.next().is_none());
230 fn zip<B, U>(self, other: U) -> Zip<Self, U> where
233 Zip{a: self, b: other}
236 /// Creates a new iterator that will apply the specified function to each
237 /// element returned by the first, yielding the mapped element instead.
243 /// let mut it = a.iter().map(|&x| 2 * x);
244 /// assert_eq!(it.next().unwrap(), 2);
245 /// assert_eq!(it.next().unwrap(), 4);
246 /// assert!(it.next().is_none());
250 fn map<B, F>(self, f: F) -> Map<Self::Item, B, Self, F> where
251 F: FnMut(Self::Item) -> B,
253 Map{iter: self, f: f}
256 /// Creates an iterator that applies the predicate to each element returned
257 /// by this iterator. Only elements that have the predicate evaluate to
258 /// `true` will be yielded.
264 /// let mut it = a.iter().filter(|&x| *x > 1);
265 /// assert_eq!(it.next().unwrap(), &2);
266 /// assert!(it.next().is_none());
270 fn filter<P>(self, predicate: P) -> Filter<Self::Item, Self, P> where
271 P: FnMut(&Self::Item) -> bool,
273 Filter{iter: self, predicate: predicate}
276 /// Creates an iterator that both filters and maps elements.
277 /// If the specified function returns None, the element is skipped.
278 /// Otherwise the option is unwrapped and the new value is yielded.
284 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
285 /// assert_eq!(it.next().unwrap(), 4);
286 /// assert!(it.next().is_none());
290 fn filter_map<B, F>(self, f: F) -> FilterMap<Self::Item, B, Self, F> where
291 F: FnMut(Self::Item) -> Option<B>,
293 FilterMap { iter: self, f: f }
296 /// Creates an iterator that yields a pair of the value returned by this
297 /// iterator plus the current index of iteration.
302 /// let a = [100i, 200];
303 /// let mut it = a.iter().enumerate();
304 /// let (x100, x200) = (100i, 200i);
305 /// assert_eq!(it.next().unwrap(), (0, &x100));
306 /// assert_eq!(it.next().unwrap(), (1, &x200));
307 /// assert!(it.next().is_none());
311 fn enumerate(self) -> Enumerate<Self> {
312 Enumerate{iter: self, count: 0}
315 /// Creates an iterator that has a `.peek()` method
316 /// that returns an optional reference to the next element.
321 /// let xs = [100i, 200, 300];
322 /// let mut it = xs.iter().map(|x| *x).peekable();
323 /// assert_eq!(*it.peek().unwrap(), 100);
324 /// assert_eq!(it.next().unwrap(), 100);
325 /// assert_eq!(it.next().unwrap(), 200);
326 /// assert_eq!(*it.peek().unwrap(), 300);
327 /// assert_eq!(*it.peek().unwrap(), 300);
328 /// assert_eq!(it.next().unwrap(), 300);
329 /// assert!(it.peek().is_none());
330 /// assert!(it.next().is_none());
334 fn peekable(self) -> Peekable<Self::Item, Self> {
335 Peekable{iter: self, peeked: None}
338 /// Creates an iterator that invokes the predicate on elements
339 /// until it returns false. Once the predicate returns false, that
340 /// element and all further elements are yielded.
345 /// let a = [1i, 2, 3, 2, 1];
346 /// let mut it = a.iter().skip_while(|&a| *a < 3);
347 /// assert_eq!(it.next().unwrap(), &3);
348 /// assert_eq!(it.next().unwrap(), &2);
349 /// assert_eq!(it.next().unwrap(), &1);
350 /// assert!(it.next().is_none());
354 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self::Item, Self, P> where
355 P: FnMut(&Self::Item) -> bool,
357 SkipWhile{iter: self, flag: false, predicate: predicate}
360 /// Creates an iterator that yields elements so long as the predicate
361 /// returns true. After the predicate returns false for the first time, no
362 /// further elements will be yielded.
367 /// let a = [1i, 2, 3, 2, 1];
368 /// let mut it = a.iter().take_while(|&a| *a < 3);
369 /// assert_eq!(it.next().unwrap(), &1);
370 /// assert_eq!(it.next().unwrap(), &2);
371 /// assert!(it.next().is_none());
375 fn take_while<P>(self, predicate: P) -> TakeWhile<Self::Item, Self, P> where
376 P: FnMut(&Self::Item) -> bool,
378 TakeWhile{iter: self, flag: false, predicate: predicate}
381 /// Creates an iterator that skips the first `n` elements of this iterator,
382 /// and then yields all further items.
387 /// let a = [1i, 2, 3, 4, 5];
388 /// let mut it = a.iter().skip(3);
389 /// assert_eq!(it.next().unwrap(), &4);
390 /// assert_eq!(it.next().unwrap(), &5);
391 /// assert!(it.next().is_none());
395 fn skip(self, n: uint) -> Skip<Self> {
396 Skip{iter: self, n: n}
399 /// Creates an iterator that yields the first `n` elements of this
400 /// iterator, and then will always return None.
405 /// let a = [1i, 2, 3, 4, 5];
406 /// let mut it = a.iter().take(3);
407 /// assert_eq!(it.next().unwrap(), &1);
408 /// assert_eq!(it.next().unwrap(), &2);
409 /// assert_eq!(it.next().unwrap(), &3);
410 /// assert!(it.next().is_none());
414 fn take(self, n: uint) -> Take<Self> {
415 Take{iter: self, n: n}
418 /// Creates a new iterator that behaves in a similar fashion to fold.
419 /// There is a state which is passed between each iteration and can be
420 /// mutated as necessary. The yielded values from the closure are yielded
421 /// from the Scan instance when not None.
426 /// let a = [1i, 2, 3, 4, 5];
427 /// let mut it = a.iter().scan(1, |fac, &x| {
431 /// assert_eq!(it.next().unwrap(), 1);
432 /// assert_eq!(it.next().unwrap(), 2);
433 /// assert_eq!(it.next().unwrap(), 6);
434 /// assert_eq!(it.next().unwrap(), 24);
435 /// assert_eq!(it.next().unwrap(), 120);
436 /// assert!(it.next().is_none());
444 ) -> Scan<Self::Item, B, Self, St, F> where
445 F: FnMut(&mut St, Self::Item) -> Option<B>,
447 Scan{iter: self, f: f, state: initial_state}
450 /// Creates an iterator that maps each element to an iterator,
451 /// and yields the elements of the produced iterators
456 /// use std::iter::count;
458 /// let xs = [2u, 3];
459 /// let ys = [0u, 1, 0, 1, 2];
460 /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
461 /// // Check that `it` has the same elements as `ys`
464 /// assert_eq!(x, ys[i]);
470 fn flat_map<B, U, F>(self, f: F) -> FlatMap<Self::Item, B, Self, U, F> where
472 F: FnMut(Self::Item) -> U,
474 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
477 /// Creates an iterator that yields `None` forever after the underlying
478 /// iterator yields `None`. Random-access iterator behavior is not
479 /// affected, only single and double-ended iterator behavior.
484 /// fn process<U: Iterator<Item=int>>(it: U) -> int {
485 /// let mut it = it.fuse();
493 /// // did we exhaust the iterator?
494 /// if it.next().is_none() {
499 /// let x = vec![1i,2,3,7,8,9];
500 /// assert_eq!(process(x.into_iter()), 6);
501 /// let x = vec![1i,2,3];
502 /// assert_eq!(process(x.into_iter()), 1006);
506 fn fuse(self) -> Fuse<Self> {
507 Fuse{iter: self, done: false}
510 /// Creates an iterator that calls a function with a reference to each
511 /// element before yielding it. This is often useful for debugging an
512 /// iterator pipeline.
517 /// use std::iter::AdditiveIterator;
519 /// let xs = [1u, 4, 2, 3, 8, 9, 6];
520 /// let sum = xs.iter()
522 /// .inspect(|&x| println!("filtering {}", x))
523 /// .filter(|&x| x % 2 == 0)
524 /// .inspect(|&x| println!("{} made it through", x))
526 /// println!("{}", sum);
530 fn inspect<F>(self, f: F) -> Inspect<Self::Item, Self, F> where
531 F: FnMut(&Self::Item),
533 Inspect{iter: self, f: f}
536 /// Creates a wrapper around a mutable reference to the iterator.
538 /// This is useful to allow applying iterator adaptors while still
539 /// retaining ownership of the original iterator value.
544 /// let mut xs = range(0u, 10);
545 /// // sum the first five values
546 /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
547 /// assert!(partial_sum == 10);
548 /// // xs.next() is now `5`
549 /// assert!(xs.next() == Some(5));
552 fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
556 /// Loops through the entire iterator, collecting all of the elements into
557 /// a container implementing `FromIterator`.
562 /// let a = [1i, 2, 3, 4, 5];
563 /// let b: Vec<int> = a.iter().map(|&x| x).collect();
564 /// assert!(a.as_slice() == b.as_slice());
568 fn collect<B: FromIterator<Self::Item>>(self) -> B {
569 FromIterator::from_iter(self)
572 /// Loops through the entire iterator, collecting all of the elements into
573 /// one of two containers, depending on a predicate. The elements of the
574 /// first container satisfy the predicate, while the elements of the second
578 /// let vec = vec![1i, 2i, 3i, 4i];
579 /// let (even, odd): (Vec<int>, Vec<int>) = vec.into_iter().partition(|&n| n % 2 == 0);
580 /// assert_eq!(even, vec![2, 4]);
581 /// assert_eq!(odd, vec![1, 3]);
583 #[unstable = "recently added as part of collections reform"]
584 fn partition<B, F>(mut self, mut f: F) -> (B, B) where
585 B: Default + Extend<Self::Item>,
586 F: FnMut(&Self::Item) -> bool
588 let mut left: B = Default::default();
589 let mut right: B = Default::default();
593 left.extend(Some(x).into_iter())
595 right.extend(Some(x).into_iter())
602 /// Performs a fold operation over the entire iterator, returning the
603 /// eventual state at the end of the iteration.
608 /// let a = [1i, 2, 3, 4, 5];
609 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
613 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
614 F: FnMut(B, Self::Item) -> B,
616 let mut accum = init;
623 /// Tests whether the predicate holds true for all elements in the iterator.
628 /// let a = [1i, 2, 3, 4, 5];
629 /// assert!(a.iter().all(|x| *x > 0));
630 /// assert!(!a.iter().all(|x| *x > 2));
634 fn all<F>(mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
635 for x in self { if !f(x) { return false; } }
639 /// Tests whether any element of an iterator satisfies the specified
645 /// let a = [1i, 2, 3, 4, 5];
646 /// let mut it = a.iter();
647 /// assert!(it.any(|x| *x == 3));
648 /// assert!(!it.any(|x| *x == 3));
652 fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
653 for x in *self { if f(x) { return true; } }
657 /// Returns the first element satisfying the specified predicate.
659 /// Does not consume the iterator past the first found element.
662 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
663 P: FnMut(&Self::Item) -> bool,
666 if predicate(&x) { return Some(x) }
671 /// Return the index of the first element satisfying the specified predicate
674 fn position<P>(&mut self, mut predicate: P) -> Option<uint> where
675 P: FnMut(Self::Item) -> bool,
687 /// Return the index of the last element satisfying the specified predicate
689 /// If no element matches, None is returned.
692 fn rposition<P>(&mut self, mut predicate: P) -> Option<uint> where
693 P: FnMut(Self::Item) -> bool,
694 Self: ExactSizeIterator + DoubleEndedIterator
696 let len = self.len();
697 for i in range(0, len).rev() {
698 if predicate(self.next_back().expect("rposition: incorrect ExactSizeIterator")) {
705 /// Consumes the entire iterator to return the maximum element.
710 /// let a = [1i, 2, 3, 4, 5];
711 /// assert!(a.iter().max().unwrap() == &5);
715 fn max(self) -> Option<Self::Item> where Self::Item: Ord
717 self.fold(None, |max, x| {
720 Some(y) => Some(cmp::max(x, y))
725 /// Consumes the entire iterator to return the minimum element.
730 /// let a = [1i, 2, 3, 4, 5];
731 /// assert!(a.iter().min().unwrap() == &1);
735 fn min(self) -> Option<Self::Item> where Self::Item: Ord
737 self.fold(None, |min, x| {
740 Some(y) => Some(cmp::min(x, y))
745 /// `min_max` finds the minimum and maximum elements in the iterator.
747 /// The return type `MinMaxResult` is an enum of three variants:
749 /// - `NoElements` if the iterator is empty.
750 /// - `OneElement(x)` if the iterator has exactly one element.
751 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
752 /// values are equal if and only if there is more than one
753 /// element in the iterator and all elements are equal.
755 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
756 /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons.
761 /// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax};
763 /// let v: [int; 0] = [];
764 /// assert_eq!(v.iter().min_max(), NoElements);
767 /// assert!(v.iter().min_max() == OneElement(&1));
769 /// let v = [1i, 2, 3, 4, 5];
770 /// assert!(v.iter().min_max() == MinMax(&1, &5));
772 /// let v = [1i, 2, 3, 4, 5, 6];
773 /// assert!(v.iter().min_max() == MinMax(&1, &6));
775 /// let v = [1i, 1, 1, 1];
776 /// assert!(v.iter().min_max() == MinMax(&1, &1));
778 #[unstable = "return type may change"]
779 fn min_max(mut self) -> MinMaxResult<Self::Item> where Self::Item: Ord
781 let (mut min, mut max) = match self.next() {
782 None => return NoElements,
785 None => return OneElement(x),
786 Some(y) => if x < y {(x, y)} else {(y,x)}
792 // `first` and `second` are the two next elements we want to look at.
793 // We first compare `first` and `second` (#1). The smaller one is then compared to
794 // current minimum (#2). The larger one is compared to current maximum (#3). This
795 // way we do 3 comparisons for 2 elements.
796 let first = match self.next() {
800 let second = match self.next() {
804 } else if first > max {
812 if first < min {min = first;}
813 if max < second {max = second;}
815 if second < min {min = second;}
816 if max < first {max = first;}
823 /// Return the element that gives the maximum value from the
824 /// specified function.
829 /// use core::num::SignedInt;
831 /// let xs = [-3i, 0, 1, 5, -10];
832 /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
835 #[unstable = "may want to produce an Ordering directly; see #15311"]
836 fn max_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
837 F: FnMut(&Self::Item) -> B,
839 self.fold(None, |max: Option<(Self::Item, B)>, x| {
842 None => Some((x, x_val)),
843 Some((y, y_val)) => if x_val > y_val {
852 /// Return the element that gives the minimum value from the
853 /// specified function.
858 /// use core::num::SignedInt;
860 /// let xs = [-3i, 0, 1, 5, -10];
861 /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
864 #[unstable = "may want to produce an Ordering directly; see #15311"]
865 fn min_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
866 F: FnMut(&Self::Item) -> B,
868 self.fold(None, |min: Option<(Self::Item, B)>, x| {
871 None => Some((x, x_val)),
872 Some((y, y_val)) => if x_val < y_val {
881 /// Change the direction of the iterator
883 /// The flipped iterator swaps the ends on an iterator that can already
884 /// be iterated from the front and from the back.
887 /// If the iterator also implements RandomAccessIterator, the flipped
888 /// iterator is also random access, with the indices starting at the back
889 /// of the original iterator.
891 /// Note: Random access with flipped indices still only applies to the first
892 /// `uint::MAX` elements of the original iterator.
895 fn rev(self) -> Rev<Self> {
899 /// Converts an iterator of pairs into a pair of containers.
901 /// Loops through the entire iterator, collecting the first component of
902 /// each item into one new container, and the second component into another.
903 #[unstable = "recent addition"]
904 fn unzip<A, B, FromA, FromB>(mut self) -> (FromA, FromB) where
905 FromA: Default + Extend<A>,
906 FromB: Default + Extend<B>,
907 Self: Iterator<Item=(A, B)>,
909 struct SizeHint<A>(uint, Option<uint>);
910 impl<A> Iterator for SizeHint<A> {
913 fn next(&mut self) -> Option<A> { None }
914 fn size_hint(&self) -> (uint, Option<uint>) {
919 let (lo, hi) = self.size_hint();
920 let mut ts: FromA = Default::default();
921 let mut us: FromB = Default::default();
923 ts.extend(SizeHint(lo, hi));
924 us.extend(SizeHint(lo, hi));
927 ts.extend(Some(t).into_iter());
928 us.extend(Some(u).into_iter());
934 /// Creates an iterator that clones the elements it yields. Useful for converting an
935 /// Iterator<&T> to an Iterator<T>.
936 #[unstable = "recent addition"]
937 fn cloned<T, D>(self) -> Cloned<Self> where
938 Self: Iterator<Item=D>,
945 /// Repeats an iterator endlessly
950 /// use std::iter::count;
952 /// let a = count(1i,1i).take(1);
953 /// let mut cy = a.cycle();
954 /// assert_eq!(cy.next(), Some(1));
955 /// assert_eq!(cy.next(), Some(1));
959 fn cycle(self) -> Cycle<Self> where Self: Clone {
960 Cycle{orig: self.clone(), iter: self}
963 /// Use an iterator to reverse a container in place.
964 #[unstable = "uncertain about placement or widespread use"]
965 fn reverse_in_place<'a, T: 'a>(&mut self) where
966 Self: Iterator<Item=&'a mut T> + DoubleEndedIterator
969 match (self.next(), self.next_back()) {
970 (Some(x), Some(y)) => mem::swap(x, y),
978 impl<I> IteratorExt for I where I: Iterator {}
980 /// A range iterator able to yield elements from both ends
982 /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust
983 /// elements from the *same* range, and do not work independently of each other.
985 pub trait DoubleEndedIterator: Iterator {
986 /// Yield an element from the end of the range, returning `None` if the range is empty.
988 fn next_back(&mut self) -> Option<Self::Item>;
991 /// An object implementing random access indexing by `uint`
993 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
994 /// Calling `next()` or `next_back()` on a `RandomAccessIterator`
995 /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)`
996 /// after `it.next()` is called.
997 #[unstable = "not widely used, may be better decomposed into Index and ExactSizeIterator"]
998 pub trait RandomAccessIterator: Iterator {
999 /// Return the number of indexable elements. At most `std::uint::MAX`
1000 /// elements are indexable, even if the iterator represents a longer range.
1001 fn indexable(&self) -> uint;
1003 /// Return an element at an index, or `None` if the index is out of bounds
1004 fn idx(&mut self, index: uint) -> Option<Self::Item>;
1007 /// An iterator that knows its exact length
1009 /// This trait is a helper for iterators like the vector iterator, so that
1010 /// it can support double-ended enumeration.
1012 /// `Iterator::size_hint` *must* return the exact size of the iterator.
1013 /// Note that the size must fit in `uint`.
1015 pub trait ExactSizeIterator: Iterator {
1017 /// Return the exact length of the iterator.
1018 fn len(&self) -> uint {
1019 let (lower, upper) = self.size_hint();
1020 // Note: This assertion is overly defensive, but it checks the invariant
1021 // guaranteed by the trait. If this trait were rust-internal,
1022 // we could use debug_assert!; assert_eq! will check all Rust user
1023 // implementations too.
1024 assert_eq!(upper, Some(lower));
1029 // All adaptors that preserve the size of the wrapped iterator are fine
1030 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
1032 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1034 impl<A, I, F> ExactSizeIterator for Inspect<A, I, F> where
1035 I: ExactSizeIterator<Item=A>,
1039 impl<I> ExactSizeIterator for Rev<I> where I: ExactSizeIterator + DoubleEndedIterator {}
1041 impl<A, B, I, F> ExactSizeIterator for Map<A, B, I, F> where
1042 I: ExactSizeIterator<Item=A>,
1046 impl<A, B> ExactSizeIterator for Zip<A, B> where A: ExactSizeIterator, B: ExactSizeIterator {}
1048 /// An double-ended iterator with the direction inverted
1050 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1057 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
1058 type Item = <I as Iterator>::Item;
1061 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1063 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
1067 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
1069 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1072 #[unstable = "trait is experimental"]
1073 impl<I> RandomAccessIterator for Rev<I> where I: DoubleEndedIterator + RandomAccessIterator {
1075 fn indexable(&self) -> uint { self.iter.indexable() }
1077 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1078 let amt = self.indexable();
1079 self.iter.idx(amt - index - 1)
1083 /// A mutable reference to an iterator
1084 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1086 pub struct ByRef<'a, I:'a> {
1091 impl<'a, I> Iterator for ByRef<'a, I> where I: 'a + Iterator {
1092 type Item = <I as Iterator>::Item;
1095 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1097 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
1101 impl<'a, I> DoubleEndedIterator for ByRef<'a, I> where I: 'a + DoubleEndedIterator {
1103 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1106 /// A trait for iterators over elements which can be added together
1107 #[unstable = "needs to be re-evaluated as part of numerics reform"]
1108 pub trait AdditiveIterator<A> {
1109 /// Iterates over the entire iterator, summing up all the elements
1114 /// use std::iter::AdditiveIterator;
1116 /// let a = [1i, 2, 3, 4, 5];
1117 /// let mut it = a.iter().map(|&x| x);
1118 /// assert!(it.sum() == 15);
1123 macro_rules! impl_additive {
1124 ($A:ty, $init:expr) => {
1125 #[unstable = "trait is experimental"]
1126 impl<T: Iterator<Item=$A>> AdditiveIterator<$A> for T {
1128 fn sum(self) -> $A {
1129 self.fold($init, |acc, x| acc + x)
1134 impl_additive! { i8, 0 }
1135 impl_additive! { i16, 0 }
1136 impl_additive! { i32, 0 }
1137 impl_additive! { i64, 0 }
1138 impl_additive! { int, 0 }
1139 impl_additive! { u8, 0 }
1140 impl_additive! { u16, 0 }
1141 impl_additive! { u32, 0 }
1142 impl_additive! { u64, 0 }
1143 impl_additive! { uint, 0 }
1144 impl_additive! { f32, 0.0 }
1145 impl_additive! { f64, 0.0 }
1147 /// A trait for iterators over elements which can be multiplied together.
1148 #[unstable = "needs to be re-evaluated as part of numerics reform"]
1149 pub trait MultiplicativeIterator<A> {
1150 /// Iterates over the entire iterator, multiplying all the elements
1155 /// use std::iter::{count, MultiplicativeIterator};
1157 /// fn factorial(n: uint) -> uint {
1158 /// count(1u, 1).take_while(|&i| i <= n).product()
1160 /// assert!(factorial(0) == 1);
1161 /// assert!(factorial(1) == 1);
1162 /// assert!(factorial(5) == 120);
1164 fn product(self) -> A;
1167 macro_rules! impl_multiplicative {
1168 ($A:ty, $init:expr) => {
1169 #[unstable = "trait is experimental"]
1170 impl<T: Iterator<Item=$A>> MultiplicativeIterator<$A> for T {
1172 fn product(self) -> $A {
1173 self.fold($init, |acc, x| acc * x)
1178 impl_multiplicative! { i8, 1 }
1179 impl_multiplicative! { i16, 1 }
1180 impl_multiplicative! { i32, 1 }
1181 impl_multiplicative! { i64, 1 }
1182 impl_multiplicative! { int, 1 }
1183 impl_multiplicative! { u8, 1 }
1184 impl_multiplicative! { u16, 1 }
1185 impl_multiplicative! { u32, 1 }
1186 impl_multiplicative! { u64, 1 }
1187 impl_multiplicative! { uint, 1 }
1188 impl_multiplicative! { f32, 1.0 }
1189 impl_multiplicative! { f64, 1.0 }
1191 /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
1192 #[derive(Clone, PartialEq, Show)]
1193 #[unstable = "unclear whether such a fine-grained result is widely useful"]
1194 pub enum MinMaxResult<T> {
1198 /// Iterator with one element, so the minimum and maximum are the same
1201 /// More than one element in the iterator, the first element is not larger than the second
1205 impl<T: Clone> MinMaxResult<T> {
1206 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1207 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1208 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1209 /// performing this operation will make one clone of `x`.
1214 /// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
1216 /// let r: MinMaxResult<int> = NoElements;
1217 /// assert_eq!(r.into_option(), None);
1219 /// let r = OneElement(1i);
1220 /// assert_eq!(r.into_option(), Some((1,1)));
1222 /// let r = MinMax(1i,2i);
1223 /// assert_eq!(r.into_option(), Some((1,2)));
1225 #[unstable = "type is unstable"]
1226 pub fn into_option(self) -> Option<(T,T)> {
1229 OneElement(x) => Some((x.clone(), x)),
1230 MinMax(x, y) => Some((x, y))
1235 /// An iterator that clones the elements of an underlying iterator
1236 #[unstable = "recent addition"]
1237 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1239 pub struct Cloned<I> {
1244 impl<T, D, I> Iterator for Cloned<I> where
1247 I: Iterator<Item=D>,
1251 fn next(&mut self) -> Option<T> {
1252 self.it.next().cloned()
1255 fn size_hint(&self) -> (uint, Option<uint>) {
1261 impl<T, D, I> DoubleEndedIterator for Cloned<I> where
1264 I: DoubleEndedIterator<Item=D>,
1266 fn next_back(&mut self) -> Option<T> {
1267 self.it.next_back().cloned()
1272 impl<T, D, I> ExactSizeIterator for Cloned<I> where
1275 I: ExactSizeIterator<Item=D>,
1278 /// An iterator that repeats endlessly
1279 #[derive(Clone, Copy)]
1280 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1282 pub struct Cycle<I> {
1288 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
1289 type Item = <I as Iterator>::Item;
1292 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1293 match self.iter.next() {
1294 None => { self.iter = self.orig.clone(); self.iter.next() }
1300 fn size_hint(&self) -> (uint, Option<uint>) {
1301 // the cycle iterator is either empty or infinite
1302 match self.orig.size_hint() {
1303 sz @ (0, Some(0)) => sz,
1304 (0, _) => (0, None),
1305 _ => (uint::MAX, None)
1310 #[unstable = "trait is experimental"]
1311 impl<I> RandomAccessIterator for Cycle<I> where
1312 I: Clone + RandomAccessIterator,
1315 fn indexable(&self) -> uint {
1316 if self.orig.indexable() > 0 {
1324 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1325 let liter = self.iter.indexable();
1326 let lorig = self.orig.indexable();
1329 } else if index < liter {
1330 self.iter.idx(index)
1332 self.orig.idx((index - liter) % lorig)
1337 /// An iterator that strings two iterators together
1339 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1341 pub struct Chain<A, B> {
1348 impl<T, A, B> Iterator for Chain<A, B> where A: Iterator<Item=T>, B: Iterator<Item=T> {
1352 fn next(&mut self) -> Option<T> {
1356 match self.a.next() {
1357 Some(x) => return Some(x),
1366 fn size_hint(&self) -> (uint, Option<uint>) {
1367 let (a_lower, a_upper) = self.a.size_hint();
1368 let (b_lower, b_upper) = self.b.size_hint();
1370 let lower = a_lower.saturating_add(b_lower);
1372 let upper = match (a_upper, b_upper) {
1373 (Some(x), Some(y)) => x.checked_add(y),
1382 impl<T, A, B> DoubleEndedIterator for Chain<A, B> where
1383 A: DoubleEndedIterator<Item=T>,
1384 B: DoubleEndedIterator<Item=T>,
1387 fn next_back(&mut self) -> Option<T> {
1388 match self.b.next_back() {
1390 None => self.a.next_back()
1395 #[unstable = "trait is experimental"]
1396 impl<T, A, B> RandomAccessIterator for Chain<A, B> where
1397 A: RandomAccessIterator<Item=T>,
1398 B: RandomAccessIterator<Item=T>,
1401 fn indexable(&self) -> uint {
1402 let (a, b) = (self.a.indexable(), self.b.indexable());
1407 fn idx(&mut self, index: uint) -> Option<T> {
1408 let len = self.a.indexable();
1412 self.b.idx(index - len)
1417 /// An iterator that iterates two other iterators simultaneously
1419 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1421 pub struct Zip<A, B> {
1427 impl<T, U, A, B> Iterator for Zip<A, B> where
1428 A: Iterator<Item = T>,
1429 B: Iterator<Item = U>,
1434 fn next(&mut self) -> Option<(T, U)> {
1435 match self.a.next() {
1437 Some(x) => match self.b.next() {
1439 Some(y) => Some((x, y))
1445 fn size_hint(&self) -> (uint, Option<uint>) {
1446 let (a_lower, a_upper) = self.a.size_hint();
1447 let (b_lower, b_upper) = self.b.size_hint();
1449 let lower = cmp::min(a_lower, b_lower);
1451 let upper = match (a_upper, b_upper) {
1452 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1453 (Some(x), None) => Some(x),
1454 (None, Some(y)) => Some(y),
1455 (None, None) => None
1463 impl<T, U, A, B> DoubleEndedIterator for Zip<A, B> where
1464 A: DoubleEndedIterator + ExactSizeIterator<Item=T>,
1465 B: DoubleEndedIterator + ExactSizeIterator<Item=U>,
1468 fn next_back(&mut self) -> Option<(T, U)> {
1469 let a_sz = self.a.len();
1470 let b_sz = self.b.len();
1472 // Adjust a, b to equal length
1474 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1476 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1479 match (self.a.next_back(), self.b.next_back()) {
1480 (Some(x), Some(y)) => Some((x, y)),
1481 (None, None) => None,
1482 _ => unreachable!(),
1487 #[unstable = "trait is experimental"]
1488 impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where
1489 A: RandomAccessIterator<Item=T>,
1490 B: RandomAccessIterator<Item=U>,
1493 fn indexable(&self) -> uint {
1494 cmp::min(self.a.indexable(), self.b.indexable())
1498 fn idx(&mut self, index: uint) -> Option<(T, U)> {
1499 match self.a.idx(index) {
1501 Some(x) => match self.b.idx(index) {
1503 Some(y) => Some((x, y))
1509 /// An iterator that maps the values of `iter` with `f`
1510 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1512 pub struct Map<A, B, I: Iterator<Item=A>, F: FnMut(A) -> B> {
1517 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1519 impl<A, B, I, F> Clone for Map<A, B, I, F> where
1520 I: Clone + Iterator<Item=A>,
1521 F: Clone + FnMut(A) -> B,
1523 fn clone(&self) -> Map<A, B, I, F> {
1525 iter: self.iter.clone(),
1531 impl<A, B, I, F> Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1533 fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1535 Some(a) => Some((self.f)(a)),
1542 impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1546 fn next(&mut self) -> Option<B> {
1547 let next = self.iter.next();
1552 fn size_hint(&self) -> (uint, Option<uint>) {
1553 self.iter.size_hint()
1558 impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where
1559 I: DoubleEndedIterator<Item=A>,
1563 fn next_back(&mut self) -> Option<B> {
1564 let next = self.iter.next_back();
1569 #[unstable = "trait is experimental"]
1570 impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where
1571 I: RandomAccessIterator<Item=A>,
1575 fn indexable(&self) -> uint {
1576 self.iter.indexable()
1580 fn idx(&mut self, index: uint) -> Option<B> {
1581 let elt = self.iter.idx(index);
1586 /// An iterator that filters the elements of `iter` with `predicate`
1587 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1589 pub struct Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1594 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1596 impl<A, I, P> Clone for Filter<A, I, P> where
1597 I: Clone + Iterator<Item=A>,
1598 P: Clone + FnMut(&A) -> bool,
1600 fn clone(&self) -> Filter<A, I, P> {
1602 iter: self.iter.clone(),
1603 predicate: self.predicate.clone(),
1609 impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1613 fn next(&mut self) -> Option<A> {
1614 for x in self.iter {
1615 if (self.predicate)(&x) {
1625 fn size_hint(&self) -> (uint, Option<uint>) {
1626 let (_, upper) = self.iter.size_hint();
1627 (0, upper) // can't know a lower bound, due to the predicate
1632 impl<A, I, P> DoubleEndedIterator for Filter<A, I, P> where
1633 I: DoubleEndedIterator<Item=A>,
1634 P: FnMut(&A) -> bool,
1637 fn next_back(&mut self) -> Option<A> {
1638 for x in self.iter.by_ref().rev() {
1639 if (self.predicate)(&x) {
1647 /// An iterator that uses `f` to both filter and map elements from `iter`
1648 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1650 pub struct FilterMap<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> Option<B> {
1655 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1657 impl<A, B, I, F> Clone for FilterMap<A, B, I, F> where
1658 I: Clone + Iterator<Item=A>,
1659 F: Clone + FnMut(A) -> Option<B>,
1661 fn clone(&self) -> FilterMap<A, B, I, F> {
1663 iter: self.iter.clone(),
1670 impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where
1671 I: Iterator<Item=A>,
1672 F: FnMut(A) -> Option<B>,
1677 fn next(&mut self) -> Option<B> {
1678 for x in self.iter {
1680 Some(y) => return Some(y),
1688 fn size_hint(&self) -> (uint, Option<uint>) {
1689 let (_, upper) = self.iter.size_hint();
1690 (0, upper) // can't know a lower bound, due to the predicate
1695 impl<A, B, I, F> DoubleEndedIterator for FilterMap<A, B, I, F> where
1696 I: DoubleEndedIterator<Item=A>,
1697 F: FnMut(A) -> Option<B>,
1700 fn next_back(&mut self) -> Option<B> {
1701 for x in self.iter.by_ref().rev() {
1703 Some(y) => return Some(y),
1711 /// An iterator that yields the current count and the element during iteration
1713 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1715 pub struct Enumerate<I> {
1721 impl<I> Iterator for Enumerate<I> where I: Iterator {
1722 type Item = (uint, <I as Iterator>::Item);
1725 fn next(&mut self) -> Option<(uint, <I as Iterator>::Item)> {
1726 match self.iter.next() {
1728 let ret = Some((self.count, a));
1737 fn size_hint(&self) -> (uint, Option<uint>) {
1738 self.iter.size_hint()
1743 impl<I> DoubleEndedIterator for Enumerate<I> where
1744 I: ExactSizeIterator + DoubleEndedIterator
1747 fn next_back(&mut self) -> Option<(uint, <I as Iterator>::Item)> {
1748 match self.iter.next_back() {
1750 let len = self.iter.len();
1751 Some((self.count + len, a))
1758 #[unstable = "trait is experimental"]
1759 impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator {
1761 fn indexable(&self) -> uint {
1762 self.iter.indexable()
1766 fn idx(&mut self, index: uint) -> Option<(uint, <I as Iterator>::Item)> {
1767 match self.iter.idx(index) {
1768 Some(a) => Some((self.count + index, a)),
1774 /// An iterator with a `peek()` that returns an optional reference to the next element.
1775 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1778 pub struct Peekable<T, I> where I: Iterator<Item=T> {
1784 impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> {
1788 fn next(&mut self) -> Option<T> {
1789 if self.peeked.is_some() { self.peeked.take() }
1790 else { self.iter.next() }
1794 fn size_hint(&self) -> (uint, Option<uint>) {
1795 let (lo, hi) = self.iter.size_hint();
1796 if self.peeked.is_some() {
1797 let lo = lo.saturating_add(1);
1799 Some(x) => x.checked_add(1),
1810 impl<T, I> Peekable<T, I> where I: Iterator<Item=T> {
1811 /// Return a reference to the next element of the iterator with out advancing it,
1812 /// or None if the iterator is exhausted.
1814 pub fn peek(&mut self) -> Option<&T> {
1815 if self.peeked.is_none() {
1816 self.peeked = self.iter.next();
1819 Some(ref value) => Some(value),
1824 /// Check whether peekable iterator is empty or not.
1826 pub fn is_empty(&mut self) -> bool {
1827 self.peek().is_none()
1831 /// An iterator that rejects elements while `predicate` is true
1832 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1834 pub struct SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1840 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1842 impl<A, I, P> Clone for SkipWhile<A, I, P> where
1843 I: Clone + Iterator<Item=A>,
1844 P: Clone + FnMut(&A) -> bool,
1846 fn clone(&self) -> SkipWhile<A, I, P> {
1848 iter: self.iter.clone(),
1850 predicate: self.predicate.clone(),
1856 impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1860 fn next(&mut self) -> Option<A> {
1861 for x in self.iter {
1862 if self.flag || !(self.predicate)(&x) {
1871 fn size_hint(&self) -> (uint, Option<uint>) {
1872 let (_, upper) = self.iter.size_hint();
1873 (0, upper) // can't know a lower bound, due to the predicate
1877 /// An iterator that only accepts elements while `predicate` is true
1878 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1880 pub struct TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1886 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1888 impl<A, I, P> Clone for TakeWhile<A, I, P> where
1889 I: Clone + Iterator<Item=A>,
1890 P: Clone + FnMut(&A) -> bool,
1892 fn clone(&self) -> TakeWhile<A, I, P> {
1894 iter: self.iter.clone(),
1896 predicate: self.predicate.clone(),
1902 impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1906 fn next(&mut self) -> Option<A> {
1910 match self.iter.next() {
1912 if (self.predicate)(&x) {
1925 fn size_hint(&self) -> (uint, Option<uint>) {
1926 let (_, upper) = self.iter.size_hint();
1927 (0, upper) // can't know a lower bound, due to the predicate
1931 /// An iterator that skips over `n` elements of `iter`.
1933 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1935 pub struct Skip<I> {
1941 impl<I> Iterator for Skip<I> where I: Iterator {
1942 type Item = <I as Iterator>::Item;
1945 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1946 let mut next = self.iter.next();
1955 next = self.iter.next();
1970 fn size_hint(&self) -> (uint, Option<uint>) {
1971 let (lower, upper) = self.iter.size_hint();
1973 let lower = lower.saturating_sub(self.n);
1975 let upper = match upper {
1976 Some(x) => Some(x.saturating_sub(self.n)),
1984 #[unstable = "trait is experimental"]
1985 impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{
1987 fn indexable(&self) -> uint {
1988 self.iter.indexable().saturating_sub(self.n)
1992 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1993 if index >= self.indexable() {
1996 self.iter.idx(index + self.n)
2001 /// An iterator that only iterates over the first `n` iterations of `iter`.
2003 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2005 pub struct Take<I> {
2011 impl<I> Iterator for Take<I> where I: Iterator{
2012 type Item = <I as Iterator>::Item;
2015 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2025 fn size_hint(&self) -> (uint, Option<uint>) {
2026 let (lower, upper) = self.iter.size_hint();
2028 let lower = cmp::min(lower, self.n);
2030 let upper = match upper {
2031 Some(x) if x < self.n => Some(x),
2039 #[unstable = "trait is experimental"]
2040 impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{
2042 fn indexable(&self) -> uint {
2043 cmp::min(self.iter.indexable(), self.n)
2047 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
2048 if index >= self.n {
2051 self.iter.idx(index)
2057 /// An iterator to maintain state while iterating another iterator
2058 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2060 pub struct Scan<A, B, I, St, F> where I: Iterator, F: FnMut(&mut St, A) -> Option<B> {
2064 /// The current internal state to be passed to the closure next.
2068 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2070 impl<A, B, I, St, F> Clone for Scan<A, B, I, St, F> where
2071 I: Clone + Iterator<Item=A>,
2073 F: Clone + FnMut(&mut St, A) -> Option<B>,
2075 fn clone(&self) -> Scan<A, B, I, St, F> {
2077 iter: self.iter.clone(),
2079 state: self.state.clone(),
2085 impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where
2086 I: Iterator<Item=A>,
2087 F: FnMut(&mut St, A) -> Option<B>,
2092 fn next(&mut self) -> Option<B> {
2093 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2097 fn size_hint(&self) -> (uint, Option<uint>) {
2098 let (_, upper) = self.iter.size_hint();
2099 (0, upper) // can't know a lower bound, due to the scan function
2103 /// An iterator that maps each element to an iterator,
2104 /// and yields the elements of the produced iterators
2106 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2108 pub struct FlatMap<A, B, I, U, F> where
2109 I: Iterator<Item=A>,
2110 U: Iterator<Item=B>,
2115 frontiter: Option<U>,
2116 backiter: Option<U>,
2119 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2121 impl<A, B, I, U, F> Clone for FlatMap<A, B, I, U, F> where
2122 I: Clone + Iterator<Item=A>,
2123 U: Clone + Iterator<Item=B>,
2124 F: Clone + FnMut(A) -> U,
2126 fn clone(&self) -> FlatMap<A, B, I, U, F> {
2128 iter: self.iter.clone(),
2130 frontiter: self.frontiter.clone(),
2131 backiter: self.backiter.clone(),
2137 impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where
2138 I: Iterator<Item=A>,
2139 U: Iterator<Item=B>,
2145 fn next(&mut self) -> Option<B> {
2147 for inner in self.frontiter.iter_mut() {
2152 match self.iter.next().map(|x| (self.f)(x)) {
2153 None => return self.backiter.as_mut().and_then(|it| it.next()),
2154 next => self.frontiter = next,
2160 fn size_hint(&self) -> (uint, Option<uint>) {
2161 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2162 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2163 let lo = flo.saturating_add(blo);
2164 match (self.iter.size_hint(), fhi, bhi) {
2165 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2172 impl<A, B, I, U, F> DoubleEndedIterator for FlatMap<A, B, I, U, F> where
2173 I: DoubleEndedIterator<Item=A>,
2174 U: DoubleEndedIterator<Item=B>,
2178 fn next_back(&mut self) -> Option<B> {
2180 for inner in self.backiter.iter_mut() {
2181 match inner.next_back() {
2186 match self.iter.next_back().map(|x| (self.f)(x)) {
2187 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2188 next => self.backiter = next,
2194 /// An iterator that yields `None` forever after the underlying iterator
2195 /// yields `None` once.
2197 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2199 pub struct Fuse<I> {
2205 impl<I> Iterator for Fuse<I> where I: Iterator {
2206 type Item = <I as Iterator>::Item;
2209 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2213 match self.iter.next() {
2224 fn size_hint(&self) -> (uint, Option<uint>) {
2228 self.iter.size_hint()
2234 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2236 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2240 match self.iter.next_back() {
2251 // Allow RandomAccessIterators to be fused without affecting random-access behavior
2252 #[unstable = "trait is experimental"]
2253 impl<I> RandomAccessIterator for Fuse<I> where I: RandomAccessIterator {
2255 fn indexable(&self) -> uint {
2256 self.iter.indexable()
2260 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
2261 self.iter.idx(index)
2266 /// Resets the fuse such that the next call to .next() or .next_back() will
2267 /// call the underlying iterator again even if it previously returned None.
2269 #[unstable = "seems marginal"]
2270 pub fn reset_fuse(&mut self) {
2275 /// An iterator that calls a function with a reference to each
2276 /// element before yielding it.
2277 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2279 pub struct Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2284 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2286 impl<A, I, F> Clone for Inspect<A, I, F> where
2287 I: Clone + Iterator<Item=A>,
2288 F: Clone + FnMut(&A),
2290 fn clone(&self) -> Inspect<A, I, F> {
2292 iter: self.iter.clone(),
2298 impl<A, I, F> Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2300 fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
2302 Some(ref a) => (self.f)(a),
2311 impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2315 fn next(&mut self) -> Option<A> {
2316 let next = self.iter.next();
2317 self.do_inspect(next)
2321 fn size_hint(&self) -> (uint, Option<uint>) {
2322 self.iter.size_hint()
2327 impl<A, I, F> DoubleEndedIterator for Inspect<A, I, F> where
2328 I: DoubleEndedIterator<Item=A>,
2332 fn next_back(&mut self) -> Option<A> {
2333 let next = self.iter.next_back();
2334 self.do_inspect(next)
2338 #[unstable = "trait is experimental"]
2339 impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where
2340 I: RandomAccessIterator<Item=A>,
2344 fn indexable(&self) -> uint {
2345 self.iter.indexable()
2349 fn idx(&mut self, index: uint) -> Option<A> {
2350 let element = self.iter.idx(index);
2351 self.do_inspect(element)
2355 /// An iterator that passes mutable state to a closure and yields the result.
2357 /// # Example: The Fibonacci Sequence
2359 /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2362 /// use std::iter::Unfold;
2363 /// use std::num::Int; // For `.checked_add()`
2365 /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2366 /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2367 /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| {
2368 /// // Attempt to get the next Fibonacci number
2369 /// // `x1` will be `None` if previously overflowed.
2370 /// let next = match (*x2, *x1) {
2371 /// (Some(x2), Some(x1)) => x2.checked_add(x1),
2375 /// // Shift left: ret <- x2 <- x1 <- next
2383 /// for i in fibonacci {
2384 /// println!("{}", i);
2388 pub struct Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2390 /// Internal state that will be passed to the closure on the next iteration
2394 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2396 impl<A, St, F> Clone for Unfold<A, St, F> where
2397 F: Clone + FnMut(&mut St) -> Option<A>,
2400 fn clone(&self) -> Unfold<A, St, F> {
2403 state: self.state.clone(),
2409 impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2410 /// Creates a new iterator with the specified closure as the "iterator
2411 /// function" and an initial state to eventually pass to the closure
2413 pub fn new(initial_state: St, f: F) -> Unfold<A, St, F> {
2416 state: initial_state
2422 impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2426 fn next(&mut self) -> Option<A> {
2427 (self.f)(&mut self.state)
2431 fn size_hint(&self) -> (uint, Option<uint>) {
2432 // no possible known bounds at this point
2437 /// An infinite iterator starting at `start` and advancing by `step` with each
2439 #[derive(Clone, Copy)]
2440 #[unstable = "may be renamed or replaced by range notation adapaters"]
2441 pub struct Counter<A> {
2442 /// The current state the counter is at (next value to be yielded)
2444 /// The amount that this iterator is stepping by
2448 /// Creates a new counter with the specified start/step
2450 #[unstable = "may be renamed or replaced by range notation adapaters"]
2451 pub fn count<A>(start: A, step: A) -> Counter<A> {
2452 Counter{state: start, step: step}
2456 impl<A: Add<Output=A> + Clone> Iterator for Counter<A> {
2460 fn next(&mut self) -> Option<A> {
2461 let result = self.state.clone();
2462 self.state = self.state.clone() + self.step.clone();
2467 fn size_hint(&self) -> (uint, Option<uint>) {
2468 (uint::MAX, None) // Too bad we can't specify an infinite lower bound
2472 /// An iterator over the range [start, stop)
2473 #[derive(Clone, Copy)]
2474 #[unstable = "will be replaced by range notation"]
2475 pub struct Range<A> {
2481 /// Returns an iterator over the given range [start, stop) (that is, starting
2482 /// at start (inclusive), and ending at stop (exclusive)).
2487 /// let array = [0, 1, 2, 3, 4];
2489 /// for i in range(0, 5u) {
2490 /// println!("{}", i);
2491 /// assert_eq!(i, array[i]);
2495 #[unstable = "will be replaced by range notation"]
2496 pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
2504 // FIXME: #10414: Unfortunate type bound
2505 #[unstable = "will be replaced by range notation"]
2506 impl<A: Int + ToPrimitive> Iterator for Range<A> {
2510 fn next(&mut self) -> Option<A> {
2511 if self.state < self.stop {
2512 let result = self.state.clone();
2513 self.state = self.state + self.one;
2521 fn size_hint(&self) -> (uint, Option<uint>) {
2522 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
2523 // handle cases like range(huge, huger)). We don't use uint/int because the difference of
2524 // the i64/u64 might lie within their range.
2525 let bound = match self.state.to_i64() {
2527 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
2529 Some(Some(bound)) => bound.to_uint(),
2533 None => match self.state.to_u64() {
2535 let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
2537 Some(Some(bound)) => bound.to_uint(),
2546 Some(b) => (b, Some(b)),
2547 // Standard fallback for unbounded/unrepresentable bounds
2553 /// `Int` is required to ensure the range will be the same regardless of
2554 /// the direction it is consumed.
2555 #[unstable = "will be replaced by range notation"]
2556 impl<A: Int + ToPrimitive> DoubleEndedIterator for Range<A> {
2558 fn next_back(&mut self) -> Option<A> {
2559 if self.stop > self.state {
2560 self.stop = self.stop - self.one;
2561 Some(self.stop.clone())
2568 /// An iterator over the range [start, stop]
2570 #[unstable = "likely to be replaced by range notation and adapters"]
2571 pub struct RangeInclusive<A> {
2576 /// Return an iterator over the range [start, stop]
2578 #[unstable = "likely to be replaced by range notation and adapters"]
2579 pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
2581 range: range(start, stop),
2586 #[unstable = "likely to be replaced by range notation and adapters"]
2587 impl<A: Int + ToPrimitive> Iterator for RangeInclusive<A> {
2591 fn next(&mut self) -> Option<A> {
2592 match self.range.next() {
2595 if !self.done && self.range.state == self.range.stop {
2597 Some(self.range.stop.clone())
2606 fn size_hint(&self) -> (uint, Option<uint>) {
2607 let (lo, hi) = self.range.size_hint();
2611 let lo = lo.saturating_add(1);
2613 Some(x) => x.checked_add(1),
2621 #[unstable = "likely to be replaced by range notation and adapters"]
2622 impl<A: Int + ToPrimitive> DoubleEndedIterator for RangeInclusive<A> {
2624 fn next_back(&mut self) -> Option<A> {
2625 if self.range.stop > self.range.state {
2626 let result = self.range.stop.clone();
2627 self.range.stop = self.range.stop - self.range.one;
2629 } else if !self.done && self.range.state == self.range.stop {
2631 Some(self.range.stop.clone())
2638 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2640 #[unstable = "likely to be replaced by range notation and adapters"]
2641 pub struct RangeStep<A> {
2648 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2650 #[unstable = "likely to be replaced by range notation and adapters"]
2651 pub fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
2652 let rev = step < Int::zero();
2653 RangeStep{state: start, stop: stop, step: step, rev: rev}
2656 #[unstable = "likely to be replaced by range notation and adapters"]
2657 impl<A: Int> Iterator for RangeStep<A> {
2661 fn next(&mut self) -> Option<A> {
2662 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2663 let result = self.state;
2664 match self.state.checked_add(self.step) {
2665 Some(x) => self.state = x,
2666 None => self.state = self.stop.clone()
2675 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2677 #[unstable = "likely to be replaced by range notation and adapters"]
2678 pub struct RangeStepInclusive<A> {
2686 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2688 #[unstable = "likely to be replaced by range notation and adapters"]
2689 pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
2690 let rev = step < Int::zero();
2691 RangeStepInclusive {
2700 #[unstable = "likely to be replaced by range notation and adapters"]
2701 impl<A: Int> Iterator for RangeStepInclusive<A> {
2705 fn next(&mut self) -> Option<A> {
2706 if !self.done && ((self.rev && self.state >= self.stop) ||
2707 (!self.rev && self.state <= self.stop)) {
2708 let result = self.state;
2709 match self.state.checked_add(self.step) {
2710 Some(x) => self.state = x,
2711 None => self.done = true
2720 macro_rules! range_impl {
2723 impl Iterator for ::ops::Range<$t> {
2727 fn next(&mut self) -> Option<$t> {
2728 if self.start < self.end {
2729 let result = self.start;
2731 return Some(result);
2738 fn size_hint(&self) -> (uint, Option<uint>) {
2739 debug_assert!(self.end >= self.start);
2740 let hint = (self.end - self.start) as uint;
2746 impl ExactSizeIterator for ::ops::Range<$t> {}
2750 macro_rules! range_impl_no_hint {
2753 impl Iterator for ::ops::Range<$t> {
2757 fn next(&mut self) -> Option<$t> {
2758 if self.start < self.end {
2759 let result = self.start;
2761 return Some(result);
2770 macro_rules! range_other_impls {
2773 impl DoubleEndedIterator for ::ops::Range<$t> {
2775 fn next_back(&mut self) -> Option<$t> {
2776 if self.start < self.end {
2778 return Some(self.end);
2786 impl Iterator for ::ops::RangeFrom<$t> {
2790 fn next(&mut self) -> Option<$t> {
2791 let result = self.start;
2793 debug_assert!(result < self.start);
2794 return Some(result);
2800 range_impl!(uint u8 u16 u32 int i8 i16 i32);
2801 #[cfg(target_pointer_width = "64")]
2802 range_impl!(u64 i64);
2803 #[cfg(target_pointer_width = "32")]
2804 range_impl_no_hint!(u64 i64);
2806 range_other_impls!(uint u8 u16 u32 u64 int i8 i16 i32 i64);
2808 /// An iterator that repeats an element endlessly
2811 pub struct Repeat<A> {
2816 impl<A: Clone> Iterator for Repeat<A> {
2820 fn next(&mut self) -> Option<A> { self.idx(0) }
2822 fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2826 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
2828 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2831 #[unstable = "trait is experimental"]
2832 impl<A: Clone> RandomAccessIterator for Repeat<A> {
2834 fn indexable(&self) -> uint { uint::MAX }
2836 fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
2839 type IterateState<T, F> = (F, Option<T>, bool);
2841 /// An iterator that repeatedly applies a given function, starting
2842 /// from a given seed value.
2844 pub type Iterate<T, F> = Unfold<T, IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>;
2846 /// Create a new iterator that produces an infinite sequence of
2847 /// repeated applications of the given function `f`.
2849 pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where
2853 fn next<T, F>(st: &mut IterateState<T, F>) -> Option<T> where
2857 let &mut (ref mut f, ref mut val, ref mut first) = st;
2863 *val = Some((*f)(x))
2871 // coerce to a fn pointer
2872 let next: fn(&mut IterateState<T,F>) -> Option<T> = next;
2874 Unfold::new((f, Some(seed), true), next)
2877 /// Create a new iterator that endlessly repeats the element `elt`.
2880 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
2881 Repeat{element: elt}
2884 /// Functions for lexicographical ordering of sequences.
2886 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2887 /// that the elements implement both `PartialEq` and `PartialOrd`.
2889 /// If two sequences are equal up until the point where one ends,
2890 /// the shorter sequence compares less.
2891 #[unstable = "needs review and revision"]
2894 use cmp::{Eq, Ord, PartialOrd, PartialEq};
2895 use cmp::Ordering::{Equal, Less, Greater};
2897 use option::Option::{Some, None};
2898 use super::Iterator;
2900 /// Compare `a` and `b` for equality using `Eq`
2901 pub fn equals<A, T, S>(mut a: T, mut b: S) -> bool where
2903 T: Iterator<Item=A>,
2904 S: Iterator<Item=A>,
2907 match (a.next(), b.next()) {
2908 (None, None) => return true,
2909 (None, _) | (_, None) => return false,
2910 (Some(x), Some(y)) => if x != y { return false },
2915 /// Order `a` and `b` lexicographically using `Ord`
2916 pub fn cmp<A, T, S>(mut a: T, mut b: S) -> cmp::Ordering where
2918 T: Iterator<Item=A>,
2919 S: Iterator<Item=A>,
2922 match (a.next(), b.next()) {
2923 (None, None) => return Equal,
2924 (None, _ ) => return Less,
2925 (_ , None) => return Greater,
2926 (Some(x), Some(y)) => match x.cmp(&y) {
2928 non_eq => return non_eq,
2934 /// Order `a` and `b` lexicographically using `PartialOrd`
2935 pub fn partial_cmp<A, T, S>(mut a: T, mut b: S) -> Option<cmp::Ordering> where
2937 T: Iterator<Item=A>,
2938 S: Iterator<Item=A>,
2941 match (a.next(), b.next()) {
2942 (None, None) => return Some(Equal),
2943 (None, _ ) => return Some(Less),
2944 (_ , None) => return Some(Greater),
2945 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2947 non_eq => return non_eq,
2953 /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
2954 pub fn eq<A, B, L, R>(mut a: L, mut b: R) -> bool where
2956 L: Iterator<Item=A>,
2957 R: Iterator<Item=B>,
2960 match (a.next(), b.next()) {
2961 (None, None) => return true,
2962 (None, _) | (_, None) => return false,
2963 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2968 /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`)
2969 pub fn ne<A, B, L, R>(mut a: L, mut b: R) -> bool where
2971 L: Iterator<Item=A>,
2972 R: Iterator<Item=B>,
2975 match (a.next(), b.next()) {
2976 (None, None) => return false,
2977 (None, _) | (_, None) => return true,
2978 (Some(x), Some(y)) => if x.ne(&y) { return true },
2983 /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`)
2984 pub fn lt<A, T, S>(mut a: T, mut b: S) -> bool where
2986 T: Iterator<Item=A>,
2987 S: Iterator<Item=A>,
2990 match (a.next(), b.next()) {
2991 (None, None) => return false,
2992 (None, _ ) => return true,
2993 (_ , None) => return false,
2994 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2999 /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
3000 pub fn le<A, T, S>(mut a: T, mut b: S) -> bool where
3002 T: Iterator<Item=A>,
3003 S: Iterator<Item=A>,
3006 match (a.next(), b.next()) {
3007 (None, None) => return true,
3008 (None, _ ) => return true,
3009 (_ , None) => return false,
3010 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
3015 /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`)
3016 pub fn gt<A, T, S>(mut a: T, mut b: S) -> bool where
3018 T: Iterator<Item=A>,
3019 S: Iterator<Item=A>,
3022 match (a.next(), b.next()) {
3023 (None, None) => return false,
3024 (None, _ ) => return false,
3025 (_ , None) => return true,
3026 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
3031 /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
3032 pub fn ge<A, T, S>(mut a: T, mut b: S) -> bool where
3034 T: Iterator<Item=A>,
3035 S: Iterator<Item=A>,
3038 match (a.next(), b.next()) {
3039 (None, None) => return true,
3040 (None, _ ) => return false,
3041 (_ , None) => return true,
3042 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },