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.
13 Composable external iterators
15 # The `Iterator` trait
17 This module defines Rust's core iteration trait. The `Iterator` trait has one
18 unimplemented method, `next`. All other methods are derived through default
19 methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.
21 The goal of this module is to unify iteration across all containers in Rust.
22 An iterator can be considered as a state machine which is used to track which
23 element will be yielded next.
25 There are various extensions also defined in this module to assist with various
26 types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
27 the `FromIterator` trait for creating a container from an iterator, and much
32 The special syntax used by rust's `for` loop is based around the `Iterator`
33 trait defined in this module. For loops can be viewed as a syntactical expansion
34 into a `loop`, for example, the `for` loop in this example is essentially
35 translated to the `loop` below.
38 let values = ~[1, 2, 3];
40 // "Syntactical sugar" taking advantage of an iterator
41 for &x in values.iter() {
45 // Rough translation of the iteration without a `for` iterator.
46 let mut it = values.iter();
57 This `for` loop syntax can be applied to any iterator over any type.
59 ## Iteration protocol and more
61 More detailed information about iterators can be found in the [container
62 guide](http://static.rust-lang.org/doc/master/guide-container.html) with
63 the rest of the rust manuals.
68 use num::{Zero, One, CheckedAdd, CheckedSub, Saturating, ToPrimitive, Int};
69 use option::{Option, Some, None};
70 use ops::{Add, Mul, Sub};
71 use cmp::{Eq, Ord, TotalOrd};
76 /// Conversion from an `Iterator`
77 pub trait FromIterator<A> {
78 /// Build a container with elements from an external iterator.
79 fn from_iter<T: Iterator<A>>(iterator: T) -> Self;
82 /// A type growable from an `Iterator` implementation
83 pub trait Extendable<A>: FromIterator<A> {
84 /// Extend a container with the elements yielded by an iterator
85 fn extend<T: Iterator<A>>(&mut self, iterator: T);
88 /// An interface for dealing with "external iterators". These types of iterators
89 /// can be resumed at any time as all state is stored internally as opposed to
90 /// being located on the call stack.
92 /// The Iterator protocol states that an iterator yields a (potentially-empty,
93 /// potentially-infinite) sequence of values, and returns `None` to signal that
94 /// it's finished. The Iterator protocol does not define behavior after `None`
95 /// is returned. A concrete Iterator implementation may choose to behave however
96 /// it wishes, either by returning `None` infinitely, or by doing something
98 pub trait Iterator<A> {
99 /// Advance the iterator and return the next value. Return `None` when the end is reached.
100 fn next(&mut self) -> Option<A>;
102 /// Return a lower bound and upper bound on the remaining length of the iterator.
104 /// The common use case for the estimate is pre-allocating space to store the results.
106 fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
108 /// Chain this iterator with another, returning a new iterator which will
109 /// finish iterating over the current iterator, and then it will iterate
110 /// over the other specified iterator.
117 /// let mut it = a.iter().chain(b.iter());
118 /// assert_eq!(it.next().unwrap(), &0);
119 /// assert_eq!(it.next().unwrap(), &1);
120 /// assert!(it.next().is_none());
123 fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
124 Chain{a: self, b: other, flag: false}
127 /// Creates an iterator which iterates over both this and the specified
128 /// iterators simultaneously, yielding the two elements as pairs. When
129 /// either iterator returns None, all further invocations of next() will
137 /// let mut it = a.iter().zip(b.iter());
138 /// assert_eq!(it.next().unwrap(), (&0, &1));
139 /// assert!(it.next().is_none());
142 fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
143 Zip{a: self, b: other}
146 /// Creates a new iterator which will apply the specified function to each
147 /// element returned by the first, yielding the mapped element instead.
153 /// let mut it = a.iter().map(|&x| 2 * x);
154 /// assert_eq!(it.next().unwrap(), 2);
155 /// assert_eq!(it.next().unwrap(), 4);
156 /// assert!(it.next().is_none());
159 fn map<'r, B>(self, f: |A|: 'r -> B) -> Map<'r, A, B, Self> {
160 Map{iter: self, f: f}
163 /// Creates an iterator which applies the predicate to each element returned
164 /// by this iterator. Only elements which have the predicate evaluate to
165 /// `true` will be yielded.
171 /// let mut it = a.iter().filter(|&x| *x > 1);
172 /// assert_eq!(it.next().unwrap(), &2);
173 /// assert!(it.next().is_none());
176 fn filter<'r>(self, predicate: |&A|: 'r -> bool) -> Filter<'r, A, Self> {
177 Filter{iter: self, predicate: predicate}
180 /// Creates an iterator which both filters and maps elements.
181 /// If the specified function returns None, the element is skipped.
182 /// Otherwise the option is unwrapped and the new value is yielded.
188 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
189 /// assert_eq!(it.next().unwrap(), 4);
190 /// assert!(it.next().is_none());
193 fn filter_map<'r, B>(self, f: |A|: 'r -> Option<B>) -> FilterMap<'r, A, B, Self> {
194 FilterMap { iter: self, f: f }
197 /// Creates an iterator which yields a pair of the value returned by this
198 /// iterator plus the current index of iteration.
203 /// let a = [100, 200];
204 /// let mut it = a.iter().enumerate();
205 /// assert_eq!(it.next().unwrap(), (0, &100));
206 /// assert_eq!(it.next().unwrap(), (1, &200));
207 /// assert!(it.next().is_none());
210 fn enumerate(self) -> Enumerate<Self> {
211 Enumerate{iter: self, count: 0}
215 /// Creates an iterator that has a `.peek()` method
216 /// that returns an optional reference to the next element.
221 /// let xs = [100, 200, 300];
222 /// let mut it = xs.iter().map(|x| *x).peekable();
223 /// assert_eq!(it.peek().unwrap(), &100);
224 /// assert_eq!(it.next().unwrap(), 100);
225 /// assert_eq!(it.next().unwrap(), 200);
226 /// assert_eq!(it.peek().unwrap(), &300);
227 /// assert_eq!(it.peek().unwrap(), &300);
228 /// assert_eq!(it.next().unwrap(), 300);
229 /// assert!(it.peek().is_none());
230 /// assert!(it.next().is_none());
233 fn peekable(self) -> Peekable<A, Self> {
234 Peekable{iter: self, peeked: None}
237 /// Creates an iterator which invokes the predicate on elements until it
238 /// returns false. Once the predicate returns false, all further elements are
244 /// let a = [1, 2, 3, 2, 1];
245 /// let mut it = a.iter().skip_while(|&a| *a < 3);
246 /// assert_eq!(it.next().unwrap(), &3);
247 /// assert_eq!(it.next().unwrap(), &2);
248 /// assert_eq!(it.next().unwrap(), &1);
249 /// assert!(it.next().is_none());
252 fn skip_while<'r>(self, predicate: |&A|: 'r -> bool) -> SkipWhile<'r, A, Self> {
253 SkipWhile{iter: self, flag: false, predicate: predicate}
256 /// Creates an iterator which yields elements so long as the predicate
257 /// returns true. After the predicate returns false for the first time, no
258 /// further elements will be yielded.
263 /// let a = [1, 2, 3, 2, 1];
264 /// let mut it = a.iter().take_while(|&a| *a < 3);
265 /// assert_eq!(it.next().unwrap(), &1);
266 /// assert_eq!(it.next().unwrap(), &2);
267 /// assert!(it.next().is_none());
270 fn take_while<'r>(self, predicate: |&A|: 'r -> bool) -> TakeWhile<'r, A, Self> {
271 TakeWhile{iter: self, flag: false, predicate: predicate}
274 /// Creates an iterator which skips the first `n` elements of this iterator,
275 /// and then it yields all further items.
280 /// let a = [1, 2, 3, 4, 5];
281 /// let mut it = a.iter().skip(3);
282 /// assert_eq!(it.next().unwrap(), &4);
283 /// assert_eq!(it.next().unwrap(), &5);
284 /// assert!(it.next().is_none());
287 fn skip(self, n: uint) -> Skip<Self> {
288 Skip{iter: self, n: n}
291 /// Creates an iterator which yields the first `n` elements of this
292 /// iterator, and then it will always return None.
297 /// let a = [1, 2, 3, 4, 5];
298 /// let mut it = a.iter().take(3);
299 /// assert_eq!(it.next().unwrap(), &1);
300 /// assert_eq!(it.next().unwrap(), &2);
301 /// assert_eq!(it.next().unwrap(), &3);
302 /// assert!(it.next().is_none());
305 fn take(self, n: uint) -> Take<Self> {
306 Take{iter: self, n: n}
309 /// Creates a new iterator which behaves in a similar fashion to fold.
310 /// There is a state which is passed between each iteration and can be
311 /// mutated as necessary. The yielded values from the closure are yielded
312 /// from the Scan instance when not None.
317 /// let a = [1, 2, 3, 4, 5];
318 /// let mut it = a.iter().scan(1, |fac, &x| {
322 /// assert_eq!(it.next().unwrap(), 1);
323 /// assert_eq!(it.next().unwrap(), 2);
324 /// assert_eq!(it.next().unwrap(), 6);
325 /// assert_eq!(it.next().unwrap(), 24);
326 /// assert_eq!(it.next().unwrap(), 120);
327 /// assert!(it.next().is_none());
330 fn scan<'r, St, B>(self, initial_state: St, f: |&mut St, A|: 'r -> Option<B>)
331 -> Scan<'r, A, B, Self, St> {
332 Scan{iter: self, f: f, state: initial_state}
335 /// Creates an iterator that maps each element to an iterator,
336 /// and yields the elements of the produced iterators
341 /// use std::iter::count;
343 /// let xs = [2u, 3];
344 /// let ys = [0u, 1, 0, 1, 2];
345 /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
346 /// // Check that `it` has the same elements as `ys`
349 /// assert_eq!(x, ys[i]);
354 fn flat_map<'r, B, U: Iterator<B>>(self, f: |A|: 'r -> U)
355 -> FlatMap<'r, A, Self, U> {
356 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
359 /// Creates an iterator that yields `None` forever after the underlying
360 /// iterator yields `None`. Random-access iterator behavior is not
361 /// affected, only single and double-ended iterator behavior.
366 /// fn process<U: Iterator<int>>(it: U) -> int {
367 /// let mut it = it.fuse();
375 /// // did we exhaust the iterator?
376 /// if it.next().is_none() {
381 /// let x = ~[1,2,3,7,8,9];
382 /// assert_eq!(process(x.move_iter()), 1006);
385 fn fuse(self) -> Fuse<Self> {
386 Fuse{iter: self, done: false}
389 /// Creates an iterator that calls a function with a reference to each
390 /// element before yielding it. This is often useful for debugging an
391 /// iterator pipeline.
396 /// use std::iter::AdditiveIterator;
398 /// let xs = [1u, 4, 2, 3, 8, 9, 6];
399 /// let sum = xs.iter()
401 /// .inspect(|&x| println!("filtering {}", x))
402 /// .filter(|&x| x % 2 == 0)
403 /// .inspect(|&x| println!("{} made it through", x))
405 /// println!("{}", sum);
408 fn inspect<'r>(self, f: |&A|: 'r) -> Inspect<'r, A, Self> {
409 Inspect{iter: self, f: f}
412 /// Creates a wrapper around a mutable reference to the iterator.
414 /// This is useful to allow applying iterator adaptors while still
415 /// retaining ownership of the original iterator value.
420 /// let mut xs = range(0, 10);
421 /// // sum the first five values
422 /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
423 /// assert!(partial_sum == 10);
424 /// // xs.next() is now `5`
425 /// assert!(xs.next() == Some(5));
427 fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
431 /// Apply a function to each element, or stop iterating if the
432 /// function returns `false`.
437 /// range(0, 5).advance(|x| {print!("{} ", x); true});
440 fn advance(&mut self, f: |A| -> bool) -> bool {
444 if !f(x) { return false; }
446 None => { return true; }
451 /// Loops through the entire iterator, collecting all of the elements into
452 /// a container implementing `FromIterator`.
457 /// let a = [1, 2, 3, 4, 5];
458 /// let b: ~[int] = a.iter().map(|&x| x).collect();
462 fn collect<B: FromIterator<A>>(&mut self) -> B {
463 FromIterator::from_iter(self.by_ref())
466 /// Loops through `n` iterations, returning the `n`th element of the
472 /// let a = [1, 2, 3, 4, 5];
473 /// let mut it = a.iter();
474 /// assert!(it.nth(2).unwrap() == &3);
475 /// assert!(it.nth(2) == None);
478 fn nth(&mut self, mut n: uint) -> Option<A> {
481 Some(x) => if n == 0 { return Some(x) },
488 /// Loops through the entire iterator, returning the last element of the
494 /// let a = [1, 2, 3, 4, 5];
495 /// assert!(a.iter().last().unwrap() == &5);
498 fn last(&mut self) -> Option<A> {
500 for x in *self { last = Some(x); }
504 /// Performs a fold operation over the entire iterator, returning the
505 /// eventual state at the end of the iteration.
510 /// let a = [1, 2, 3, 4, 5];
511 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
514 fn fold<B>(&mut self, init: B, f: |B, A| -> B) -> B {
515 let mut accum = init;
518 Some(x) => { accum = f(accum, x); }
525 /// Counts the number of elements in this iterator.
530 /// let a = [1, 2, 3, 4, 5];
531 /// let mut it = a.iter();
532 /// assert!(it.len() == 5);
533 /// assert!(it.len() == 0);
536 fn len(&mut self) -> uint {
537 self.fold(0, |cnt, _x| cnt + 1)
540 /// Tests whether the predicate holds true for all elements in the iterator.
545 /// let a = [1, 2, 3, 4, 5];
546 /// assert!(a.iter().all(|x| *x > 0));
547 /// assert!(!a.iter().all(|x| *x > 2));
550 fn all(&mut self, f: |A| -> bool) -> bool {
551 for x in *self { if !f(x) { return false; } }
555 /// Tests whether any element of an iterator satisfies the specified
561 /// let a = [1, 2, 3, 4, 5];
562 /// let mut it = a.iter();
563 /// assert!(it.any(|x| *x == 3));
564 /// assert!(!it.any(|x| *x == 3));
567 fn any(&mut self, f: |A| -> bool) -> bool {
568 for x in *self { if f(x) { return true; } }
572 /// Return the first element satisfying the specified predicate
574 fn find(&mut self, predicate: |&A| -> bool) -> Option<A> {
576 if predicate(&x) { return Some(x) }
581 /// Return the index of the first element satisfying the specified predicate
583 fn position(&mut self, predicate: |A| -> bool) -> Option<uint> {
594 /// Count the number of elements satisfying the specified predicate
596 fn count(&mut self, predicate: |A| -> bool) -> uint {
599 if predicate(x) { i += 1 }
604 /// Return the element that gives the maximum value from the
605 /// specified function.
610 /// let xs = [-3i, 0, 1, 5, -10];
611 /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
614 fn max_by<B: TotalOrd>(&mut self, f: |&A| -> B) -> Option<A> {
615 self.fold(None, |max: Option<(A, B)>, x| {
618 None => Some((x, x_val)),
619 Some((y, y_val)) => if x_val > y_val {
628 /// Return the element that gives the minimum value from the
629 /// specified function.
634 /// let xs = [-3i, 0, 1, 5, -10];
635 /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
638 fn min_by<B: TotalOrd>(&mut self, f: |&A| -> B) -> Option<A> {
639 self.fold(None, |min: Option<(A, B)>, x| {
642 None => Some((x, x_val)),
643 Some((y, y_val)) => if x_val < y_val {
653 /// A range iterator able to yield elements from both ends
654 pub trait DoubleEndedIterator<A>: Iterator<A> {
655 /// Yield an element from the end of the range, returning `None` if the range is empty.
656 fn next_back(&mut self) -> Option<A>;
658 /// Change the direction of the iterator
660 /// The flipped iterator swaps the ends on an iterator that can already
661 /// be iterated from the front and from the back.
664 /// If the iterator also implements RandomAccessIterator, the flipped
665 /// iterator is also random access, with the indices starting at the back
666 /// of the original iterator.
668 /// Note: Random access with flipped indices still only applies to the first
669 /// `uint::MAX` elements of the original iterator.
671 fn rev(self) -> Rev<Self> {
676 /// A double-ended iterator yielding mutable references
677 pub trait MutableDoubleEndedIterator {
678 // FIXME: #5898: should be called `reverse`
679 /// Use an iterator to reverse a container in-place
680 fn reverse_(&mut self);
683 impl<'a, A, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T {
684 // FIXME: #5898: should be called `reverse`
685 /// Use an iterator to reverse a container in-place
686 fn reverse_(&mut self) {
688 match (self.next(), self.next_back()) {
689 (Some(x), Some(y)) => mem::swap(x, y),
697 /// An object implementing random access indexing by `uint`
699 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
700 pub trait RandomAccessIterator<A>: Iterator<A> {
701 /// Return the number of indexable elements. At most `std::uint::MAX`
702 /// elements are indexable, even if the iterator represents a longer range.
703 fn indexable(&self) -> uint;
705 /// Return an element at an index
706 fn idx(&mut self, index: uint) -> Option<A>;
709 /// An iterator that knows its exact length
711 /// This trait is a helper for iterators like the vector iterator, so that
712 /// it can support double-ended enumeration.
714 /// `Iterator::size_hint` *must* return the exact size of the iterator.
715 /// Note that the size must fit in `uint`.
716 pub trait ExactSize<A> : DoubleEndedIterator<A> {
717 /// Return the index of the last element satisfying the specified predicate
719 /// If no element matches, None is returned.
721 fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> {
722 let (lower, upper) = self.size_hint();
723 assert!(upper == Some(lower));
726 match self.next_back() {
729 i = match i.checked_sub(&1) {
731 None => fail!("rposition: incorrect ExactSize")
743 // All adaptors that preserve the size of the wrapped iterator are fine
744 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
745 impl<A, T: ExactSize<A>> ExactSize<(uint, A)> for Enumerate<T> {}
746 impl<'a, A, T: ExactSize<A>> ExactSize<A> for Inspect<'a, A, T> {}
747 impl<A, T: ExactSize<A>> ExactSize<A> for Rev<T> {}
748 impl<'a, A, B, T: ExactSize<A>> ExactSize<B> for Map<'a, A, B, T> {}
749 impl<A, B, T: ExactSize<A>, U: ExactSize<B>> ExactSize<(A, B)> for Zip<T, U> {}
751 /// An double-ended iterator with the direction inverted
757 impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> {
759 fn next(&mut self) -> Option<A> { self.iter.next_back() }
761 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
764 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> {
766 fn next_back(&mut self) -> Option<A> { self.iter.next() }
769 impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
772 fn indexable(&self) -> uint { self.iter.indexable() }
774 fn idx(&mut self, index: uint) -> Option<A> {
775 let amt = self.indexable();
776 self.iter.idx(amt - index - 1)
780 /// A mutable reference to an iterator
781 pub struct ByRef<'a, T> {
785 impl<'a, A, T: Iterator<A>> Iterator<A> for ByRef<'a, T> {
787 fn next(&mut self) -> Option<A> { self.iter.next() }
789 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
792 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for ByRef<'a, T> {
794 fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
797 /// A trait for iterators over elements which can be added together
798 pub trait AdditiveIterator<A> {
799 /// Iterates over the entire iterator, summing up all the elements
804 /// use std::iter::AdditiveIterator;
806 /// let a = [1, 2, 3, 4, 5];
807 /// let mut it = a.iter().map(|&x| x);
808 /// assert!(it.sum() == 15);
810 fn sum(&mut self) -> A;
813 impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
815 fn sum(&mut self) -> A {
816 let zero: A = Zero::zero();
817 self.fold(zero, |s, x| s + x)
821 /// A trait for iterators over elements whose elements can be multiplied
823 pub trait MultiplicativeIterator<A> {
824 /// Iterates over the entire iterator, multiplying all the elements
829 /// use std::iter::{count, MultiplicativeIterator};
831 /// fn factorial(n: uint) -> uint {
832 /// count(1u, 1).take_while(|&i| i <= n).product()
834 /// assert!(factorial(0) == 1);
835 /// assert!(factorial(1) == 1);
836 /// assert!(factorial(5) == 120);
838 fn product(&mut self) -> A;
841 impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
843 fn product(&mut self) -> A {
844 let one: A = One::one();
845 self.fold(one, |p, x| p * x)
849 /// A trait for iterators over elements which can be compared to one another.
850 /// The type of each element must ascribe to the `Ord` trait.
851 pub trait OrdIterator<A> {
852 /// Consumes the entire iterator to return the maximum element.
857 /// let a = [1, 2, 3, 4, 5];
858 /// assert!(a.iter().max().unwrap() == &5);
860 fn max(&mut self) -> Option<A>;
862 /// Consumes the entire iterator to return the minimum element.
867 /// let a = [1, 2, 3, 4, 5];
868 /// assert!(a.iter().min().unwrap() == &1);
870 fn min(&mut self) -> Option<A>;
872 /// `min_max` finds the minimum and maximum elements in the iterator.
874 /// The return type `MinMaxResult` is an enum of three variants:
875 /// - `NoElements` if the iterator is empty.
876 /// - `OneElement(x)` if the iterator has exactly one element.
877 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two values are equal if and only if
878 /// there is more than one element in the iterator and all elements are equal.
880 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
881 /// and so faster than calling `min` and `max separately which does `2 * n` comparisons.
886 /// use std::iter::{NoElements, OneElement, MinMax};
888 /// let v: [int, ..0] = [];
889 /// assert_eq!(v.iter().min_max(), NoElements);
892 /// assert!(v.iter().min_max() == OneElement(&1));
894 /// let v = [1i, 2, 3, 4, 5];
895 /// assert!(v.iter().min_max() == MinMax(&1, &5));
897 /// let v = [1i, 2, 3, 4, 5, 6];
898 /// assert!(v.iter().min_max() == MinMax(&1, &6));
900 /// let v = [1i, 1, 1, 1];
901 /// assert!(v.iter().min_max() == MinMax(&1, &1));
903 fn min_max(&mut self) -> MinMaxResult<A>;
906 impl<A: TotalOrd, T: Iterator<A>> OrdIterator<A> for T {
908 fn max(&mut self) -> Option<A> {
909 self.fold(None, |max, x| {
912 Some(y) => Some(cmp::max(x, y))
918 fn min(&mut self) -> Option<A> {
919 self.fold(None, |min, x| {
922 Some(y) => Some(cmp::min(x, y))
927 fn min_max(&mut self) -> MinMaxResult<A> {
928 let (mut min, mut max) = match self.next() {
929 None => return NoElements,
932 None => return OneElement(x),
933 Some(y) => if x < y {(x, y)} else {(y,x)}
939 // `first` and `second` are the two next elements we want to look at.
940 // We first compare `first` and `second` (#1). The smaller one is then compared to
941 // current minimum (#2). The larger one is compared to current maximum (#3). This
942 // way we do 3 comparisons for 2 elements.
943 let first = match self.next() {
947 let second = match self.next() {
951 } else if first > max {
959 if first < min {min = first;}
960 if max < second {max = second;}
962 if second < min {min = second;}
963 if max < first {max = first;}
971 /// `MinMaxResult` is an enum returned by `min_max`. See `OrdIterator::min_max` for more detail.
972 #[deriving(Clone, Eq, Show)]
973 pub enum MinMaxResult<T> {
977 /// Iterator with one element, so the minimum and maximum are the same
980 /// More than one element in the iterator, the first element is not larger than the second
984 impl<T: Clone> MinMaxResult<T> {
985 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
986 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
987 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
988 /// performing this operation will make one clone of `x`.
993 /// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
995 /// let r: MinMaxResult<int> = NoElements;
996 /// assert_eq!(r.into_option(), None)
998 /// let r = OneElement(1);
999 /// assert_eq!(r.into_option(), Some((1,1)));
1001 /// let r = MinMax(1,2);
1002 /// assert_eq!(r.into_option(), Some((1,2)));
1004 pub fn into_option(self) -> Option<(T,T)> {
1007 OneElement(x) => Some((x.clone(), x)),
1008 MinMax(x, y) => Some((x, y))
1013 /// A trait for iterators that are cloneable.
1014 pub trait CloneableIterator {
1015 /// Repeats an iterator endlessly
1020 /// use std::iter::{CloneableIterator, count};
1022 /// let a = count(1,1).take(1);
1023 /// let mut cy = a.cycle();
1024 /// assert_eq!(cy.next(), Some(1));
1025 /// assert_eq!(cy.next(), Some(1));
1027 fn cycle(self) -> Cycle<Self>;
1030 impl<A, T: Clone + Iterator<A>> CloneableIterator for T {
1032 fn cycle(self) -> Cycle<T> {
1033 Cycle{orig: self.clone(), iter: self}
1037 /// An iterator that repeats endlessly
1039 pub struct Cycle<T> {
1044 impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
1046 fn next(&mut self) -> Option<A> {
1047 match self.iter.next() {
1048 None => { self.iter = self.orig.clone(); self.iter.next() }
1054 fn size_hint(&self) -> (uint, Option<uint>) {
1055 // the cycle iterator is either empty or infinite
1056 match self.orig.size_hint() {
1057 sz @ (0, Some(0)) => sz,
1058 (0, _) => (0, None),
1059 _ => (uint::MAX, None)
1064 impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
1066 fn indexable(&self) -> uint {
1067 if self.orig.indexable() > 0 {
1075 fn idx(&mut self, index: uint) -> Option<A> {
1076 let liter = self.iter.indexable();
1077 let lorig = self.orig.indexable();
1080 } else if index < liter {
1081 self.iter.idx(index)
1083 self.orig.idx((index - liter) % lorig)
1088 /// An iterator which strings two iterators together
1090 pub struct Chain<T, U> {
1096 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
1098 fn next(&mut self) -> Option<A> {
1102 match self.a.next() {
1103 Some(x) => return Some(x),
1112 fn size_hint(&self) -> (uint, Option<uint>) {
1113 let (a_lower, a_upper) = self.a.size_hint();
1114 let (b_lower, b_upper) = self.b.size_hint();
1116 let lower = a_lower.saturating_add(b_lower);
1118 let upper = match (a_upper, b_upper) {
1119 (Some(x), Some(y)) => x.checked_add(&y),
1127 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1130 fn next_back(&mut self) -> Option<A> {
1131 match self.b.next_back() {
1133 None => self.a.next_back()
1138 impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
1141 fn indexable(&self) -> uint {
1142 let (a, b) = (self.a.indexable(), self.b.indexable());
1147 fn idx(&mut self, index: uint) -> Option<A> {
1148 let len = self.a.indexable();
1152 self.b.idx(index - len)
1157 /// An iterator which iterates two other iterators simultaneously
1159 pub struct Zip<T, U> {
1164 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
1166 fn next(&mut self) -> Option<(A, B)> {
1167 match self.a.next() {
1169 Some(x) => match self.b.next() {
1171 Some(y) => Some((x, y))
1177 fn size_hint(&self) -> (uint, Option<uint>) {
1178 let (a_lower, a_upper) = self.a.size_hint();
1179 let (b_lower, b_upper) = self.b.size_hint();
1181 let lower = cmp::min(a_lower, b_lower);
1183 let upper = match (a_upper, b_upper) {
1184 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1185 (Some(x), None) => Some(x),
1186 (None, Some(y)) => Some(y),
1187 (None, None) => None
1194 impl<A, B, T: ExactSize<A>, U: ExactSize<B>> DoubleEndedIterator<(A, B)>
1197 fn next_back(&mut self) -> Option<(A, B)> {
1198 let (a_sz, a_upper) = self.a.size_hint();
1199 let (b_sz, b_upper) = self.b.size_hint();
1200 assert!(a_upper == Some(a_sz));
1201 assert!(b_upper == Some(b_sz));
1203 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1204 } else if a_sz > b_sz {
1205 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1207 let (a_sz, _) = self.a.size_hint();
1208 let (b_sz, _) = self.b.size_hint();
1209 assert!(a_sz == b_sz);
1210 match (self.a.next_back(), self.b.next_back()) {
1211 (Some(x), Some(y)) => Some((x, y)),
1217 impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
1218 RandomAccessIterator<(A, B)> for Zip<T, U> {
1220 fn indexable(&self) -> uint {
1221 cmp::min(self.a.indexable(), self.b.indexable())
1225 fn idx(&mut self, index: uint) -> Option<(A, B)> {
1226 match self.a.idx(index) {
1228 Some(x) => match self.b.idx(index) {
1230 Some(y) => Some((x, y))
1236 /// An iterator which maps the values of `iter` with `f`
1237 pub struct Map<'a, A, B, T> {
1242 impl<'a, A, B, T> Map<'a, A, B, T> {
1244 fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1246 Some(a) => Some((self.f)(a)),
1252 impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> {
1254 fn next(&mut self) -> Option<B> {
1255 let next = self.iter.next();
1260 fn size_hint(&self) -> (uint, Option<uint>) {
1261 self.iter.size_hint()
1265 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> {
1267 fn next_back(&mut self) -> Option<B> {
1268 let next = self.iter.next_back();
1273 impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> {
1275 fn indexable(&self) -> uint {
1276 self.iter.indexable()
1280 fn idx(&mut self, index: uint) -> Option<B> {
1281 let elt = self.iter.idx(index);
1286 /// An iterator which filters the elements of `iter` with `predicate`
1287 pub struct Filter<'a, A, T> {
1289 predicate: |&A|: 'a -> bool
1292 impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> {
1294 fn next(&mut self) -> Option<A> {
1295 for x in self.iter {
1296 if (self.predicate)(&x) {
1306 fn size_hint(&self) -> (uint, Option<uint>) {
1307 let (_, upper) = self.iter.size_hint();
1308 (0, upper) // can't know a lower bound, due to the predicate
1312 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> {
1314 fn next_back(&mut self) -> Option<A> {
1316 match self.iter.next_back() {
1317 None => return None,
1319 if (self.predicate)(&x) {
1330 /// An iterator which uses `f` to both filter and map elements from `iter`
1331 pub struct FilterMap<'a, A, B, T> {
1333 f: |A|: 'a -> Option<B>
1336 impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> {
1338 fn next(&mut self) -> Option<B> {
1339 for x in self.iter {
1341 Some(y) => return Some(y),
1349 fn size_hint(&self) -> (uint, Option<uint>) {
1350 let (_, upper) = self.iter.size_hint();
1351 (0, upper) // can't know a lower bound, due to the predicate
1355 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1356 for FilterMap<'a, A, B, T> {
1358 fn next_back(&mut self) -> Option<B> {
1360 match self.iter.next_back() {
1361 None => return None,
1364 Some(y) => return Some(y),
1373 /// An iterator which yields the current count and the element during iteration
1375 pub struct Enumerate<T> {
1380 impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1382 fn next(&mut self) -> Option<(uint, A)> {
1383 match self.iter.next() {
1385 let ret = Some((self.count, a));
1394 fn size_hint(&self) -> (uint, Option<uint>) {
1395 self.iter.size_hint()
1399 impl<A, T: ExactSize<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
1401 fn next_back(&mut self) -> Option<(uint, A)> {
1402 match self.iter.next_back() {
1404 let (lower, upper) = self.iter.size_hint();
1405 assert!(upper == Some(lower));
1406 Some((self.count + lower, a))
1413 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
1415 fn indexable(&self) -> uint {
1416 self.iter.indexable()
1420 fn idx(&mut self, index: uint) -> Option<(uint, A)> {
1421 match self.iter.idx(index) {
1422 Some(a) => Some((self.count + index, a)),
1428 /// An iterator with a `peek()` that returns an optional reference to the next element.
1429 pub struct Peekable<A, T> {
1434 impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
1436 fn next(&mut self) -> Option<A> {
1437 if self.peeked.is_some() { self.peeked.take() }
1438 else { self.iter.next() }
1442 fn size_hint(&self) -> (uint, Option<uint>) {
1443 let (lo, hi) = self.iter.size_hint();
1444 if self.peeked.is_some() {
1445 let lo = lo.saturating_add(1);
1447 Some(x) => x.checked_add(&1),
1457 impl<'a, A, T: Iterator<A>> Peekable<A, T> {
1458 /// Return a reference to the next element of the iterator with out advancing it,
1459 /// or None if the iterator is exhausted.
1461 pub fn peek(&'a mut self) -> Option<&'a A> {
1462 if self.peeked.is_none() {
1463 self.peeked = self.iter.next();
1466 Some(ref value) => Some(value),
1471 /// Check whether peekable iterator is empty or not.
1473 pub fn is_empty(&mut self) -> bool {
1474 self.peek().is_none()
1478 /// An iterator which rejects elements while `predicate` is true
1479 pub struct SkipWhile<'a, A, T> {
1482 predicate: |&A|: 'a -> bool
1485 impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> {
1487 fn next(&mut self) -> Option<A> {
1488 let mut next = self.iter.next();
1495 if (self.predicate)(&x) {
1496 next = self.iter.next();
1510 fn size_hint(&self) -> (uint, Option<uint>) {
1511 let (_, upper) = self.iter.size_hint();
1512 (0, upper) // can't know a lower bound, due to the predicate
1516 /// An iterator which only accepts elements while `predicate` is true
1517 pub struct TakeWhile<'a, A, T> {
1520 predicate: |&A|: 'a -> bool
1523 impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> {
1525 fn next(&mut self) -> Option<A> {
1529 match self.iter.next() {
1531 if (self.predicate)(&x) {
1544 fn size_hint(&self) -> (uint, Option<uint>) {
1545 let (_, upper) = self.iter.size_hint();
1546 (0, upper) // can't know a lower bound, due to the predicate
1550 /// An iterator which skips over `n` elements of `iter`.
1552 pub struct Skip<T> {
1557 impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
1559 fn next(&mut self) -> Option<A> {
1560 let mut next = self.iter.next();
1569 next = self.iter.next();
1584 fn size_hint(&self) -> (uint, Option<uint>) {
1585 let (lower, upper) = self.iter.size_hint();
1587 let lower = lower.saturating_sub(self.n);
1589 let upper = match upper {
1590 Some(x) => Some(x.saturating_sub(self.n)),
1598 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
1600 fn indexable(&self) -> uint {
1601 self.iter.indexable().saturating_sub(self.n)
1605 fn idx(&mut self, index: uint) -> Option<A> {
1606 if index >= self.indexable() {
1609 self.iter.idx(index + self.n)
1614 /// An iterator which only iterates over the first `n` iterations of `iter`.
1616 pub struct Take<T> {
1621 impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
1623 fn next(&mut self) -> Option<A> {
1633 fn size_hint(&self) -> (uint, Option<uint>) {
1634 let (lower, upper) = self.iter.size_hint();
1636 let lower = cmp::min(lower, self.n);
1638 let upper = match upper {
1639 Some(x) if x < self.n => Some(x),
1647 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
1649 fn indexable(&self) -> uint {
1650 cmp::min(self.iter.indexable(), self.n)
1654 fn idx(&mut self, index: uint) -> Option<A> {
1655 if index >= self.n {
1658 self.iter.idx(index)
1664 /// An iterator to maintain state while iterating another iterator
1665 pub struct Scan<'a, A, B, T, St> {
1667 f: |&mut St, A|: 'a -> Option<B>,
1669 /// The current internal state to be passed to the closure next.
1673 impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> {
1675 fn next(&mut self) -> Option<B> {
1676 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1680 fn size_hint(&self) -> (uint, Option<uint>) {
1681 let (_, upper) = self.iter.size_hint();
1682 (0, upper) // can't know a lower bound, due to the scan function
1686 /// An iterator that maps each element to an iterator,
1687 /// and yields the elements of the produced iterators
1689 pub struct FlatMap<'a, A, T, U> {
1692 frontiter: Option<U>,
1693 backiter: Option<U>,
1696 impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> {
1698 fn next(&mut self) -> Option<B> {
1700 for inner in self.frontiter.mut_iter() {
1705 match self.iter.next().map(|x| (self.f)(x)) {
1706 None => return self.backiter.as_mut().and_then(|it| it.next()),
1707 next => self.frontiter = next,
1713 fn size_hint(&self) -> (uint, Option<uint>) {
1714 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1715 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1716 let lo = flo.saturating_add(blo);
1717 match (self.iter.size_hint(), fhi, bhi) {
1718 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(&b)),
1725 A, T: DoubleEndedIterator<A>,
1726 B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
1727 for FlatMap<'a, A, T, U> {
1729 fn next_back(&mut self) -> Option<B> {
1731 for inner in self.backiter.mut_iter() {
1732 match inner.next_back() {
1737 match self.iter.next_back().map(|x| (self.f)(x)) {
1738 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1739 next => self.backiter = next,
1745 /// An iterator that yields `None` forever after the underlying iterator
1746 /// yields `None` once.
1748 pub struct Fuse<T> {
1753 impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
1755 fn next(&mut self) -> Option<A> {
1759 match self.iter.next() {
1770 fn size_hint(&self) -> (uint, Option<uint>) {
1774 self.iter.size_hint()
1779 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
1781 fn next_back(&mut self) -> Option<A> {
1785 match self.iter.next_back() {
1796 // Allow RandomAccessIterators to be fused without affecting random-access behavior
1797 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
1799 fn indexable(&self) -> uint {
1800 self.iter.indexable()
1804 fn idx(&mut self, index: uint) -> Option<A> {
1805 self.iter.idx(index)
1810 /// Resets the fuse such that the next call to .next() or .next_back() will
1811 /// call the underlying iterator again even if it previously returned None.
1813 pub fn reset_fuse(&mut self) {
1818 /// An iterator that calls a function with a reference to each
1819 /// element before yielding it.
1820 pub struct Inspect<'a, A, T> {
1825 impl<'a, A, T> Inspect<'a, A, T> {
1827 fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
1829 Some(ref a) => (self.f)(a),
1837 impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> {
1839 fn next(&mut self) -> Option<A> {
1840 let next = self.iter.next();
1841 self.do_inspect(next)
1845 fn size_hint(&self) -> (uint, Option<uint>) {
1846 self.iter.size_hint()
1850 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1851 for Inspect<'a, A, T> {
1853 fn next_back(&mut self) -> Option<A> {
1854 let next = self.iter.next_back();
1855 self.do_inspect(next)
1859 impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
1860 for Inspect<'a, A, T> {
1862 fn indexable(&self) -> uint {
1863 self.iter.indexable()
1867 fn idx(&mut self, index: uint) -> Option<A> {
1868 let element = self.iter.idx(index);
1869 self.do_inspect(element)
1873 /// An iterator which just modifies the contained state throughout iteration.
1874 pub struct Unfold<'a, A, St> {
1875 f: |&mut St|: 'a -> Option<A>,
1876 /// Internal state that will be yielded on the next iteration
1880 impl<'a, A, St> Unfold<'a, A, St> {
1881 /// Creates a new iterator with the specified closure as the "iterator
1882 /// function" and an initial state to eventually pass to the iterator
1884 pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option<A>)
1885 -> Unfold<'a, A, St> {
1888 state: initial_state
1893 impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> {
1895 fn next(&mut self) -> Option<A> {
1896 (self.f)(&mut self.state)
1900 fn size_hint(&self) -> (uint, Option<uint>) {
1901 // no possible known bounds at this point
1906 /// An infinite iterator starting at `start` and advancing by `step` with each
1909 pub struct Counter<A> {
1910 /// The current state the counter is at (next value to be yielded)
1912 /// The amount that this iterator is stepping by
1916 /// Creates a new counter with the specified start/step
1918 pub fn count<A>(start: A, step: A) -> Counter<A> {
1919 Counter{state: start, step: step}
1922 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
1924 fn next(&mut self) -> Option<A> {
1925 let result = self.state.clone();
1926 self.state = self.state + self.step;
1931 fn size_hint(&self) -> (uint, Option<uint>) {
1932 (uint::MAX, None) // Too bad we can't specify an infinite lower bound
1936 /// An iterator over the range [start, stop)
1938 pub struct Range<A> {
1944 /// Return an iterator over the range [start, stop)
1946 pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
1947 Range{state: start, stop: stop, one: One::one()}
1950 // FIXME: #10414: Unfortunate type bound
1951 impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for Range<A> {
1953 fn next(&mut self) -> Option<A> {
1954 if self.state < self.stop {
1955 let result = self.state.clone();
1956 self.state = self.state + self.one;
1964 fn size_hint(&self) -> (uint, Option<uint>) {
1965 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
1966 // handle cases like range(huge, huger)). We don't use uint/int because the difference of
1967 // the i64/u64 might lie within their range.
1968 let bound = match self.state.to_i64() {
1970 let sz = self.stop.to_i64().map(|b| b.checked_sub(&a));
1972 Some(Some(bound)) => bound.to_uint(),
1976 None => match self.state.to_u64() {
1978 let sz = self.stop.to_u64().map(|b| b.checked_sub(&a));
1980 Some(Some(bound)) => bound.to_uint(),
1989 Some(b) => (b, Some(b)),
1990 // Standard fallback for unbounded/unrepresentable bounds
1996 /// `Int` is required to ensure the range will be the same regardless of
1997 /// the direction it is consumed.
1998 impl<A: Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
2000 fn next_back(&mut self) -> Option<A> {
2001 if self.stop > self.state {
2002 self.stop = self.stop - self.one;
2003 Some(self.stop.clone())
2010 /// An iterator over the range [start, stop]
2012 pub struct RangeInclusive<A> {
2017 /// Return an iterator over the range [start, stop]
2019 pub fn range_inclusive<A: Add<A, A> + Ord + Clone + One + ToPrimitive>(start: A, stop: A)
2020 -> RangeInclusive<A> {
2021 RangeInclusive{range: range(start, stop), done: false}
2024 impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for RangeInclusive<A> {
2026 fn next(&mut self) -> Option<A> {
2027 match self.range.next() {
2030 if !self.done && self.range.state == self.range.stop {
2032 Some(self.range.stop.clone())
2041 fn size_hint(&self) -> (uint, Option<uint>) {
2042 let (lo, hi) = self.range.size_hint();
2046 let lo = lo.saturating_add(1);
2048 Some(x) => x.checked_add(&1),
2056 impl<A: Sub<A, A> + Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A>
2057 for RangeInclusive<A> {
2059 fn next_back(&mut self) -> Option<A> {
2060 if self.range.stop > self.range.state {
2061 let result = self.range.stop.clone();
2062 self.range.stop = self.range.stop - self.range.one;
2064 } else if !self.done && self.range.state == self.range.stop {
2066 Some(self.range.stop.clone())
2073 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2075 pub struct RangeStep<A> {
2082 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2084 pub fn range_step<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A, step: A) -> RangeStep<A> {
2085 let rev = step < Zero::zero();
2086 RangeStep{state: start, stop: stop, step: step, rev: rev}
2089 impl<A: CheckedAdd + Ord + Clone> Iterator<A> for RangeStep<A> {
2091 fn next(&mut self) -> Option<A> {
2092 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2093 let result = self.state.clone();
2094 match self.state.checked_add(&self.step) {
2095 Some(x) => self.state = x,
2096 None => self.state = self.stop.clone()
2105 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2107 pub struct RangeStepInclusive<A> {
2115 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2117 pub fn range_step_inclusive<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A,
2118 step: A) -> RangeStepInclusive<A> {
2119 let rev = step < Zero::zero();
2120 RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
2123 impl<A: CheckedAdd + Ord + Clone + Eq> Iterator<A> for RangeStepInclusive<A> {
2125 fn next(&mut self) -> Option<A> {
2126 if !self.done && ((self.rev && self.state >= self.stop) ||
2127 (!self.rev && self.state <= self.stop)) {
2128 let result = self.state.clone();
2129 match self.state.checked_add(&self.step) {
2130 Some(x) => self.state = x,
2131 None => self.done = true
2140 /// An iterator that repeats an element endlessly
2142 pub struct Repeat<A> {
2146 impl<A: Clone> Repeat<A> {
2147 /// Create a new `Repeat` that endlessly repeats the element `elt`.
2149 pub fn new(elt: A) -> Repeat<A> {
2150 Repeat{element: elt}
2154 impl<A: Clone> Iterator<A> for Repeat<A> {
2156 fn next(&mut self) -> Option<A> { self.idx(0) }
2158 fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2161 impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
2163 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2166 impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
2168 fn indexable(&self) -> uint { uint::MAX }
2170 fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
2173 /// Functions for lexicographical ordering of sequences.
2175 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2176 /// that the elements implement both `Eq` and `Ord`.
2178 /// If two sequences are equal up until the point where one ends,
2179 /// the shorter sequence compares less.
2182 use cmp::{TotalEq, TotalOrd, Ord, Eq};
2183 use option::{Some, None};
2184 use super::Iterator;
2186 /// Compare `a` and `b` for equality using `TotalEq`
2187 pub fn equals<A: TotalEq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2189 match (a.next(), b.next()) {
2190 (None, None) => return true,
2191 (None, _) | (_, None) => return false,
2192 (Some(x), Some(y)) => if x != y { return false },
2197 /// Order `a` and `b` lexicographically using `TotalOrd`
2198 pub fn cmp<A: TotalOrd, T: Iterator<A>>(mut a: T, mut b: T) -> cmp::Ordering {
2200 match (a.next(), b.next()) {
2201 (None, None) => return cmp::Equal,
2202 (None, _ ) => return cmp::Less,
2203 (_ , None) => return cmp::Greater,
2204 (Some(x), Some(y)) => match x.cmp(&y) {
2206 non_eq => return non_eq,
2212 /// Compare `a` and `b` for equality (Using partial equality, `Eq`)
2213 pub fn eq<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2215 match (a.next(), b.next()) {
2216 (None, None) => return true,
2217 (None, _) | (_, None) => return false,
2218 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2223 /// Compare `a` and `b` for nonequality (Using partial equality, `Eq`)
2224 pub fn ne<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2226 match (a.next(), b.next()) {
2227 (None, None) => return false,
2228 (None, _) | (_, None) => return true,
2229 (Some(x), Some(y)) => if x.ne(&y) { return true },
2234 /// Return `a` < `b` lexicographically (Using partial order, `Ord`)
2235 pub fn lt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2237 match (a.next(), b.next()) {
2238 (None, None) => return false,
2239 (None, _ ) => return true,
2240 (_ , None) => return false,
2241 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2246 /// Return `a` <= `b` lexicographically (Using partial order, `Ord`)
2247 pub fn le<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2249 match (a.next(), b.next()) {
2250 (None, None) => return true,
2251 (None, _ ) => return true,
2252 (_ , None) => return false,
2253 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2258 /// Return `a` > `b` lexicographically (Using partial order, `Ord`)
2259 pub fn gt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2261 match (a.next(), b.next()) {
2262 (None, None) => return false,
2263 (None, _ ) => return false,
2264 (_ , None) => return true,
2265 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2270 /// Return `a` >= `b` lexicographically (Using partial order, `Ord`)
2271 pub fn ge<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2273 match (a.next(), b.next()) {
2274 (None, None) => return true,
2275 (None, _ ) => return false,
2276 (_ , None) => return true,
2277 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },
2284 use slice::ImmutableVector;
2286 let empty: [int, ..0] = [];
2290 assert!(!lt(xs.iter(), ys.iter()));
2291 assert!(!le(xs.iter(), ys.iter()));
2292 assert!( gt(xs.iter(), ys.iter()));
2293 assert!( ge(xs.iter(), ys.iter()));
2295 assert!( lt(ys.iter(), xs.iter()));
2296 assert!( le(ys.iter(), xs.iter()));
2297 assert!(!gt(ys.iter(), xs.iter()));
2298 assert!(!ge(ys.iter(), xs.iter()));
2300 assert!( lt(empty.iter(), xs.iter()));
2301 assert!( le(empty.iter(), xs.iter()));
2302 assert!(!gt(empty.iter(), xs.iter()));
2303 assert!(!ge(empty.iter(), xs.iter()));
2305 // Sequence with NaN
2307 let v = [0.0/0.0, 3.0];
2309 assert!(!lt(u.iter(), v.iter()));
2310 assert!(!le(u.iter(), v.iter()));
2311 assert!(!gt(u.iter(), v.iter()));
2312 assert!(!ge(u.iter(), v.iter()));
2318 assert!(lt(a.iter(), b.iter()) == (a[0] < b[0]));
2319 assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
2320 assert!(gt(a.iter(), b.iter()) == (a[0] > b[0]));
2321 assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0]));
2323 assert!(lt(c.iter(), b.iter()) == (c[0] < b[0]));
2324 assert!(le(c.iter(), b.iter()) == (c[0] <= b[0]));
2325 assert!(gt(c.iter(), b.iter()) == (c[0] > b[0]));
2326 assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0]));
2340 fn test_counter_from_iter() {
2341 let it = count(0, 5).take(10);
2342 let xs: ~[int] = FromIterator::from_iter(it);
2343 assert_eq!(xs, box [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
2347 fn test_iterator_chain() {
2348 let xs = [0u, 1, 2, 3, 4, 5];
2349 let ys = [30u, 40, 50, 60];
2350 let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
2351 let mut it = xs.iter().chain(ys.iter());
2354 assert_eq!(x, expected[i]);
2357 assert_eq!(i, expected.len());
2359 let ys = count(30u, 10).take(4);
2360 let mut it = xs.iter().map(|&x| x).chain(ys);
2363 assert_eq!(x, expected[i]);
2366 assert_eq!(i, expected.len());
2370 fn test_filter_map() {
2371 let mut it = count(0u, 1u).take(10)
2372 .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None });
2373 assert_eq!(it.collect::<~[uint]>(), box [0*0, 2*2, 4*4, 6*6, 8*8]);
2377 fn test_iterator_enumerate() {
2378 let xs = [0u, 1, 2, 3, 4, 5];
2379 let mut it = xs.iter().enumerate();
2386 fn test_iterator_peekable() {
2387 let xs = box [0u, 1, 2, 3, 4, 5];
2388 let mut it = xs.iter().map(|&x|x).peekable();
2389 assert_eq!(it.peek().unwrap(), &0);
2390 assert_eq!(it.next().unwrap(), 0);
2391 assert_eq!(it.next().unwrap(), 1);
2392 assert_eq!(it.next().unwrap(), 2);
2393 assert_eq!(it.peek().unwrap(), &3);
2394 assert_eq!(it.peek().unwrap(), &3);
2395 assert_eq!(it.next().unwrap(), 3);
2396 assert_eq!(it.next().unwrap(), 4);
2397 assert_eq!(it.peek().unwrap(), &5);
2398 assert_eq!(it.next().unwrap(), 5);
2399 assert!(it.peek().is_none());
2400 assert!(it.next().is_none());
2404 fn test_iterator_take_while() {
2405 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2406 let ys = [0u, 1, 2, 3, 5, 13];
2407 let mut it = xs.iter().take_while(|&x| *x < 15u);
2410 assert_eq!(x, ys[i]);
2413 assert_eq!(i, ys.len());
2417 fn test_iterator_skip_while() {
2418 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2419 let ys = [15, 16, 17, 19];
2420 let mut it = xs.iter().skip_while(|&x| *x < 15u);
2423 assert_eq!(x, ys[i]);
2426 assert_eq!(i, ys.len());
2430 fn test_iterator_skip() {
2431 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
2432 let ys = [13, 15, 16, 17, 19, 20, 30];
2433 let mut it = xs.iter().skip(5);
2436 assert_eq!(x, ys[i]);
2439 assert_eq!(i, ys.len());
2443 fn test_iterator_take() {
2444 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2445 let ys = [0u, 1, 2, 3, 5];
2446 let mut it = xs.iter().take(5);
2449 assert_eq!(x, ys[i]);
2452 assert_eq!(i, ys.len());
2456 fn test_iterator_scan() {
2457 // test the type inference
2458 fn add(old: &mut int, new: &uint) -> Option<f64> {
2459 *old += *new as int;
2462 let xs = [0u, 1, 2, 3, 4];
2463 let ys = [0f64, 1.0, 3.0, 6.0, 10.0];
2465 let mut it = xs.iter().scan(0, add);
2468 assert_eq!(x, ys[i]);
2471 assert_eq!(i, ys.len());
2475 fn test_iterator_flat_map() {
2476 let xs = [0u, 3, 6];
2477 let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
2478 let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3));
2481 assert_eq!(x, ys[i]);
2484 assert_eq!(i, ys.len());
2489 let xs = [1u, 2, 3, 4];
2494 .inspect(|_| n += 1)
2495 .collect::<~[uint]>();
2497 assert_eq!(n, xs.len());
2498 assert_eq!(xs.as_slice(), ys.as_slice());
2503 fn count(st: &mut uint) -> Option<uint> {
2505 let ret = Some(*st);
2513 let mut it = Unfold::new(0, count);
2516 assert_eq!(counted, i);
2525 let it = count(0u, 1).take(cycle_len).cycle();
2526 assert_eq!(it.size_hint(), (uint::MAX, None));
2527 for (i, x) in it.take(100).enumerate() {
2528 assert_eq!(i % cycle_len, x);
2531 let mut it = count(0u, 1).take(0).cycle();
2532 assert_eq!(it.size_hint(), (0, Some(0)));
2533 assert_eq!(it.next(), None);
2537 fn test_iterator_nth() {
2538 let v = &[0, 1, 2, 3, 4];
2539 for i in range(0u, v.len()) {
2540 assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
2545 fn test_iterator_last() {
2546 let v = &[0, 1, 2, 3, 4];
2547 assert_eq!(v.iter().last().unwrap(), &4);
2548 assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
2552 fn test_iterator_len() {
2553 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2554 assert_eq!(v.slice(0, 4).iter().len(), 4);
2555 assert_eq!(v.slice(0, 10).iter().len(), 10);
2556 assert_eq!(v.slice(0, 0).iter().len(), 0);
2560 fn test_iterator_sum() {
2561 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2562 assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
2563 assert_eq!(v.iter().map(|&x| x).sum(), 55);
2564 assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
2568 fn test_iterator_product() {
2569 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2570 assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
2571 assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
2572 assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
2576 fn test_iterator_max() {
2577 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2578 assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
2579 assert_eq!(v.iter().map(|&x| x).max(), Some(10));
2580 assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
2584 fn test_iterator_min() {
2585 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2586 assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
2587 assert_eq!(v.iter().map(|&x| x).min(), Some(0));
2588 assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
2592 fn test_iterator_size_hint() {
2593 let c = count(0, 1);
2594 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2595 let v2 = &[10, 11, 12];
2598 assert_eq!(c.size_hint(), (uint::MAX, None));
2599 assert_eq!(vi.size_hint(), (10, Some(10)));
2601 assert_eq!(c.take(5).size_hint(), (5, Some(5)));
2602 assert_eq!(c.skip(5).size_hint().val1(), None);
2603 assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
2604 assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
2605 assert_eq!(c.enumerate().size_hint(), (uint::MAX, None));
2606 assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None));
2607 assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
2608 assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
2609 assert_eq!(c.filter(|_| false).size_hint(), (0, None));
2610 assert_eq!(c.map(|_| 0).size_hint(), (uint::MAX, None));
2611 assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
2613 assert_eq!(vi.take(5).size_hint(), (5, Some(5)));
2614 assert_eq!(vi.take(12).size_hint(), (10, Some(10)));
2615 assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
2616 assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
2617 assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
2618 assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
2619 assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
2620 assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13)));
2621 assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
2622 assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
2623 assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
2624 assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10)));
2625 assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
2630 let a = box [1, 2, 3, 4, 5];
2631 let b: ~[int] = a.iter().map(|&x| x).collect();
2637 let v: ~&[int] = box &[1, 2, 3, 4, 5];
2638 assert!(v.iter().all(|&x| x < 10));
2639 assert!(!v.iter().all(|&x| x % 2 == 0));
2640 assert!(!v.iter().all(|&x| x > 100));
2641 assert!(v.slice(0, 0).iter().all(|_| fail!()));
2646 let v: ~&[int] = box &[1, 2, 3, 4, 5];
2647 assert!(v.iter().any(|&x| x < 10));
2648 assert!(v.iter().any(|&x| x % 2 == 0));
2649 assert!(!v.iter().any(|&x| x > 100));
2650 assert!(!v.slice(0, 0).iter().any(|_| fail!()));
2655 let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
2656 assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
2657 assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
2658 assert!(v.iter().find(|x| *x % 12 == 0).is_none());
2662 fn test_position() {
2663 let v = &[1, 3, 9, 27, 103, 14, 11];
2664 assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
2665 assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
2666 assert!(v.iter().position(|x| *x % 12 == 0).is_none());
2671 let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
2672 assert_eq!(xs.iter().count(|x| *x == 2), 3);
2673 assert_eq!(xs.iter().count(|x| *x == 5), 1);
2674 assert_eq!(xs.iter().count(|x| *x == 95), 0);
2679 let xs: &[int] = &[-3, 0, 1, 5, -10];
2680 assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
2685 let xs: &[int] = &[-3, 0, 1, 5, -10];
2686 assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
2691 let mut xs = range(0, 10);
2692 // sum the first five values
2693 let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
2694 assert_eq!(partial_sum, 10);
2695 assert_eq!(xs.next(), Some(5));
2700 let xs = [2, 4, 6, 8, 10, 12, 14, 16];
2701 let mut it = xs.iter();
2704 assert_eq!(it.rev().map(|&x| x).collect::<~[int]>(), box [16, 14, 12, 10, 8, 6]);
2708 fn test_double_ended_map() {
2709 let xs = [1, 2, 3, 4, 5, 6];
2710 let mut it = xs.iter().map(|&x| x * -1);
2711 assert_eq!(it.next(), Some(-1));
2712 assert_eq!(it.next(), Some(-2));
2713 assert_eq!(it.next_back(), Some(-6));
2714 assert_eq!(it.next_back(), Some(-5));
2715 assert_eq!(it.next(), Some(-3));
2716 assert_eq!(it.next_back(), Some(-4));
2717 assert_eq!(it.next(), None);
2721 fn test_double_ended_enumerate() {
2722 let xs = [1, 2, 3, 4, 5, 6];
2723 let mut it = xs.iter().map(|&x| x).enumerate();
2724 assert_eq!(it.next(), Some((0, 1)));
2725 assert_eq!(it.next(), Some((1, 2)));
2726 assert_eq!(it.next_back(), Some((5, 6)));
2727 assert_eq!(it.next_back(), Some((4, 5)));
2728 assert_eq!(it.next_back(), Some((3, 4)));
2729 assert_eq!(it.next_back(), Some((2, 3)));
2730 assert_eq!(it.next(), None);
2734 fn test_double_ended_zip() {
2735 let xs = [1, 2, 3, 4, 5, 6];
2736 let ys = [1, 2, 3, 7];
2737 let a = xs.iter().map(|&x| x);
2738 let b = ys.iter().map(|&x| x);
2739 let mut it = a.zip(b);
2740 assert_eq!(it.next(), Some((1, 1)));
2741 assert_eq!(it.next(), Some((2, 2)));
2742 assert_eq!(it.next_back(), Some((4, 7)));
2743 assert_eq!(it.next_back(), Some((3, 3)));
2744 assert_eq!(it.next(), None);
2748 fn test_double_ended_filter() {
2749 let xs = [1, 2, 3, 4, 5, 6];
2750 let mut it = xs.iter().filter(|&x| *x & 1 == 0);
2751 assert_eq!(it.next_back().unwrap(), &6);
2752 assert_eq!(it.next_back().unwrap(), &4);
2753 assert_eq!(it.next().unwrap(), &2);
2754 assert_eq!(it.next_back(), None);
2758 fn test_double_ended_filter_map() {
2759 let xs = [1, 2, 3, 4, 5, 6];
2760 let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
2761 assert_eq!(it.next_back().unwrap(), 12);
2762 assert_eq!(it.next_back().unwrap(), 8);
2763 assert_eq!(it.next().unwrap(), 4);
2764 assert_eq!(it.next_back(), None);
2768 fn test_double_ended_chain() {
2769 let xs = [1, 2, 3, 4, 5];
2770 let ys = box [7, 9, 11];
2771 let mut it = xs.iter().chain(ys.iter()).rev();
2772 assert_eq!(it.next().unwrap(), &11)
2773 assert_eq!(it.next().unwrap(), &9)
2774 assert_eq!(it.next_back().unwrap(), &1)
2775 assert_eq!(it.next_back().unwrap(), &2)
2776 assert_eq!(it.next_back().unwrap(), &3)
2777 assert_eq!(it.next_back().unwrap(), &4)
2778 assert_eq!(it.next_back().unwrap(), &5)
2779 assert_eq!(it.next_back().unwrap(), &7)
2780 assert_eq!(it.next_back(), None)
2784 fn test_rposition() {
2785 fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
2786 fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
2787 let v = box [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
2789 assert_eq!(v.iter().rposition(f), Some(3u));
2790 assert!(v.iter().rposition(g).is_none());
2795 fn test_rposition_fail() {
2796 let v = [(box 0, @0), (box 0, @0), (box 0, @0), (box 0, @0)];
2798 v.iter().rposition(|_elt| {
2809 fn check_randacc_iter<A: Eq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint)
2811 let mut b = a.clone();
2812 assert_eq!(len, b.indexable());
2814 for (i, elt) in a.enumerate() {
2815 assert!(Some(elt) == b.idx(i));
2819 assert!(None == b.idx(n));
2820 // call recursively to check after picking off an element
2823 check_randacc_iter(b, len-1);
2829 fn test_double_ended_flat_map() {
2832 let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
2833 assert_eq!(it.next_back().unwrap(), &8);
2834 assert_eq!(it.next().unwrap(), &5);
2835 assert_eq!(it.next_back().unwrap(), &7);
2836 assert_eq!(it.next_back().unwrap(), &6);
2837 assert_eq!(it.next_back().unwrap(), &8);
2838 assert_eq!(it.next().unwrap(), &6);
2839 assert_eq!(it.next_back().unwrap(), &7);
2840 assert_eq!(it.next_back(), None);
2841 assert_eq!(it.next(), None);
2842 assert_eq!(it.next_back(), None);
2846 fn test_random_access_chain() {
2847 let xs = [1, 2, 3, 4, 5];
2848 let ys = box [7, 9, 11];
2849 let mut it = xs.iter().chain(ys.iter());
2850 assert_eq!(it.idx(0).unwrap(), &1);
2851 assert_eq!(it.idx(5).unwrap(), &7);
2852 assert_eq!(it.idx(7).unwrap(), &11);
2853 assert!(it.idx(8).is_none());
2859 assert_eq!(it.idx(0).unwrap(), &3);
2860 assert_eq!(it.idx(4).unwrap(), &9);
2861 assert!(it.idx(6).is_none());
2863 check_randacc_iter(it, xs.len() + ys.len() - 3);
2867 fn test_random_access_enumerate() {
2868 let xs = [1, 2, 3, 4, 5];
2869 check_randacc_iter(xs.iter().enumerate(), xs.len());
2873 fn test_random_access_rev() {
2874 let xs = [1, 2, 3, 4, 5];
2875 check_randacc_iter(xs.iter().rev(), xs.len());
2876 let mut it = xs.iter().rev();
2880 check_randacc_iter(it, xs.len() - 3);
2884 fn test_random_access_zip() {
2885 let xs = [1, 2, 3, 4, 5];
2886 let ys = [7, 9, 11];
2887 check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
2891 fn test_random_access_take() {
2892 let xs = [1, 2, 3, 4, 5];
2893 let empty: &[int] = [];
2894 check_randacc_iter(xs.iter().take(3), 3);
2895 check_randacc_iter(xs.iter().take(20), xs.len());
2896 check_randacc_iter(xs.iter().take(0), 0);
2897 check_randacc_iter(empty.iter().take(2), 0);
2901 fn test_random_access_skip() {
2902 let xs = [1, 2, 3, 4, 5];
2903 let empty: &[int] = [];
2904 check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
2905 check_randacc_iter(empty.iter().skip(2), 0);
2909 fn test_random_access_inspect() {
2910 let xs = [1, 2, 3, 4, 5];
2912 // test .map and .inspect that don't implement Clone
2913 let mut it = xs.iter().inspect(|_| {});
2914 assert_eq!(xs.len(), it.indexable());
2915 for (i, elt) in xs.iter().enumerate() {
2916 assert_eq!(Some(elt), it.idx(i));
2922 fn test_random_access_map() {
2923 let xs = [1, 2, 3, 4, 5];
2925 let mut it = xs.iter().map(|x| *x);
2926 assert_eq!(xs.len(), it.indexable());
2927 for (i, elt) in xs.iter().enumerate() {
2928 assert_eq!(Some(*elt), it.idx(i));
2933 fn test_random_access_cycle() {
2934 let xs = [1, 2, 3, 4, 5];
2935 let empty: &[int] = [];
2936 check_randacc_iter(xs.iter().cycle().take(27), 27);
2937 check_randacc_iter(empty.iter().cycle(), 0);
2941 fn test_double_ended_range() {
2942 assert_eq!(range(11i, 14).rev().collect::<~[int]>(), box [13i, 12, 11]);
2943 for _ in range(10i, 0).rev() {
2944 fail!("unreachable");
2947 assert_eq!(range(11u, 14).rev().collect::<~[uint]>(), box [13u, 12, 11]);
2948 for _ in range(10u, 0).rev() {
2949 fail!("unreachable");
2955 /// A mock type to check Range when ToPrimitive returns None
2958 impl ToPrimitive for Foo {
2959 fn to_i64(&self) -> Option<i64> { None }
2960 fn to_u64(&self) -> Option<u64> { None }
2963 impl Add<Foo, Foo> for Foo {
2964 fn add(&self, _: &Foo) -> Foo {
2970 fn eq(&self, _: &Foo) -> bool {
2976 fn lt(&self, _: &Foo) -> bool {
2981 impl Clone for Foo {
2982 fn clone(&self) -> Foo {
2987 impl Mul<Foo, Foo> for Foo {
2988 fn mul(&self, _: &Foo) -> Foo {
2993 impl num::One for Foo {
2999 assert_eq!(range(0i, 5).collect::<~[int]>(), box [0i, 1, 2, 3, 4]);
3000 assert_eq!(range(-10i, -1).collect::<~[int]>(), box [-10, -9, -8, -7, -6, -5, -4, -3, -2]);
3001 assert_eq!(range(0i, 5).rev().collect::<~[int]>(), box [4, 3, 2, 1, 0]);
3002 assert_eq!(range(200, -5).collect::<~[int]>(), box []);
3003 assert_eq!(range(200, -5).rev().collect::<~[int]>(), box []);
3004 assert_eq!(range(200, 200).collect::<~[int]>(), box []);
3005 assert_eq!(range(200, 200).rev().collect::<~[int]>(), box []);
3007 assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
3008 // this test is only meaningful when sizeof uint < sizeof u64
3009 assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1)));
3010 assert_eq!(range(-10i, -1).size_hint(), (9, Some(9)));
3011 assert_eq!(range(Foo, Foo).size_hint(), (0, None));
3015 fn test_range_inclusive() {
3016 assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), box [0i, 1, 2, 3, 4, 5]);
3017 assert_eq!(range_inclusive(0i, 5).rev().collect::<~[int]>(), box [5i, 4, 3, 2, 1, 0]);
3018 assert_eq!(range_inclusive(200, -5).collect::<~[int]>(), box []);
3019 assert_eq!(range_inclusive(200, -5).rev().collect::<~[int]>(), box []);
3020 assert_eq!(range_inclusive(200, 200).collect::<~[int]>(), box [200]);
3021 assert_eq!(range_inclusive(200, 200).rev().collect::<~[int]>(), box [200]);
3025 fn test_range_step() {
3026 assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), box [0, 5, 10, 15]);
3027 assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), box [20, 15, 10, 5]);
3028 assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), box [20, 14, 8, 2]);
3029 assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), box [200u8, 250]);
3030 assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), box []);
3031 assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), box []);
3035 fn test_range_step_inclusive() {
3036 assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), box [0, 5, 10, 15, 20]);
3037 assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), box [20, 15, 10, 5, 0]);
3038 assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), box [20, 14, 8, 2]);
3039 assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), box [200u8, 250]);
3040 assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), box []);
3041 assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), box [200]);
3046 let mut ys = [1, 2, 3, 4, 5];
3047 ys.mut_iter().reverse_();
3048 assert!(ys == [5, 4, 3, 2, 1]);
3052 fn test_peekable_is_empty() {
3054 let mut it = a.iter().peekable();
3055 assert!( !it.is_empty() );
3057 assert!( it.is_empty() );
3062 let v: [int, ..0] = [];
3063 assert_eq!(v.iter().min_max(), NoElements);
3066 assert!(v.iter().min_max() == OneElement(&1));
3068 let v = [1i, 2, 3, 4, 5];
3069 assert!(v.iter().min_max() == MinMax(&1, &5));
3071 let v = [1i, 2, 3, 4, 5, 6];
3072 assert!(v.iter().min_max() == MinMax(&1, &6));
3074 let v = [1i, 1, 1, 1];
3075 assert!(v.iter().min_max() == MinMax(&1, &1));
3079 fn test_MinMaxResult() {
3080 let r: MinMaxResult<int> = NoElements;
3081 assert_eq!(r.into_option(), None)
3083 let r = OneElement(1);
3084 assert_eq!(r.into_option(), Some((1,1)));
3086 let r = MinMax(1,2);
3087 assert_eq!(r.into_option(), Some((1,2)));