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 /// Conversion from an `Iterator`
104 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
105 built from an iterator over elements of type `{A}`"]
106 pub trait FromIterator<A> {
107 /// Build a container with elements from an external iterator.
108 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> Self;
111 /// A type growable from an `Iterator` implementation
113 pub trait Extend<A> {
114 /// Extend a container with the elements yielded by an arbitrary iterator
116 fn extend<T: Iterator<Item=A>>(&mut self, iterator: T);
119 /// An extension trait providing numerous methods applicable to all iterators.
121 pub trait IteratorExt: Iterator + Sized {
122 /// Counts the number of elements in this iterator.
127 /// let a = [1i, 2, 3, 4, 5];
128 /// let mut it = a.iter();
129 /// assert!(it.count() == 5);
133 fn count(self) -> uint {
134 self.fold(0, |cnt, _x| cnt + 1)
137 /// Loops through the entire iterator, returning the last element of the
143 /// let a = [1i, 2, 3, 4, 5];
144 /// assert!(a.iter().last().unwrap() == &5);
148 fn last(mut self) -> Option<Self::Item> {
150 for x in self { last = Some(x); }
154 /// Loops through `n` iterations, returning the `n`th element of the
160 /// let a = [1i, 2, 3, 4, 5];
161 /// let mut it = a.iter();
162 /// assert!(it.nth(2).unwrap() == &3);
163 /// assert!(it.nth(2) == None);
167 fn nth(&mut self, mut n: uint) -> Option<Self::Item> {
169 if n == 0 { return Some(x) }
175 /// Chain this iterator with another, returning a new iterator that will
176 /// finish iterating over the current iterator, and then iterate
177 /// over the other specified iterator.
184 /// let mut it = a.iter().chain(b.iter());
185 /// assert_eq!(it.next().unwrap(), &0);
186 /// assert_eq!(it.next().unwrap(), &1);
187 /// assert!(it.next().is_none());
191 fn chain<U>(self, other: U) -> Chain<Self, U> where
192 U: Iterator<Item=Self::Item>,
194 Chain{a: self, b: other, flag: false}
197 /// Creates an iterator that iterates over both this and the specified
198 /// iterators simultaneously, yielding the two elements as pairs. When
199 /// either iterator returns None, all further invocations of next() will
207 /// let mut it = a.iter().zip(b.iter());
208 /// let (x0, x1) = (0i, 1i);
209 /// assert_eq!(it.next().unwrap(), (&x0, &x1));
210 /// assert!(it.next().is_none());
214 fn zip<B, U>(self, other: U) -> Zip<Self, U> where
217 Zip{a: self, b: other}
220 /// Creates a new iterator that will apply the specified function to each
221 /// element returned by the first, yielding the mapped element instead.
227 /// let mut it = a.iter().map(|&x| 2 * x);
228 /// assert_eq!(it.next().unwrap(), 2);
229 /// assert_eq!(it.next().unwrap(), 4);
230 /// assert!(it.next().is_none());
234 fn map<B, F>(self, f: F) -> Map<Self::Item, B, Self, F> where
235 F: FnMut(Self::Item) -> B,
237 Map{iter: self, f: f}
240 /// Creates an iterator that applies the predicate to each element returned
241 /// by this iterator. Only elements that have the predicate evaluate to
242 /// `true` will be yielded.
248 /// let mut it = a.iter().filter(|&x| *x > 1);
249 /// assert_eq!(it.next().unwrap(), &2);
250 /// assert!(it.next().is_none());
254 fn filter<P>(self, predicate: P) -> Filter<Self::Item, Self, P> where
255 P: FnMut(&Self::Item) -> bool,
257 Filter{iter: self, predicate: predicate}
260 /// Creates an iterator that both filters and maps elements.
261 /// If the specified function returns None, the element is skipped.
262 /// Otherwise the option is unwrapped and the new value is yielded.
268 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
269 /// assert_eq!(it.next().unwrap(), 4);
270 /// assert!(it.next().is_none());
274 fn filter_map<B, F>(self, f: F) -> FilterMap<Self::Item, B, Self, F> where
275 F: FnMut(Self::Item) -> Option<B>,
277 FilterMap { iter: self, f: f }
280 /// Creates an iterator that yields a pair of the value returned by this
281 /// iterator plus the current index of iteration.
286 /// let a = [100i, 200];
287 /// let mut it = a.iter().enumerate();
288 /// let (x100, x200) = (100i, 200i);
289 /// assert_eq!(it.next().unwrap(), (0, &x100));
290 /// assert_eq!(it.next().unwrap(), (1, &x200));
291 /// assert!(it.next().is_none());
295 fn enumerate(self) -> Enumerate<Self> {
296 Enumerate{iter: self, count: 0}
299 /// Creates an iterator that has a `.peek()` method
300 /// that returns an optional reference to the next element.
305 /// let xs = [100i, 200, 300];
306 /// let mut it = xs.iter().map(|x| *x).peekable();
307 /// assert_eq!(*it.peek().unwrap(), 100);
308 /// assert_eq!(it.next().unwrap(), 100);
309 /// assert_eq!(it.next().unwrap(), 200);
310 /// assert_eq!(*it.peek().unwrap(), 300);
311 /// assert_eq!(*it.peek().unwrap(), 300);
312 /// assert_eq!(it.next().unwrap(), 300);
313 /// assert!(it.peek().is_none());
314 /// assert!(it.next().is_none());
318 fn peekable(self) -> Peekable<Self::Item, Self> {
319 Peekable{iter: self, peeked: None}
322 /// Creates an iterator that invokes the predicate on elements
323 /// until it returns false. Once the predicate returns false, that
324 /// element and all further elements are yielded.
329 /// let a = [1i, 2, 3, 2, 1];
330 /// let mut it = a.iter().skip_while(|&a| *a < 3);
331 /// assert_eq!(it.next().unwrap(), &3);
332 /// assert_eq!(it.next().unwrap(), &2);
333 /// assert_eq!(it.next().unwrap(), &1);
334 /// assert!(it.next().is_none());
338 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self::Item, Self, P> where
339 P: FnMut(&Self::Item) -> bool,
341 SkipWhile{iter: self, flag: false, predicate: predicate}
344 /// Creates an iterator that yields elements so long as the predicate
345 /// returns true. After the predicate returns false for the first time, no
346 /// further elements will be yielded.
351 /// let a = [1i, 2, 3, 2, 1];
352 /// let mut it = a.iter().take_while(|&a| *a < 3);
353 /// assert_eq!(it.next().unwrap(), &1);
354 /// assert_eq!(it.next().unwrap(), &2);
355 /// assert!(it.next().is_none());
359 fn take_while<P>(self, predicate: P) -> TakeWhile<Self::Item, Self, P> where
360 P: FnMut(&Self::Item) -> bool,
362 TakeWhile{iter: self, flag: false, predicate: predicate}
365 /// Creates an iterator that skips the first `n` elements of this iterator,
366 /// and then yields all further items.
371 /// let a = [1i, 2, 3, 4, 5];
372 /// let mut it = a.iter().skip(3);
373 /// assert_eq!(it.next().unwrap(), &4);
374 /// assert_eq!(it.next().unwrap(), &5);
375 /// assert!(it.next().is_none());
379 fn skip(self, n: uint) -> Skip<Self> {
380 Skip{iter: self, n: n}
383 /// Creates an iterator that yields the first `n` elements of this
384 /// iterator, and then will always return None.
389 /// let a = [1i, 2, 3, 4, 5];
390 /// let mut it = a.iter().take(3);
391 /// assert_eq!(it.next().unwrap(), &1);
392 /// assert_eq!(it.next().unwrap(), &2);
393 /// assert_eq!(it.next().unwrap(), &3);
394 /// assert!(it.next().is_none());
398 fn take(self, n: uint) -> Take<Self> {
399 Take{iter: self, n: n}
402 /// Creates a new iterator that behaves in a similar fashion to fold.
403 /// There is a state which is passed between each iteration and can be
404 /// mutated as necessary. The yielded values from the closure are yielded
405 /// from the Scan instance when not None.
410 /// let a = [1i, 2, 3, 4, 5];
411 /// let mut it = a.iter().scan(1, |fac, &x| {
415 /// assert_eq!(it.next().unwrap(), 1);
416 /// assert_eq!(it.next().unwrap(), 2);
417 /// assert_eq!(it.next().unwrap(), 6);
418 /// assert_eq!(it.next().unwrap(), 24);
419 /// assert_eq!(it.next().unwrap(), 120);
420 /// assert!(it.next().is_none());
428 ) -> Scan<Self::Item, B, Self, St, F> where
429 F: FnMut(&mut St, Self::Item) -> Option<B>,
431 Scan{iter: self, f: f, state: initial_state}
434 /// Creates an iterator that maps each element to an iterator,
435 /// and yields the elements of the produced iterators
440 /// use std::iter::count;
442 /// let xs = [2u, 3];
443 /// let ys = [0u, 1, 0, 1, 2];
444 /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
445 /// // Check that `it` has the same elements as `ys`
448 /// assert_eq!(x, ys[i]);
454 fn flat_map<B, U, F>(self, f: F) -> FlatMap<Self::Item, B, Self, U, F> where
456 F: FnMut(Self::Item) -> U,
458 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
461 /// Creates an iterator that yields `None` forever after the underlying
462 /// iterator yields `None`. Random-access iterator behavior is not
463 /// affected, only single and double-ended iterator behavior.
468 /// fn process<U: Iterator<Item=int>>(it: U) -> int {
469 /// let mut it = it.fuse();
477 /// // did we exhaust the iterator?
478 /// if it.next().is_none() {
483 /// let x = vec![1i,2,3,7,8,9];
484 /// assert_eq!(process(x.into_iter()), 6);
485 /// let x = vec![1i,2,3];
486 /// assert_eq!(process(x.into_iter()), 1006);
490 fn fuse(self) -> Fuse<Self> {
491 Fuse{iter: self, done: false}
494 /// Creates an iterator that calls a function with a reference to each
495 /// element before yielding it. This is often useful for debugging an
496 /// iterator pipeline.
501 /// use std::iter::AdditiveIterator;
503 /// let xs = [1u, 4, 2, 3, 8, 9, 6];
504 /// let sum = xs.iter()
506 /// .inspect(|&x| println!("filtering {}", x))
507 /// .filter(|&x| x % 2 == 0)
508 /// .inspect(|&x| println!("{} made it through", x))
510 /// println!("{}", sum);
514 fn inspect<F>(self, f: F) -> Inspect<Self::Item, Self, F> where
515 F: FnMut(&Self::Item),
517 Inspect{iter: self, f: f}
520 /// Creates a wrapper around a mutable reference to the iterator.
522 /// This is useful to allow applying iterator adaptors while still
523 /// retaining ownership of the original iterator value.
528 /// let mut xs = range(0u, 10);
529 /// // sum the first five values
530 /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
531 /// assert!(partial_sum == 10);
532 /// // xs.next() is now `5`
533 /// assert!(xs.next() == Some(5));
536 fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
540 /// Loops through the entire iterator, collecting all of the elements into
541 /// a container implementing `FromIterator`.
546 /// let a = [1i, 2, 3, 4, 5];
547 /// let b: Vec<int> = a.iter().map(|&x| x).collect();
548 /// assert!(a.as_slice() == b.as_slice());
552 fn collect<B: FromIterator<Self::Item>>(self) -> B {
553 FromIterator::from_iter(self)
556 /// Loops through the entire iterator, collecting all of the elements into
557 /// one of two containers, depending on a predicate. The elements of the
558 /// first container satisfy the predicate, while the elements of the second
562 /// let vec = vec![1i, 2i, 3i, 4i];
563 /// let (even, odd): (Vec<int>, Vec<int>) = vec.into_iter().partition(|&n| n % 2 == 0);
564 /// assert_eq!(even, vec![2, 4]);
565 /// assert_eq!(odd, vec![1, 3]);
567 #[unstable = "recently added as part of collections reform"]
568 fn partition<B, F>(mut self, mut f: F) -> (B, B) where
569 B: Default + Extend<Self::Item>,
570 F: FnMut(&Self::Item) -> bool
572 let mut left: B = Default::default();
573 let mut right: B = Default::default();
577 left.extend(Some(x).into_iter())
579 right.extend(Some(x).into_iter())
586 /// Performs a fold operation over the entire iterator, returning the
587 /// eventual state at the end of the iteration.
592 /// let a = [1i, 2, 3, 4, 5];
593 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
597 fn fold<B, F>(mut self, init: B, mut f: F) -> B where
598 F: FnMut(B, Self::Item) -> B,
600 let mut accum = init;
607 /// Tests whether the predicate holds true for all elements in the iterator.
612 /// let a = [1i, 2, 3, 4, 5];
613 /// assert!(a.iter().all(|x| *x > 0));
614 /// assert!(!a.iter().all(|x| *x > 2));
618 fn all<F>(mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
619 for x in self { if !f(x) { return false; } }
623 /// Tests whether any element of an iterator satisfies the specified
629 /// let a = [1i, 2, 3, 4, 5];
630 /// let mut it = a.iter();
631 /// assert!(it.any(|x| *x == 3));
632 /// assert!(!it.any(|x| *x == 3));
636 fn any<F>(&mut self, mut f: F) -> bool where F: FnMut(Self::Item) -> bool {
637 for x in *self { if f(x) { return true; } }
641 /// Returns the first element satisfying the specified predicate.
643 /// Does not consume the iterator past the first found element.
646 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
647 P: FnMut(&Self::Item) -> bool,
650 if predicate(&x) { return Some(x) }
655 /// Return the index of the first element satisfying the specified predicate
658 fn position<P>(&mut self, mut predicate: P) -> Option<uint> where
659 P: FnMut(Self::Item) -> bool,
671 /// Return the index of the last element satisfying the specified predicate
673 /// If no element matches, None is returned.
676 fn rposition<P>(&mut self, mut predicate: P) -> Option<uint> where
677 P: FnMut(Self::Item) -> bool,
678 Self: ExactSizeIterator + DoubleEndedIterator
680 let len = self.len();
681 for i in range(0, len).rev() {
682 if predicate(self.next_back().expect("rposition: incorrect ExactSizeIterator")) {
689 /// Consumes the entire iterator to return the maximum element.
694 /// let a = [1i, 2, 3, 4, 5];
695 /// assert!(a.iter().max().unwrap() == &5);
699 fn max(self) -> Option<Self::Item> where Self::Item: Ord
701 self.fold(None, |max, x| {
704 Some(y) => Some(cmp::max(x, y))
709 /// Consumes the entire iterator to return the minimum element.
714 /// let a = [1i, 2, 3, 4, 5];
715 /// assert!(a.iter().min().unwrap() == &1);
719 fn min(self) -> Option<Self::Item> where Self::Item: Ord
721 self.fold(None, |min, x| {
724 Some(y) => Some(cmp::min(x, y))
729 /// `min_max` finds the minimum and maximum elements in the iterator.
731 /// The return type `MinMaxResult` is an enum of three variants:
733 /// - `NoElements` if the iterator is empty.
734 /// - `OneElement(x)` if the iterator has exactly one element.
735 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
736 /// values are equal if and only if there is more than one
737 /// element in the iterator and all elements are equal.
739 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
740 /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons.
745 /// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax};
747 /// let v: [int; 0] = [];
748 /// assert_eq!(v.iter().min_max(), NoElements);
751 /// assert!(v.iter().min_max() == OneElement(&1));
753 /// let v = [1i, 2, 3, 4, 5];
754 /// assert!(v.iter().min_max() == MinMax(&1, &5));
756 /// let v = [1i, 2, 3, 4, 5, 6];
757 /// assert!(v.iter().min_max() == MinMax(&1, &6));
759 /// let v = [1i, 1, 1, 1];
760 /// assert!(v.iter().min_max() == MinMax(&1, &1));
762 #[unstable = "return type may change"]
763 fn min_max(mut self) -> MinMaxResult<Self::Item> where Self::Item: Ord
765 let (mut min, mut max) = match self.next() {
766 None => return NoElements,
769 None => return OneElement(x),
770 Some(y) => if x < y {(x, y)} else {(y,x)}
776 // `first` and `second` are the two next elements we want to look at.
777 // We first compare `first` and `second` (#1). The smaller one is then compared to
778 // current minimum (#2). The larger one is compared to current maximum (#3). This
779 // way we do 3 comparisons for 2 elements.
780 let first = match self.next() {
784 let second = match self.next() {
788 } else if first > max {
796 if first < min {min = first;}
797 if max < second {max = second;}
799 if second < min {min = second;}
800 if max < first {max = first;}
807 /// Return the element that gives the maximum value from the
808 /// specified function.
813 /// use core::num::SignedInt;
815 /// let xs = [-3i, 0, 1, 5, -10];
816 /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
819 #[unstable = "may want to produce an Ordering directly; see #15311"]
820 fn max_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
821 F: FnMut(&Self::Item) -> B,
823 self.fold(None, |max: Option<(Self::Item, B)>, x| {
826 None => Some((x, x_val)),
827 Some((y, y_val)) => if x_val > y_val {
836 /// Return the element that gives the minimum value from the
837 /// specified function.
842 /// use core::num::SignedInt;
844 /// let xs = [-3i, 0, 1, 5, -10];
845 /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
848 #[unstable = "may want to produce an Ordering directly; see #15311"]
849 fn min_by<B: Ord, F>(self, mut f: F) -> Option<Self::Item> where
850 F: FnMut(&Self::Item) -> B,
852 self.fold(None, |min: Option<(Self::Item, B)>, x| {
855 None => Some((x, x_val)),
856 Some((y, y_val)) => if x_val < y_val {
865 /// Change the direction of the iterator
867 /// The flipped iterator swaps the ends on an iterator that can already
868 /// be iterated from the front and from the back.
871 /// If the iterator also implements RandomAccessIterator, the flipped
872 /// iterator is also random access, with the indices starting at the back
873 /// of the original iterator.
875 /// Note: Random access with flipped indices still only applies to the first
876 /// `uint::MAX` elements of the original iterator.
879 fn rev(self) -> Rev<Self> {
883 /// Converts an iterator of pairs into a pair of containers.
885 /// Loops through the entire iterator, collecting the first component of
886 /// each item into one new container, and the second component into another.
887 #[unstable = "recent addition"]
888 fn unzip<A, B, FromA, FromB>(mut self) -> (FromA, FromB) where
889 FromA: Default + Extend<A>,
890 FromB: Default + Extend<B>,
891 Self: Iterator<Item=(A, B)>,
893 struct SizeHint<A>(uint, Option<uint>);
894 impl<A> Iterator for SizeHint<A> {
897 fn next(&mut self) -> Option<A> { None }
898 fn size_hint(&self) -> (uint, Option<uint>) {
903 let (lo, hi) = self.size_hint();
904 let mut ts: FromA = Default::default();
905 let mut us: FromB = Default::default();
907 ts.extend(SizeHint(lo, hi));
908 us.extend(SizeHint(lo, hi));
911 ts.extend(Some(t).into_iter());
912 us.extend(Some(u).into_iter());
918 /// Creates an iterator that clones the elements it yields. Useful for converting an
919 /// Iterator<&T> to an Iterator<T>.
920 #[unstable = "recent addition"]
921 fn cloned<T, D>(self) -> Cloned<Self> where
922 Self: Iterator<Item=D>,
929 /// Repeats an iterator endlessly
934 /// use std::iter::count;
936 /// let a = count(1i,1i).take(1);
937 /// let mut cy = a.cycle();
938 /// assert_eq!(cy.next(), Some(1));
939 /// assert_eq!(cy.next(), Some(1));
943 fn cycle(self) -> Cycle<Self> where Self: Clone {
944 Cycle{orig: self.clone(), iter: self}
947 /// Use an iterator to reverse a container in place.
948 #[unstable = "uncertain about placement or widespread use"]
949 fn reverse_in_place<'a, T: 'a>(&mut self) where
950 Self: Iterator<Item=&'a mut T> + DoubleEndedIterator
953 match (self.next(), self.next_back()) {
954 (Some(x), Some(y)) => mem::swap(x, y),
962 impl<I> IteratorExt for I where I: Iterator {}
964 /// A range iterator able to yield elements from both ends
966 /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust
967 /// elements from the *same* range, and do not work independently of each other.
969 pub trait DoubleEndedIterator: Iterator {
970 /// Yield an element from the end of the range, returning `None` if the range is empty.
972 fn next_back(&mut self) -> Option<Self::Item>;
975 /// An object implementing random access indexing by `uint`
977 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
978 /// Calling `next()` or `next_back()` on a `RandomAccessIterator`
979 /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)`
980 /// after `it.next()` is called.
981 #[unstable = "not widely used, may be better decomposed into Index and ExactSizeIterator"]
982 pub trait RandomAccessIterator: Iterator {
983 /// Return the number of indexable elements. At most `std::uint::MAX`
984 /// elements are indexable, even if the iterator represents a longer range.
985 fn indexable(&self) -> uint;
987 /// Return an element at an index, or `None` if the index is out of bounds
988 fn idx(&mut self, index: uint) -> Option<Self::Item>;
991 /// An iterator that knows its exact length
993 /// This trait is a helper for iterators like the vector iterator, so that
994 /// it can support double-ended enumeration.
996 /// `Iterator::size_hint` *must* return the exact size of the iterator.
997 /// Note that the size must fit in `uint`.
999 pub trait ExactSizeIterator: Iterator {
1001 /// Return the exact length of the iterator.
1002 fn len(&self) -> uint {
1003 let (lower, upper) = self.size_hint();
1004 // Note: This assertion is overly defensive, but it checks the invariant
1005 // guaranteed by the trait. If this trait were rust-internal,
1006 // we could use debug_assert!; assert_eq! will check all Rust user
1007 // implementations too.
1008 assert_eq!(upper, Some(lower));
1013 // All adaptors that preserve the size of the wrapped iterator are fine
1014 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
1016 impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
1018 impl<A, I, F> ExactSizeIterator for Inspect<A, I, F> where
1019 I: ExactSizeIterator<Item=A>,
1023 impl<I> ExactSizeIterator for Rev<I> where I: ExactSizeIterator + DoubleEndedIterator {}
1025 impl<A, B, I, F> ExactSizeIterator for Map<A, B, I, F> where
1026 I: ExactSizeIterator<Item=A>,
1030 impl<A, B> ExactSizeIterator for Zip<A, B> where A: ExactSizeIterator, B: ExactSizeIterator {}
1032 /// An double-ended iterator with the direction inverted
1034 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1041 impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
1042 type Item = <I as Iterator>::Item;
1045 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1047 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
1051 impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
1053 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1056 #[unstable = "trait is experimental"]
1057 impl<I> RandomAccessIterator for Rev<I> where I: DoubleEndedIterator + RandomAccessIterator {
1059 fn indexable(&self) -> uint { self.iter.indexable() }
1061 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1062 let amt = self.indexable();
1063 self.iter.idx(amt - index - 1)
1067 /// A mutable reference to an iterator
1068 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1070 pub struct ByRef<'a, I:'a> {
1075 impl<'a, I> Iterator for ByRef<'a, I> where I: 'a + Iterator {
1076 type Item = <I as Iterator>::Item;
1079 fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
1081 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
1085 impl<'a, I> DoubleEndedIterator for ByRef<'a, I> where I: 'a + DoubleEndedIterator {
1087 fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
1090 /// A trait for iterators over elements which can be added together
1091 #[unstable = "needs to be re-evaluated as part of numerics reform"]
1092 pub trait AdditiveIterator<A> {
1093 /// Iterates over the entire iterator, summing up all the elements
1098 /// use std::iter::AdditiveIterator;
1100 /// let a = [1i, 2, 3, 4, 5];
1101 /// let mut it = a.iter().map(|&x| x);
1102 /// assert!(it.sum() == 15);
1107 macro_rules! impl_additive {
1108 ($A:ty, $init:expr) => {
1109 #[unstable = "trait is experimental"]
1110 impl<T: Iterator<Item=$A>> AdditiveIterator<$A> for T {
1112 fn sum(self) -> $A {
1113 self.fold($init, |acc, x| acc + x)
1118 impl_additive! { i8, 0 }
1119 impl_additive! { i16, 0 }
1120 impl_additive! { i32, 0 }
1121 impl_additive! { i64, 0 }
1122 impl_additive! { int, 0 }
1123 impl_additive! { u8, 0 }
1124 impl_additive! { u16, 0 }
1125 impl_additive! { u32, 0 }
1126 impl_additive! { u64, 0 }
1127 impl_additive! { uint, 0 }
1128 impl_additive! { f32, 0.0 }
1129 impl_additive! { f64, 0.0 }
1131 /// A trait for iterators over elements which can be multiplied together.
1132 #[unstable = "needs to be re-evaluated as part of numerics reform"]
1133 pub trait MultiplicativeIterator<A> {
1134 /// Iterates over the entire iterator, multiplying all the elements
1139 /// use std::iter::{count, MultiplicativeIterator};
1141 /// fn factorial(n: uint) -> uint {
1142 /// count(1u, 1).take_while(|&i| i <= n).product()
1144 /// assert!(factorial(0) == 1);
1145 /// assert!(factorial(1) == 1);
1146 /// assert!(factorial(5) == 120);
1148 fn product(self) -> A;
1151 macro_rules! impl_multiplicative {
1152 ($A:ty, $init:expr) => {
1153 #[unstable = "trait is experimental"]
1154 impl<T: Iterator<Item=$A>> MultiplicativeIterator<$A> for T {
1156 fn product(self) -> $A {
1157 self.fold($init, |acc, x| acc * x)
1162 impl_multiplicative! { i8, 1 }
1163 impl_multiplicative! { i16, 1 }
1164 impl_multiplicative! { i32, 1 }
1165 impl_multiplicative! { i64, 1 }
1166 impl_multiplicative! { int, 1 }
1167 impl_multiplicative! { u8, 1 }
1168 impl_multiplicative! { u16, 1 }
1169 impl_multiplicative! { u32, 1 }
1170 impl_multiplicative! { u64, 1 }
1171 impl_multiplicative! { uint, 1 }
1172 impl_multiplicative! { f32, 1.0 }
1173 impl_multiplicative! { f64, 1.0 }
1175 /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
1176 #[derive(Clone, PartialEq, Show)]
1177 #[unstable = "unclear whether such a fine-grained result is widely useful"]
1178 pub enum MinMaxResult<T> {
1182 /// Iterator with one element, so the minimum and maximum are the same
1185 /// More than one element in the iterator, the first element is not larger than the second
1189 impl<T: Clone> MinMaxResult<T> {
1190 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1191 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1192 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1193 /// performing this operation will make one clone of `x`.
1198 /// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
1200 /// let r: MinMaxResult<int> = NoElements;
1201 /// assert_eq!(r.into_option(), None);
1203 /// let r = OneElement(1i);
1204 /// assert_eq!(r.into_option(), Some((1,1)));
1206 /// let r = MinMax(1i,2i);
1207 /// assert_eq!(r.into_option(), Some((1,2)));
1209 #[unstable = "type is unstable"]
1210 pub fn into_option(self) -> Option<(T,T)> {
1213 OneElement(x) => Some((x.clone(), x)),
1214 MinMax(x, y) => Some((x, y))
1219 /// An iterator that clones the elements of an underlying iterator
1220 #[unstable = "recent addition"]
1221 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1223 pub struct Cloned<I> {
1228 impl<T, D, I> Iterator for Cloned<I> where
1231 I: Iterator<Item=D>,
1235 fn next(&mut self) -> Option<T> {
1236 self.it.next().cloned()
1239 fn size_hint(&self) -> (uint, Option<uint>) {
1245 impl<T, D, I> DoubleEndedIterator for Cloned<I> where
1248 I: DoubleEndedIterator<Item=D>,
1250 fn next_back(&mut self) -> Option<T> {
1251 self.it.next_back().cloned()
1256 impl<T, D, I> ExactSizeIterator for Cloned<I> where
1259 I: ExactSizeIterator<Item=D>,
1262 /// An iterator that repeats endlessly
1263 #[derive(Clone, Copy)]
1264 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1266 pub struct Cycle<I> {
1272 impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
1273 type Item = <I as Iterator>::Item;
1276 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1277 match self.iter.next() {
1278 None => { self.iter = self.orig.clone(); self.iter.next() }
1284 fn size_hint(&self) -> (uint, Option<uint>) {
1285 // the cycle iterator is either empty or infinite
1286 match self.orig.size_hint() {
1287 sz @ (0, Some(0)) => sz,
1288 (0, _) => (0, None),
1289 _ => (uint::MAX, None)
1294 #[unstable = "trait is experimental"]
1295 impl<I> RandomAccessIterator for Cycle<I> where
1296 I: Clone + RandomAccessIterator,
1299 fn indexable(&self) -> uint {
1300 if self.orig.indexable() > 0 {
1308 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1309 let liter = self.iter.indexable();
1310 let lorig = self.orig.indexable();
1313 } else if index < liter {
1314 self.iter.idx(index)
1316 self.orig.idx((index - liter) % lorig)
1321 /// An iterator that strings two iterators together
1323 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1325 pub struct Chain<A, B> {
1332 impl<T, A, B> Iterator for Chain<A, B> where A: Iterator<Item=T>, B: Iterator<Item=T> {
1336 fn next(&mut self) -> Option<T> {
1340 match self.a.next() {
1341 Some(x) => return Some(x),
1350 fn size_hint(&self) -> (uint, Option<uint>) {
1351 let (a_lower, a_upper) = self.a.size_hint();
1352 let (b_lower, b_upper) = self.b.size_hint();
1354 let lower = a_lower.saturating_add(b_lower);
1356 let upper = match (a_upper, b_upper) {
1357 (Some(x), Some(y)) => x.checked_add(y),
1366 impl<T, A, B> DoubleEndedIterator for Chain<A, B> where
1367 A: DoubleEndedIterator<Item=T>,
1368 B: DoubleEndedIterator<Item=T>,
1371 fn next_back(&mut self) -> Option<T> {
1372 match self.b.next_back() {
1374 None => self.a.next_back()
1379 #[unstable = "trait is experimental"]
1380 impl<T, A, B> RandomAccessIterator for Chain<A, B> where
1381 A: RandomAccessIterator<Item=T>,
1382 B: RandomAccessIterator<Item=T>,
1385 fn indexable(&self) -> uint {
1386 let (a, b) = (self.a.indexable(), self.b.indexable());
1391 fn idx(&mut self, index: uint) -> Option<T> {
1392 let len = self.a.indexable();
1396 self.b.idx(index - len)
1401 /// An iterator that iterates two other iterators simultaneously
1403 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1405 pub struct Zip<A, B> {
1411 impl<T, U, A, B> Iterator for Zip<A, B> where
1412 A: Iterator<Item = T>,
1413 B: Iterator<Item = U>,
1418 fn next(&mut self) -> Option<(T, U)> {
1419 match self.a.next() {
1421 Some(x) => match self.b.next() {
1423 Some(y) => Some((x, y))
1429 fn size_hint(&self) -> (uint, Option<uint>) {
1430 let (a_lower, a_upper) = self.a.size_hint();
1431 let (b_lower, b_upper) = self.b.size_hint();
1433 let lower = cmp::min(a_lower, b_lower);
1435 let upper = match (a_upper, b_upper) {
1436 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1437 (Some(x), None) => Some(x),
1438 (None, Some(y)) => Some(y),
1439 (None, None) => None
1447 impl<T, U, A, B> DoubleEndedIterator for Zip<A, B> where
1448 A: DoubleEndedIterator + ExactSizeIterator<Item=T>,
1449 B: DoubleEndedIterator + ExactSizeIterator<Item=U>,
1452 fn next_back(&mut self) -> Option<(T, U)> {
1453 let a_sz = self.a.len();
1454 let b_sz = self.b.len();
1456 // Adjust a, b to equal length
1458 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1460 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1463 match (self.a.next_back(), self.b.next_back()) {
1464 (Some(x), Some(y)) => Some((x, y)),
1465 (None, None) => None,
1466 _ => unreachable!(),
1471 #[unstable = "trait is experimental"]
1472 impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where
1473 A: RandomAccessIterator<Item=T>,
1474 B: RandomAccessIterator<Item=U>,
1477 fn indexable(&self) -> uint {
1478 cmp::min(self.a.indexable(), self.b.indexable())
1482 fn idx(&mut self, index: uint) -> Option<(T, U)> {
1483 match self.a.idx(index) {
1485 Some(x) => match self.b.idx(index) {
1487 Some(y) => Some((x, y))
1493 /// An iterator that maps the values of `iter` with `f`
1494 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1496 pub struct Map<A, B, I: Iterator<Item=A>, F: FnMut(A) -> B> {
1501 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1503 impl<A, B, I, F> Clone for Map<A, B, I, F> where
1504 I: Clone + Iterator<Item=A>,
1505 F: Clone + FnMut(A) -> B,
1507 fn clone(&self) -> Map<A, B, I, F> {
1509 iter: self.iter.clone(),
1515 impl<A, B, I, F> Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1517 fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1519 Some(a) => Some((self.f)(a)),
1526 impl<A, B, I, F> Iterator for Map<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> B {
1530 fn next(&mut self) -> Option<B> {
1531 let next = self.iter.next();
1536 fn size_hint(&self) -> (uint, Option<uint>) {
1537 self.iter.size_hint()
1542 impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where
1543 I: DoubleEndedIterator<Item=A>,
1547 fn next_back(&mut self) -> Option<B> {
1548 let next = self.iter.next_back();
1553 #[unstable = "trait is experimental"]
1554 impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where
1555 I: RandomAccessIterator<Item=A>,
1559 fn indexable(&self) -> uint {
1560 self.iter.indexable()
1564 fn idx(&mut self, index: uint) -> Option<B> {
1565 let elt = self.iter.idx(index);
1570 /// An iterator that filters the elements of `iter` with `predicate`
1571 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1573 pub struct Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1578 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1580 impl<A, I, P> Clone for Filter<A, I, P> where
1581 I: Clone + Iterator<Item=A>,
1582 P: Clone + FnMut(&A) -> bool,
1584 fn clone(&self) -> Filter<A, I, P> {
1586 iter: self.iter.clone(),
1587 predicate: self.predicate.clone(),
1593 impl<A, I, P> Iterator for Filter<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1597 fn next(&mut self) -> Option<A> {
1598 for x in self.iter {
1599 if (self.predicate)(&x) {
1609 fn size_hint(&self) -> (uint, Option<uint>) {
1610 let (_, upper) = self.iter.size_hint();
1611 (0, upper) // can't know a lower bound, due to the predicate
1616 impl<A, I, P> DoubleEndedIterator for Filter<A, I, P> where
1617 I: DoubleEndedIterator<Item=A>,
1618 P: FnMut(&A) -> bool,
1621 fn next_back(&mut self) -> Option<A> {
1622 for x in self.iter.by_ref().rev() {
1623 if (self.predicate)(&x) {
1631 /// An iterator that uses `f` to both filter and map elements from `iter`
1632 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1634 pub struct FilterMap<A, B, I, F> where I: Iterator<Item=A>, F: FnMut(A) -> Option<B> {
1639 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1641 impl<A, B, I, F> Clone for FilterMap<A, B, I, F> where
1642 I: Clone + Iterator<Item=A>,
1643 F: Clone + FnMut(A) -> Option<B>,
1645 fn clone(&self) -> FilterMap<A, B, I, F> {
1647 iter: self.iter.clone(),
1654 impl<A, B, I, F> Iterator for FilterMap<A, B, I, F> where
1655 I: Iterator<Item=A>,
1656 F: FnMut(A) -> Option<B>,
1661 fn next(&mut self) -> Option<B> {
1662 for x in self.iter {
1664 Some(y) => return Some(y),
1672 fn size_hint(&self) -> (uint, Option<uint>) {
1673 let (_, upper) = self.iter.size_hint();
1674 (0, upper) // can't know a lower bound, due to the predicate
1679 impl<A, B, I, F> DoubleEndedIterator for FilterMap<A, B, I, F> where
1680 I: DoubleEndedIterator<Item=A>,
1681 F: FnMut(A) -> Option<B>,
1684 fn next_back(&mut self) -> Option<B> {
1685 for x in self.iter.by_ref().rev() {
1687 Some(y) => return Some(y),
1695 /// An iterator that yields the current count and the element during iteration
1697 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1699 pub struct Enumerate<I> {
1705 impl<I> Iterator for Enumerate<I> where I: Iterator {
1706 type Item = (uint, <I as Iterator>::Item);
1709 fn next(&mut self) -> Option<(uint, <I as Iterator>::Item)> {
1710 match self.iter.next() {
1712 let ret = Some((self.count, a));
1721 fn size_hint(&self) -> (uint, Option<uint>) {
1722 self.iter.size_hint()
1727 impl<I> DoubleEndedIterator for Enumerate<I> where
1728 I: ExactSizeIterator + DoubleEndedIterator
1731 fn next_back(&mut self) -> Option<(uint, <I as Iterator>::Item)> {
1732 match self.iter.next_back() {
1734 let len = self.iter.len();
1735 Some((self.count + len, a))
1742 #[unstable = "trait is experimental"]
1743 impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator {
1745 fn indexable(&self) -> uint {
1746 self.iter.indexable()
1750 fn idx(&mut self, index: uint) -> Option<(uint, <I as Iterator>::Item)> {
1751 match self.iter.idx(index) {
1752 Some(a) => Some((self.count + index, a)),
1758 /// An iterator with a `peek()` that returns an optional reference to the next element.
1759 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1762 pub struct Peekable<T, I> where I: Iterator<Item=T> {
1768 impl<T, I> Iterator for Peekable<T, I> where I: Iterator<Item=T> {
1772 fn next(&mut self) -> Option<T> {
1773 if self.peeked.is_some() { self.peeked.take() }
1774 else { self.iter.next() }
1778 fn size_hint(&self) -> (uint, Option<uint>) {
1779 let (lo, hi) = self.iter.size_hint();
1780 if self.peeked.is_some() {
1781 let lo = lo.saturating_add(1);
1783 Some(x) => x.checked_add(1),
1794 impl<T, I> Peekable<T, I> where I: Iterator<Item=T> {
1795 /// Return a reference to the next element of the iterator with out advancing it,
1796 /// or None if the iterator is exhausted.
1798 pub fn peek(&mut self) -> Option<&T> {
1799 if self.peeked.is_none() {
1800 self.peeked = self.iter.next();
1803 Some(ref value) => Some(value),
1808 /// Check whether peekable iterator is empty or not.
1810 pub fn is_empty(&mut self) -> bool {
1811 self.peek().is_none()
1815 /// An iterator that rejects elements while `predicate` is true
1816 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1818 pub struct SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1824 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1826 impl<A, I, P> Clone for SkipWhile<A, I, P> where
1827 I: Clone + Iterator<Item=A>,
1828 P: Clone + FnMut(&A) -> bool,
1830 fn clone(&self) -> SkipWhile<A, I, P> {
1832 iter: self.iter.clone(),
1834 predicate: self.predicate.clone(),
1840 impl<A, I, P> Iterator for SkipWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1844 fn next(&mut self) -> Option<A> {
1845 for x in self.iter {
1846 if self.flag || !(self.predicate)(&x) {
1855 fn size_hint(&self) -> (uint, Option<uint>) {
1856 let (_, upper) = self.iter.size_hint();
1857 (0, upper) // can't know a lower bound, due to the predicate
1861 /// An iterator that only accepts elements while `predicate` is true
1862 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1864 pub struct TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1870 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1872 impl<A, I, P> Clone for TakeWhile<A, I, P> where
1873 I: Clone + Iterator<Item=A>,
1874 P: Clone + FnMut(&A) -> bool,
1876 fn clone(&self) -> TakeWhile<A, I, P> {
1878 iter: self.iter.clone(),
1880 predicate: self.predicate.clone(),
1886 impl<A, I, P> Iterator for TakeWhile<A, I, P> where I: Iterator<Item=A>, P: FnMut(&A) -> bool {
1890 fn next(&mut self) -> Option<A> {
1894 match self.iter.next() {
1896 if (self.predicate)(&x) {
1909 fn size_hint(&self) -> (uint, Option<uint>) {
1910 let (_, upper) = self.iter.size_hint();
1911 (0, upper) // can't know a lower bound, due to the predicate
1915 /// An iterator that skips over `n` elements of `iter`.
1917 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1919 pub struct Skip<I> {
1925 impl<I> Iterator for Skip<I> where I: Iterator {
1926 type Item = <I as Iterator>::Item;
1929 fn next(&mut self) -> Option<<I as Iterator>::Item> {
1930 let mut next = self.iter.next();
1939 next = self.iter.next();
1954 fn size_hint(&self) -> (uint, Option<uint>) {
1955 let (lower, upper) = self.iter.size_hint();
1957 let lower = lower.saturating_sub(self.n);
1959 let upper = match upper {
1960 Some(x) => Some(x.saturating_sub(self.n)),
1968 #[unstable = "trait is experimental"]
1969 impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{
1971 fn indexable(&self) -> uint {
1972 self.iter.indexable().saturating_sub(self.n)
1976 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
1977 if index >= self.indexable() {
1980 self.iter.idx(index + self.n)
1985 /// An iterator that only iterates over the first `n` iterations of `iter`.
1987 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1989 pub struct Take<I> {
1995 impl<I> Iterator for Take<I> where I: Iterator{
1996 type Item = <I as Iterator>::Item;
1999 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2009 fn size_hint(&self) -> (uint, Option<uint>) {
2010 let (lower, upper) = self.iter.size_hint();
2012 let lower = cmp::min(lower, self.n);
2014 let upper = match upper {
2015 Some(x) if x < self.n => Some(x),
2023 #[unstable = "trait is experimental"]
2024 impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{
2026 fn indexable(&self) -> uint {
2027 cmp::min(self.iter.indexable(), self.n)
2031 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
2032 if index >= self.n {
2035 self.iter.idx(index)
2041 /// An iterator to maintain state while iterating another iterator
2042 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2044 pub struct Scan<A, B, I, St, F> where I: Iterator, F: FnMut(&mut St, A) -> Option<B> {
2048 /// The current internal state to be passed to the closure next.
2052 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2054 impl<A, B, I, St, F> Clone for Scan<A, B, I, St, F> where
2055 I: Clone + Iterator<Item=A>,
2057 F: Clone + FnMut(&mut St, A) -> Option<B>,
2059 fn clone(&self) -> Scan<A, B, I, St, F> {
2061 iter: self.iter.clone(),
2063 state: self.state.clone(),
2069 impl<A, B, I, St, F> Iterator for Scan<A, B, I, St, F> where
2070 I: Iterator<Item=A>,
2071 F: FnMut(&mut St, A) -> Option<B>,
2076 fn next(&mut self) -> Option<B> {
2077 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
2081 fn size_hint(&self) -> (uint, Option<uint>) {
2082 let (_, upper) = self.iter.size_hint();
2083 (0, upper) // can't know a lower bound, due to the scan function
2087 /// An iterator that maps each element to an iterator,
2088 /// and yields the elements of the produced iterators
2090 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2092 pub struct FlatMap<A, B, I, U, F> where
2093 I: Iterator<Item=A>,
2094 U: Iterator<Item=B>,
2099 frontiter: Option<U>,
2100 backiter: Option<U>,
2103 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2105 impl<A, B, I, U, F> Clone for FlatMap<A, B, I, U, F> where
2106 I: Clone + Iterator<Item=A>,
2107 U: Clone + Iterator<Item=B>,
2108 F: Clone + FnMut(A) -> U,
2110 fn clone(&self) -> FlatMap<A, B, I, U, F> {
2112 iter: self.iter.clone(),
2114 frontiter: self.frontiter.clone(),
2115 backiter: self.backiter.clone(),
2121 impl<A, B, I, U, F> Iterator for FlatMap<A, B, I, U, F> where
2122 I: Iterator<Item=A>,
2123 U: Iterator<Item=B>,
2129 fn next(&mut self) -> Option<B> {
2131 for inner in self.frontiter.iter_mut() {
2136 match self.iter.next().map(|x| (self.f)(x)) {
2137 None => return self.backiter.as_mut().and_then(|it| it.next()),
2138 next => self.frontiter = next,
2144 fn size_hint(&self) -> (uint, Option<uint>) {
2145 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2146 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
2147 let lo = flo.saturating_add(blo);
2148 match (self.iter.size_hint(), fhi, bhi) {
2149 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
2156 impl<A, B, I, U, F> DoubleEndedIterator for FlatMap<A, B, I, U, F> where
2157 I: DoubleEndedIterator<Item=A>,
2158 U: DoubleEndedIterator<Item=B>,
2162 fn next_back(&mut self) -> Option<B> {
2164 for inner in self.backiter.iter_mut() {
2165 match inner.next_back() {
2170 match self.iter.next_back().map(|x| (self.f)(x)) {
2171 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
2172 next => self.backiter = next,
2178 /// An iterator that yields `None` forever after the underlying iterator
2179 /// yields `None` once.
2181 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2183 pub struct Fuse<I> {
2189 impl<I> Iterator for Fuse<I> where I: Iterator {
2190 type Item = <I as Iterator>::Item;
2193 fn next(&mut self) -> Option<<I as Iterator>::Item> {
2197 match self.iter.next() {
2208 fn size_hint(&self) -> (uint, Option<uint>) {
2212 self.iter.size_hint()
2218 impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
2220 fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
2224 match self.iter.next_back() {
2235 // Allow RandomAccessIterators to be fused without affecting random-access behavior
2236 #[unstable = "trait is experimental"]
2237 impl<I> RandomAccessIterator for Fuse<I> where I: RandomAccessIterator {
2239 fn indexable(&self) -> uint {
2240 self.iter.indexable()
2244 fn idx(&mut self, index: uint) -> Option<<I as Iterator>::Item> {
2245 self.iter.idx(index)
2250 /// Resets the fuse such that the next call to .next() or .next_back() will
2251 /// call the underlying iterator again even if it previously returned None.
2253 #[unstable = "seems marginal"]
2254 pub fn reset_fuse(&mut self) {
2259 /// An iterator that calls a function with a reference to each
2260 /// element before yielding it.
2261 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
2263 pub struct Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2268 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2270 impl<A, I, F> Clone for Inspect<A, I, F> where
2271 I: Clone + Iterator<Item=A>,
2272 F: Clone + FnMut(&A),
2274 fn clone(&self) -> Inspect<A, I, F> {
2276 iter: self.iter.clone(),
2282 impl<A, I, F> Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2284 fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
2286 Some(ref a) => (self.f)(a),
2295 impl<A, I, F> Iterator for Inspect<A, I, F> where I: Iterator<Item=A>, F: FnMut(&A) {
2299 fn next(&mut self) -> Option<A> {
2300 let next = self.iter.next();
2301 self.do_inspect(next)
2305 fn size_hint(&self) -> (uint, Option<uint>) {
2306 self.iter.size_hint()
2311 impl<A, I, F> DoubleEndedIterator for Inspect<A, I, F> where
2312 I: DoubleEndedIterator<Item=A>,
2316 fn next_back(&mut self) -> Option<A> {
2317 let next = self.iter.next_back();
2318 self.do_inspect(next)
2322 #[unstable = "trait is experimental"]
2323 impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where
2324 I: RandomAccessIterator<Item=A>,
2328 fn indexable(&self) -> uint {
2329 self.iter.indexable()
2333 fn idx(&mut self, index: uint) -> Option<A> {
2334 let element = self.iter.idx(index);
2335 self.do_inspect(element)
2339 /// An iterator that passes mutable state to a closure and yields the result.
2341 /// # Example: The Fibonacci Sequence
2343 /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2346 /// use std::iter::Unfold;
2347 /// use std::num::Int; // For `.checked_add()`
2349 /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2350 /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2351 /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| {
2352 /// // Attempt to get the next Fibonacci number
2353 /// // `x1` will be `None` if previously overflowed.
2354 /// let next = match (*x2, *x1) {
2355 /// (Some(x2), Some(x1)) => x2.checked_add(x1),
2359 /// // Shift left: ret <- x2 <- x1 <- next
2367 /// for i in fibonacci {
2368 /// println!("{}", i);
2372 pub struct Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2374 /// Internal state that will be passed to the closure on the next iteration
2378 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2380 impl<A, St, F> Clone for Unfold<A, St, F> where
2381 F: Clone + FnMut(&mut St) -> Option<A>,
2384 fn clone(&self) -> Unfold<A, St, F> {
2387 state: self.state.clone(),
2393 impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2394 /// Creates a new iterator with the specified closure as the "iterator
2395 /// function" and an initial state to eventually pass to the closure
2397 pub fn new(initial_state: St, f: F) -> Unfold<A, St, F> {
2400 state: initial_state
2406 impl<A, St, F> Iterator for Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> {
2410 fn next(&mut self) -> Option<A> {
2411 (self.f)(&mut self.state)
2415 fn size_hint(&self) -> (uint, Option<uint>) {
2416 // no possible known bounds at this point
2421 /// An infinite iterator starting at `start` and advancing by `step` with each
2423 #[derive(Clone, Copy)]
2424 #[unstable = "may be renamed or replaced by range notation adapaters"]
2425 pub struct Counter<A> {
2426 /// The current state the counter is at (next value to be yielded)
2428 /// The amount that this iterator is stepping by
2432 /// Creates a new counter with the specified start/step
2434 #[unstable = "may be renamed or replaced by range notation adapaters"]
2435 pub fn count<A>(start: A, step: A) -> Counter<A> {
2436 Counter{state: start, step: step}
2440 impl<A: Add<Output=A> + Clone> Iterator for Counter<A> {
2444 fn next(&mut self) -> Option<A> {
2445 let result = self.state.clone();
2446 self.state = self.state.clone() + self.step.clone();
2451 fn size_hint(&self) -> (uint, Option<uint>) {
2452 (uint::MAX, None) // Too bad we can't specify an infinite lower bound
2456 /// An iterator over the range [start, stop)
2457 #[derive(Clone, Copy)]
2458 #[unstable = "will be replaced by range notation"]
2459 pub struct Range<A> {
2465 /// Returns an iterator over the given range [start, stop) (that is, starting
2466 /// at start (inclusive), and ending at stop (exclusive)).
2471 /// let array = [0, 1, 2, 3, 4];
2473 /// for i in range(0, 5u) {
2474 /// println!("{}", i);
2475 /// assert_eq!(i, array[i]);
2479 #[unstable = "will be replaced by range notation"]
2480 pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
2488 // FIXME: #10414: Unfortunate type bound
2489 #[unstable = "will be replaced by range notation"]
2490 impl<A: Int + ToPrimitive> Iterator for Range<A> {
2494 fn next(&mut self) -> Option<A> {
2495 if self.state < self.stop {
2496 let result = self.state.clone();
2497 self.state = self.state + self.one;
2505 fn size_hint(&self) -> (uint, Option<uint>) {
2506 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
2507 // handle cases like range(huge, huger)). We don't use uint/int because the difference of
2508 // the i64/u64 might lie within their range.
2509 let bound = match self.state.to_i64() {
2511 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
2513 Some(Some(bound)) => bound.to_uint(),
2517 None => match self.state.to_u64() {
2519 let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
2521 Some(Some(bound)) => bound.to_uint(),
2530 Some(b) => (b, Some(b)),
2531 // Standard fallback for unbounded/unrepresentable bounds
2537 /// `Int` is required to ensure the range will be the same regardless of
2538 /// the direction it is consumed.
2539 #[unstable = "will be replaced by range notation"]
2540 impl<A: Int + ToPrimitive> DoubleEndedIterator for Range<A> {
2542 fn next_back(&mut self) -> Option<A> {
2543 if self.stop > self.state {
2544 self.stop = self.stop - self.one;
2545 Some(self.stop.clone())
2552 /// An iterator over the range [start, stop]
2554 #[unstable = "likely to be replaced by range notation and adapters"]
2555 pub struct RangeInclusive<A> {
2560 /// Return an iterator over the range [start, stop]
2562 #[unstable = "likely to be replaced by range notation and adapters"]
2563 pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
2565 range: range(start, stop),
2570 #[unstable = "likely to be replaced by range notation and adapters"]
2571 impl<A: Int + ToPrimitive> Iterator for RangeInclusive<A> {
2575 fn next(&mut self) -> Option<A> {
2576 match self.range.next() {
2579 if !self.done && self.range.state == self.range.stop {
2581 Some(self.range.stop.clone())
2590 fn size_hint(&self) -> (uint, Option<uint>) {
2591 let (lo, hi) = self.range.size_hint();
2595 let lo = lo.saturating_add(1);
2597 Some(x) => x.checked_add(1),
2605 #[unstable = "likely to be replaced by range notation and adapters"]
2606 impl<A: Int + ToPrimitive> DoubleEndedIterator for RangeInclusive<A> {
2608 fn next_back(&mut self) -> Option<A> {
2609 if self.range.stop > self.range.state {
2610 let result = self.range.stop.clone();
2611 self.range.stop = self.range.stop - self.range.one;
2613 } else if !self.done && self.range.state == self.range.stop {
2615 Some(self.range.stop.clone())
2622 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2624 #[unstable = "likely to be replaced by range notation and adapters"]
2625 pub struct RangeStep<A> {
2632 /// Return 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 fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
2636 let rev = step < Int::zero();
2637 RangeStep{state: start, stop: stop, step: step, rev: rev}
2640 #[unstable = "likely to be replaced by range notation and adapters"]
2641 impl<A: Int> Iterator for RangeStep<A> {
2645 fn next(&mut self) -> Option<A> {
2646 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2647 let result = self.state;
2648 match self.state.checked_add(self.step) {
2649 Some(x) => self.state = x,
2650 None => self.state = self.stop.clone()
2659 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2661 #[unstable = "likely to be replaced by range notation and adapters"]
2662 pub struct RangeStepInclusive<A> {
2670 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2672 #[unstable = "likely to be replaced by range notation and adapters"]
2673 pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
2674 let rev = step < Int::zero();
2675 RangeStepInclusive {
2684 #[unstable = "likely to be replaced by range notation and adapters"]
2685 impl<A: Int> Iterator for RangeStepInclusive<A> {
2689 fn next(&mut self) -> Option<A> {
2690 if !self.done && ((self.rev && self.state >= self.stop) ||
2691 (!self.rev && self.state <= self.stop)) {
2692 let result = self.state;
2693 match self.state.checked_add(self.step) {
2694 Some(x) => self.state = x,
2695 None => self.done = true
2705 /// The `Step` trait identifies objects which can be stepped over in both
2706 /// directions. The `steps_between` function provides a way to
2707 /// compare two Step objects (it could be provided using `step()` and `Ord`,
2708 /// but the implementation would be so inefficient as to be useless).
2709 #[unstable = "design of range notation/iteration is in flux"]
2710 pub trait Step: Ord {
2711 /// Change self to the next object.
2713 /// Change self to the previous object.
2714 fn step_back(&mut self);
2715 /// The steps_between two step objects.
2716 /// start should always be less than end, so the result should never be negative.
2717 /// Return None if it is not possible to calculate steps_between without
2719 fn steps_between(start: &Self, end: &Self) -> Option<uint>;
2722 macro_rules! step_impl {
2724 #[unstable = "Trait is unstable."]
2727 fn step(&mut self) { *self += 1; }
2729 fn step_back(&mut self) { *self -= 1; }
2731 fn steps_between(start: &$t, end: &$t) -> Option<uint> {
2732 debug_assert!(end >= start);
2733 Some((*end - *start) as uint)
2739 macro_rules! step_impl_no_between {
2741 #[unstable = "Trait is unstable."]
2744 fn step(&mut self) { *self += 1; }
2746 fn step_back(&mut self) { *self -= 1; }
2748 fn steps_between(_start: &$t, _end: &$t) -> Option<uint> {
2755 step_impl!(uint u8 u16 u32 int i8 i16 i32);
2756 #[cfg(target_pointer_width = "64")]
2757 step_impl!(u64 i64);
2758 #[cfg(target_pointer_width = "32")]
2759 step_impl_no_between!(u64 i64);
2762 /// An iterator that repeats an element endlessly
2765 pub struct Repeat<A> {
2770 impl<A: Clone> Iterator for Repeat<A> {
2774 fn next(&mut self) -> Option<A> { self.idx(0) }
2776 fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2780 impl<A: Clone> DoubleEndedIterator for Repeat<A> {
2782 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2785 #[unstable = "trait is experimental"]
2786 impl<A: Clone> RandomAccessIterator for Repeat<A> {
2788 fn indexable(&self) -> uint { uint::MAX }
2790 fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
2793 type IterateState<T, F> = (F, Option<T>, bool);
2795 /// An iterator that repeatedly applies a given function, starting
2796 /// from a given seed value.
2798 pub type Iterate<T, F> = Unfold<T, IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>;
2800 /// Create a new iterator that produces an infinite sequence of
2801 /// repeated applications of the given function `f`.
2803 pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where
2807 fn next<T, F>(st: &mut IterateState<T, F>) -> Option<T> where
2811 let &mut (ref mut f, ref mut val, ref mut first) = st;
2817 *val = Some((*f)(x))
2825 // coerce to a fn pointer
2826 let next: fn(&mut IterateState<T,F>) -> Option<T> = next;
2828 Unfold::new((f, Some(seed), true), next)
2831 /// Create a new iterator that endlessly repeats the element `elt`.
2834 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
2835 Repeat{element: elt}
2838 /// Functions for lexicographical ordering of sequences.
2840 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2841 /// that the elements implement both `PartialEq` and `PartialOrd`.
2843 /// If two sequences are equal up until the point where one ends,
2844 /// the shorter sequence compares less.
2845 #[unstable = "needs review and revision"]
2848 use cmp::{Eq, Ord, PartialOrd, PartialEq};
2849 use cmp::Ordering::{Equal, Less, Greater};
2851 use option::Option::{Some, None};
2852 use super::Iterator;
2854 /// Compare `a` and `b` for equality using `Eq`
2855 pub fn equals<A, T, S>(mut a: T, mut b: S) -> bool where
2857 T: Iterator<Item=A>,
2858 S: Iterator<Item=A>,
2861 match (a.next(), b.next()) {
2862 (None, None) => return true,
2863 (None, _) | (_, None) => return false,
2864 (Some(x), Some(y)) => if x != y { return false },
2869 /// Order `a` and `b` lexicographically using `Ord`
2870 pub fn cmp<A, T, S>(mut a: T, mut b: S) -> cmp::Ordering where
2872 T: Iterator<Item=A>,
2873 S: Iterator<Item=A>,
2876 match (a.next(), b.next()) {
2877 (None, None) => return Equal,
2878 (None, _ ) => return Less,
2879 (_ , None) => return Greater,
2880 (Some(x), Some(y)) => match x.cmp(&y) {
2882 non_eq => return non_eq,
2888 /// Order `a` and `b` lexicographically using `PartialOrd`
2889 pub fn partial_cmp<A, T, S>(mut a: T, mut b: S) -> Option<cmp::Ordering> where
2891 T: Iterator<Item=A>,
2892 S: Iterator<Item=A>,
2895 match (a.next(), b.next()) {
2896 (None, None) => return Some(Equal),
2897 (None, _ ) => return Some(Less),
2898 (_ , None) => return Some(Greater),
2899 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2901 non_eq => return non_eq,
2907 /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
2908 pub fn eq<A, B, L, R>(mut a: L, mut b: R) -> bool where
2910 L: Iterator<Item=A>,
2911 R: Iterator<Item=B>,
2914 match (a.next(), b.next()) {
2915 (None, None) => return true,
2916 (None, _) | (_, None) => return false,
2917 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2922 /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`)
2923 pub fn ne<A, B, L, R>(mut a: L, mut b: R) -> bool where
2925 L: Iterator<Item=A>,
2926 R: Iterator<Item=B>,
2929 match (a.next(), b.next()) {
2930 (None, None) => return false,
2931 (None, _) | (_, None) => return true,
2932 (Some(x), Some(y)) => if x.ne(&y) { return true },
2937 /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`)
2938 pub fn lt<A, T, S>(mut a: T, mut b: S) -> bool where
2940 T: Iterator<Item=A>,
2941 S: Iterator<Item=A>,
2944 match (a.next(), b.next()) {
2945 (None, None) => return false,
2946 (None, _ ) => return true,
2947 (_ , None) => return false,
2948 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2953 /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
2954 pub fn le<A, T, S>(mut a: T, mut b: S) -> bool where
2956 T: Iterator<Item=A>,
2957 S: Iterator<Item=A>,
2960 match (a.next(), b.next()) {
2961 (None, None) => return true,
2962 (None, _ ) => return true,
2963 (_ , None) => return false,
2964 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2969 /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`)
2970 pub fn gt<A, T, S>(mut a: T, mut b: S) -> bool where
2972 T: Iterator<Item=A>,
2973 S: Iterator<Item=A>,
2976 match (a.next(), b.next()) {
2977 (None, None) => return false,
2978 (None, _ ) => return false,
2979 (_ , None) => return true,
2980 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2985 /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
2986 pub fn ge<A, T, S>(mut a: T, mut b: S) -> bool where
2988 T: Iterator<Item=A>,
2989 S: Iterator<Item=A>,
2992 match (a.next(), b.next()) {
2993 (None, None) => return true,
2994 (None, _ ) => return false,
2995 (_ , None) => return true,
2996 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },