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_iterator<T: Iterator<A>>(iterator: &mut 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: &mut 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: 'r |A| -> 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: 'r |&A| -> 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: 'r |A| -> 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: 'r |&A| -> 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: 'r |&A| -> 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 foldl.
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: 'r |&mut St, A| -> 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: 'r |A| -> 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: 'r |&A|) -> 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_iterator(self)
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(&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(&self, index: uint) -> Option<A> {
775 self.iter.idx(self.indexable() - index - 1)
779 /// A mutable reference to an iterator
780 pub struct ByRef<'a, T> {
784 impl<'a, A, T: Iterator<A>> Iterator<A> for ByRef<'a, T> {
786 fn next(&mut self) -> Option<A> { self.iter.next() }
788 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
791 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for ByRef<'a, T> {
793 fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
796 /// A trait for iterators over elements which can be added together
797 pub trait AdditiveIterator<A> {
798 /// Iterates over the entire iterator, summing up all the elements
803 /// use std::iter::AdditiveIterator;
805 /// let a = [1, 2, 3, 4, 5];
806 /// let mut it = a.iter().map(|&x| x);
807 /// assert!(it.sum() == 15);
809 fn sum(&mut self) -> A;
812 impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
814 fn sum(&mut self) -> A {
815 let zero: A = Zero::zero();
816 self.fold(zero, |s, x| s + x)
820 /// A trait for iterators over elements whose elements can be multiplied
822 pub trait MultiplicativeIterator<A> {
823 /// Iterates over the entire iterator, multiplying all the elements
828 /// use std::iter::{count, MultiplicativeIterator};
830 /// fn factorial(n: uint) -> uint {
831 /// count(1u, 1).take_while(|&i| i <= n).product()
833 /// assert!(factorial(0) == 1);
834 /// assert!(factorial(1) == 1);
835 /// assert!(factorial(5) == 120);
837 fn product(&mut self) -> A;
840 impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
842 fn product(&mut self) -> A {
843 let one: A = One::one();
844 self.fold(one, |p, x| p * x)
848 /// A trait for iterators over elements which can be compared to one another.
849 /// The type of each element must ascribe to the `Ord` trait.
850 pub trait OrdIterator<A> {
851 /// Consumes the entire iterator to return the maximum element.
856 /// let a = [1, 2, 3, 4, 5];
857 /// assert!(a.iter().max().unwrap() == &5);
859 fn max(&mut self) -> Option<A>;
861 /// Consumes the entire iterator to return the minimum element.
866 /// let a = [1, 2, 3, 4, 5];
867 /// assert!(a.iter().min().unwrap() == &1);
869 fn min(&mut self) -> Option<A>;
871 /// `min_max` finds the minimum and maximum elements in the iterator.
873 /// The return type `MinMaxResult` is an enum of three variants:
874 /// - `NoElements` if the iterator is empty.
875 /// - `OneElement(x)` if the iterator has exactly one element.
876 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two values are equal if and only if
877 /// there is more than one element in the iterator and all elements are equal.
879 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
880 /// and so faster than calling `min` and `max separately which does `2 * n` comparisons.
885 /// use std::iter::{NoElements, OneElement, MinMax};
887 /// let v: [int, ..0] = [];
888 /// assert_eq!(v.iter().min_max(), NoElements);
891 /// assert!(v.iter().min_max() == OneElement(&1));
893 /// let v = [1i, 2, 3, 4, 5];
894 /// assert!(v.iter().min_max() == MinMax(&1, &5));
896 /// let v = [1i, 2, 3, 4, 5, 6];
897 /// assert!(v.iter().min_max() == MinMax(&1, &6));
899 /// let v = [1i, 1, 1, 1];
900 /// assert!(v.iter().min_max() == MinMax(&1, &1));
902 fn min_max(&mut self) -> MinMaxResult<A>;
905 impl<A: TotalOrd, T: Iterator<A>> OrdIterator<A> for T {
907 fn max(&mut self) -> Option<A> {
908 self.fold(None, |max, x| {
911 Some(y) => Some(cmp::max(x, y))
917 fn min(&mut self) -> Option<A> {
918 self.fold(None, |min, x| {
921 Some(y) => Some(cmp::min(x, y))
926 fn min_max(&mut self) -> MinMaxResult<A> {
927 let (mut min, mut max) = match self.next() {
928 None => return NoElements,
931 None => return OneElement(x),
932 Some(y) => if x < y {(x, y)} else {(y,x)}
938 // `first` and `second` are the two next elements we want to look at.
939 // We first compare `first` and `second` (#1). The smaller one is then compared to
940 // current mininum (#2). The larger one is compared to current maximum (#3). This
941 // way we do 3 comparisons for 2 elements.
942 let first = match self.next() {
946 let second = match self.next() {
950 } else if first > max {
958 if first < min {min = first;}
959 if max < second {max = second;}
961 if second < min {min = second;}
962 if max < first {max = first;}
970 /// `MinMaxResult` is an enum returned by `min_max`. See `OrdIterator::min_max` for more detail.
971 #[deriving(Clone, Eq, Show)]
972 pub enum MinMaxResult<T> {
976 /// Iterator with one element, so the minimum and maximum are the same
979 /// More than one element in the iterator, the first element is not larger than the second
983 impl<T: Clone> MinMaxResult<T> {
984 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
985 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
986 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
987 /// performing this operation will make one clone of `x`.
992 /// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
994 /// let r: MinMaxResult<int> = NoElements;
995 /// assert_eq!(r.into_option(), None)
997 /// let r = OneElement(1);
998 /// assert_eq!(r.into_option(), Some((1,1)));
1000 /// let r = MinMax(1,2);
1001 /// assert_eq!(r.into_option(), Some((1,2)));
1003 pub fn into_option(self) -> Option<(T,T)> {
1006 OneElement(x) => Some((x.clone(), x)),
1007 MinMax(x, y) => Some((x, y))
1012 /// A trait for iterators that are cloneable.
1013 pub trait CloneableIterator {
1014 /// Repeats an iterator endlessly
1019 /// use std::iter::{CloneableIterator, count};
1021 /// let a = count(1,1).take(1);
1022 /// let mut cy = a.cycle();
1023 /// assert_eq!(cy.next(), Some(1));
1024 /// assert_eq!(cy.next(), Some(1));
1026 fn cycle(self) -> Cycle<Self>;
1029 impl<A, T: Clone + Iterator<A>> CloneableIterator for T {
1031 fn cycle(self) -> Cycle<T> {
1032 Cycle{orig: self.clone(), iter: self}
1036 /// An iterator that repeats endlessly
1038 pub struct Cycle<T> {
1043 impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
1045 fn next(&mut self) -> Option<A> {
1046 match self.iter.next() {
1047 None => { self.iter = self.orig.clone(); self.iter.next() }
1053 fn size_hint(&self) -> (uint, Option<uint>) {
1054 // the cycle iterator is either empty or infinite
1055 match self.orig.size_hint() {
1056 sz @ (0, Some(0)) => sz,
1057 (0, _) => (0, None),
1058 _ => (uint::MAX, None)
1063 impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
1065 fn indexable(&self) -> uint {
1066 if self.orig.indexable() > 0 {
1074 fn idx(&self, index: uint) -> Option<A> {
1075 let liter = self.iter.indexable();
1076 let lorig = self.orig.indexable();
1079 } else if index < liter {
1080 self.iter.idx(index)
1082 self.orig.idx((index - liter) % lorig)
1087 /// An iterator which strings two iterators together
1089 pub struct Chain<T, U> {
1095 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
1097 fn next(&mut self) -> Option<A> {
1101 match self.a.next() {
1102 Some(x) => return Some(x),
1111 fn size_hint(&self) -> (uint, Option<uint>) {
1112 let (a_lower, a_upper) = self.a.size_hint();
1113 let (b_lower, b_upper) = self.b.size_hint();
1115 let lower = a_lower.saturating_add(b_lower);
1117 let upper = match (a_upper, b_upper) {
1118 (Some(x), Some(y)) => x.checked_add(&y),
1126 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1129 fn next_back(&mut self) -> Option<A> {
1130 match self.b.next_back() {
1132 None => self.a.next_back()
1137 impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
1140 fn indexable(&self) -> uint {
1141 let (a, b) = (self.a.indexable(), self.b.indexable());
1146 fn idx(&self, index: uint) -> Option<A> {
1147 let len = self.a.indexable();
1151 self.b.idx(index - len)
1156 /// An iterator which iterates two other iterators simultaneously
1158 pub struct Zip<T, U> {
1163 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
1165 fn next(&mut self) -> Option<(A, B)> {
1166 match self.a.next() {
1168 Some(x) => match self.b.next() {
1170 Some(y) => Some((x, y))
1176 fn size_hint(&self) -> (uint, Option<uint>) {
1177 let (a_lower, a_upper) = self.a.size_hint();
1178 let (b_lower, b_upper) = self.b.size_hint();
1180 let lower = cmp::min(a_lower, b_lower);
1182 let upper = match (a_upper, b_upper) {
1183 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1184 (Some(x), None) => Some(x),
1185 (None, Some(y)) => Some(y),
1186 (None, None) => None
1193 impl<A, B, T: ExactSize<A>, U: ExactSize<B>> DoubleEndedIterator<(A, B)>
1196 fn next_back(&mut self) -> Option<(A, B)> {
1197 let (a_sz, a_upper) = self.a.size_hint();
1198 let (b_sz, b_upper) = self.b.size_hint();
1199 assert!(a_upper == Some(a_sz));
1200 assert!(b_upper == Some(b_sz));
1202 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1203 } else if a_sz > b_sz {
1204 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1206 let (a_sz, _) = self.a.size_hint();
1207 let (b_sz, _) = self.b.size_hint();
1208 assert!(a_sz == b_sz);
1209 match (self.a.next_back(), self.b.next_back()) {
1210 (Some(x), Some(y)) => Some((x, y)),
1216 impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
1217 RandomAccessIterator<(A, B)> for Zip<T, U> {
1219 fn indexable(&self) -> uint {
1220 cmp::min(self.a.indexable(), self.b.indexable())
1224 fn idx(&self, index: uint) -> Option<(A, B)> {
1225 match self.a.idx(index) {
1227 Some(x) => match self.b.idx(index) {
1229 Some(y) => Some((x, y))
1235 /// An iterator which maps the values of `iter` with `f`
1236 pub struct Map<'a, A, B, T> {
1241 impl<'a, A, B, T> Map<'a, A, B, T> {
1243 fn do_map(&self, elt: Option<A>) -> Option<B> {
1245 Some(a) => Some((self.f)(a)),
1251 impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> {
1253 fn next(&mut self) -> Option<B> {
1254 let next = self.iter.next();
1259 fn size_hint(&self) -> (uint, Option<uint>) {
1260 self.iter.size_hint()
1264 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> {
1266 fn next_back(&mut self) -> Option<B> {
1267 let next = self.iter.next_back();
1272 impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> {
1274 fn indexable(&self) -> uint {
1275 self.iter.indexable()
1279 fn idx(&self, index: uint) -> Option<B> {
1280 self.do_map(self.iter.idx(index))
1284 /// An iterator which filters the elements of `iter` with `predicate`
1285 pub struct Filter<'a, A, T> {
1287 priv predicate: 'a |&A| -> bool
1290 impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> {
1292 fn next(&mut self) -> Option<A> {
1293 for x in self.iter {
1294 if (self.predicate)(&x) {
1304 fn size_hint(&self) -> (uint, Option<uint>) {
1305 let (_, upper) = self.iter.size_hint();
1306 (0, upper) // can't know a lower bound, due to the predicate
1310 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> {
1312 fn next_back(&mut self) -> Option<A> {
1314 match self.iter.next_back() {
1315 None => return None,
1317 if (self.predicate)(&x) {
1328 /// An iterator which uses `f` to both filter and map elements from `iter`
1329 pub struct FilterMap<'a, A, B, T> {
1331 priv f: 'a |A| -> Option<B>
1334 impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> {
1336 fn next(&mut self) -> Option<B> {
1337 for x in self.iter {
1339 Some(y) => return Some(y),
1347 fn size_hint(&self) -> (uint, Option<uint>) {
1348 let (_, upper) = self.iter.size_hint();
1349 (0, upper) // can't know a lower bound, due to the predicate
1353 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1354 for FilterMap<'a, A, B, T> {
1356 fn next_back(&mut self) -> Option<B> {
1358 match self.iter.next_back() {
1359 None => return None,
1362 Some(y) => return Some(y),
1371 /// An iterator which yields the current count and the element during iteration
1373 pub struct Enumerate<T> {
1378 impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1380 fn next(&mut self) -> Option<(uint, A)> {
1381 match self.iter.next() {
1383 let ret = Some((self.count, a));
1392 fn size_hint(&self) -> (uint, Option<uint>) {
1393 self.iter.size_hint()
1397 impl<A, T: ExactSize<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
1399 fn next_back(&mut self) -> Option<(uint, A)> {
1400 match self.iter.next_back() {
1402 let (lower, upper) = self.iter.size_hint();
1403 assert!(upper == Some(lower));
1404 Some((self.count + lower, a))
1411 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
1413 fn indexable(&self) -> uint {
1414 self.iter.indexable()
1418 fn idx(&self, index: uint) -> Option<(uint, A)> {
1419 match self.iter.idx(index) {
1420 Some(a) => Some((self.count + index, a)),
1426 /// An iterator with a `peek()` that returns an optional reference to the next element.
1427 pub struct Peekable<A, T> {
1429 priv peeked: Option<A>,
1432 impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
1434 fn next(&mut self) -> Option<A> {
1435 if self.peeked.is_some() { self.peeked.take() }
1436 else { self.iter.next() }
1440 fn size_hint(&self) -> (uint, Option<uint>) {
1441 let (lo, hi) = self.iter.size_hint();
1442 if self.peeked.is_some() {
1443 let lo = lo.saturating_add(1);
1445 Some(x) => x.checked_add(&1),
1455 impl<'a, A, T: Iterator<A>> Peekable<A, T> {
1456 /// Return a reference to the next element of the iterator with out advancing it,
1457 /// or None if the iterator is exhausted.
1459 pub fn peek(&'a mut self) -> Option<&'a A> {
1460 if self.peeked.is_none() {
1461 self.peeked = self.iter.next();
1464 Some(ref value) => Some(value),
1469 /// Check whether peekable iterator is empty or not.
1471 pub fn is_empty(&mut self) -> bool {
1472 self.peek().is_none()
1476 /// An iterator which rejects elements while `predicate` is true
1477 pub struct SkipWhile<'a, A, T> {
1480 priv predicate: 'a |&A| -> bool
1483 impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> {
1485 fn next(&mut self) -> Option<A> {
1486 let mut next = self.iter.next();
1493 if (self.predicate)(&x) {
1494 next = self.iter.next();
1508 fn size_hint(&self) -> (uint, Option<uint>) {
1509 let (_, upper) = self.iter.size_hint();
1510 (0, upper) // can't know a lower bound, due to the predicate
1514 /// An iterator which only accepts elements while `predicate` is true
1515 pub struct TakeWhile<'a, A, T> {
1518 priv predicate: 'a |&A| -> bool
1521 impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> {
1523 fn next(&mut self) -> Option<A> {
1527 match self.iter.next() {
1529 if (self.predicate)(&x) {
1542 fn size_hint(&self) -> (uint, Option<uint>) {
1543 let (_, upper) = self.iter.size_hint();
1544 (0, upper) // can't know a lower bound, due to the predicate
1548 /// An iterator which skips over `n` elements of `iter`.
1550 pub struct Skip<T> {
1555 impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
1557 fn next(&mut self) -> Option<A> {
1558 let mut next = self.iter.next();
1567 next = self.iter.next();
1582 fn size_hint(&self) -> (uint, Option<uint>) {
1583 let (lower, upper) = self.iter.size_hint();
1585 let lower = lower.saturating_sub(self.n);
1587 let upper = match upper {
1588 Some(x) => Some(x.saturating_sub(self.n)),
1596 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
1598 fn indexable(&self) -> uint {
1599 self.iter.indexable().saturating_sub(self.n)
1603 fn idx(&self, index: uint) -> Option<A> {
1604 if index >= self.indexable() {
1607 self.iter.idx(index + self.n)
1612 /// An iterator which only iterates over the first `n` iterations of `iter`.
1614 pub struct Take<T> {
1619 impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
1621 fn next(&mut self) -> Option<A> {
1631 fn size_hint(&self) -> (uint, Option<uint>) {
1632 let (lower, upper) = self.iter.size_hint();
1634 let lower = cmp::min(lower, self.n);
1636 let upper = match upper {
1637 Some(x) if x < self.n => Some(x),
1645 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
1647 fn indexable(&self) -> uint {
1648 cmp::min(self.iter.indexable(), self.n)
1652 fn idx(&self, index: uint) -> Option<A> {
1653 if index >= self.n {
1656 self.iter.idx(index)
1662 /// An iterator to maintain state while iterating another iterator
1663 pub struct Scan<'a, A, B, T, St> {
1665 priv f: 'a |&mut St, A| -> Option<B>,
1667 /// The current internal state to be passed to the closure next.
1671 impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> {
1673 fn next(&mut self) -> Option<B> {
1674 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1678 fn size_hint(&self) -> (uint, Option<uint>) {
1679 let (_, upper) = self.iter.size_hint();
1680 (0, upper) // can't know a lower bound, due to the scan function
1684 /// An iterator that maps each element to an iterator,
1685 /// and yields the elements of the produced iterators
1687 pub struct FlatMap<'a, A, T, U> {
1689 priv f: 'a |A| -> U,
1690 priv frontiter: Option<U>,
1691 priv backiter: Option<U>,
1694 impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> {
1696 fn next(&mut self) -> Option<B> {
1698 for inner in self.frontiter.mut_iter() {
1703 match self.iter.next().map(|x| (self.f)(x)) {
1704 None => return self.backiter.as_mut().and_then(|it| it.next()),
1705 next => self.frontiter = next,
1711 fn size_hint(&self) -> (uint, Option<uint>) {
1712 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1713 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1714 let lo = flo.saturating_add(blo);
1715 match (self.iter.size_hint(), fhi, bhi) {
1716 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(&b)),
1723 A, T: DoubleEndedIterator<A>,
1724 B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
1725 for FlatMap<'a, A, T, U> {
1727 fn next_back(&mut self) -> Option<B> {
1729 for inner in self.backiter.mut_iter() {
1730 match inner.next_back() {
1735 match self.iter.next_back().map(|x| (self.f)(x)) {
1736 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1737 next => self.backiter = next,
1743 /// An iterator that yields `None` forever after the underlying iterator
1744 /// yields `None` once.
1746 pub struct Fuse<T> {
1751 impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
1753 fn next(&mut self) -> Option<A> {
1757 match self.iter.next() {
1768 fn size_hint(&self) -> (uint, Option<uint>) {
1772 self.iter.size_hint()
1777 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
1779 fn next_back(&mut self) -> Option<A> {
1783 match self.iter.next_back() {
1794 // Allow RandomAccessIterators to be fused without affecting random-access behavior
1795 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
1797 fn indexable(&self) -> uint {
1798 self.iter.indexable()
1802 fn idx(&self, index: uint) -> Option<A> {
1803 self.iter.idx(index)
1808 /// Resets the fuse such that the next call to .next() or .next_back() will
1809 /// call the underlying iterator again even if it previously returned None.
1811 pub fn reset_fuse(&mut self) {
1816 /// An iterator that calls a function with a reference to each
1817 /// element before yielding it.
1818 pub struct Inspect<'a, A, T> {
1823 impl<'a, A, T> Inspect<'a, A, T> {
1825 fn do_inspect(&self, elt: Option<A>) -> Option<A> {
1827 Some(ref a) => (self.f)(a),
1835 impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> {
1837 fn next(&mut self) -> Option<A> {
1838 let next = self.iter.next();
1839 self.do_inspect(next)
1843 fn size_hint(&self) -> (uint, Option<uint>) {
1844 self.iter.size_hint()
1848 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1849 for Inspect<'a, A, T> {
1851 fn next_back(&mut self) -> Option<A> {
1852 let next = self.iter.next_back();
1853 self.do_inspect(next)
1857 impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
1858 for Inspect<'a, A, T> {
1860 fn indexable(&self) -> uint {
1861 self.iter.indexable()
1865 fn idx(&self, index: uint) -> Option<A> {
1866 self.do_inspect(self.iter.idx(index))
1870 /// An iterator which just modifies the contained state throughout iteration.
1871 pub struct Unfold<'a, A, St> {
1872 priv f: 'a |&mut St| -> Option<A>,
1873 /// Internal state that will be yielded on the next iteration
1877 impl<'a, A, St> Unfold<'a, A, St> {
1878 /// Creates a new iterator with the specified closure as the "iterator
1879 /// function" and an initial state to eventually pass to the iterator
1881 pub fn new<'a>(initial_state: St, f: 'a |&mut St| -> Option<A>)
1882 -> Unfold<'a, A, St> {
1885 state: initial_state
1890 impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> {
1892 fn next(&mut self) -> Option<A> {
1893 (self.f)(&mut self.state)
1897 fn size_hint(&self) -> (uint, Option<uint>) {
1898 // no possible known bounds at this point
1903 /// An infinite iterator starting at `start` and advancing by `step` with each
1906 pub struct Counter<A> {
1907 /// The current state the counter is at (next value to be yielded)
1909 /// The amount that this iterator is stepping by
1913 /// Creates a new counter with the specified start/step
1915 pub fn count<A>(start: A, step: A) -> Counter<A> {
1916 Counter{state: start, step: step}
1919 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
1921 fn next(&mut self) -> Option<A> {
1922 let result = self.state.clone();
1923 self.state = self.state + self.step;
1928 fn size_hint(&self) -> (uint, Option<uint>) {
1929 (uint::MAX, None) // Too bad we can't specify an infinite lower bound
1933 /// An iterator over the range [start, stop)
1935 pub struct Range<A> {
1941 /// Return an iterator over the range [start, stop)
1943 pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
1944 Range{state: start, stop: stop, one: One::one()}
1947 // FIXME: #10414: Unfortunate type bound
1948 impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for Range<A> {
1950 fn next(&mut self) -> Option<A> {
1951 if self.state < self.stop {
1952 let result = self.state.clone();
1953 self.state = self.state + self.one;
1961 fn size_hint(&self) -> (uint, Option<uint>) {
1962 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
1963 // handle cases like range(huge, huger)). We don't use uint/int because the difference of
1964 // the i64/u64 might lie within their range.
1965 let bound = match self.state.to_i64() {
1967 let sz = self.stop.to_i64().map(|b| b.checked_sub(&a));
1969 Some(Some(bound)) => bound.to_uint(),
1973 None => match self.state.to_u64() {
1975 let sz = self.stop.to_u64().map(|b| b.checked_sub(&a));
1977 Some(Some(bound)) => bound.to_uint(),
1986 Some(b) => (b, Some(b)),
1987 // Standard fallback for unbounded/unrepresentable bounds
1993 /// `Int` is required to ensure the range will be the same regardless of
1994 /// the direction it is consumed.
1995 impl<A: Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
1997 fn next_back(&mut self) -> Option<A> {
1998 if self.stop > self.state {
1999 self.stop = self.stop - self.one;
2000 Some(self.stop.clone())
2007 /// An iterator over the range [start, stop]
2009 pub struct RangeInclusive<A> {
2010 priv range: Range<A>,
2014 /// Return an iterator over the range [start, stop]
2016 pub fn range_inclusive<A: Add<A, A> + Ord + Clone + One + ToPrimitive>(start: A, stop: A)
2017 -> RangeInclusive<A> {
2018 RangeInclusive{range: range(start, stop), done: false}
2021 impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for RangeInclusive<A> {
2023 fn next(&mut self) -> Option<A> {
2024 match self.range.next() {
2027 if !self.done && self.range.state == self.range.stop {
2029 Some(self.range.stop.clone())
2038 fn size_hint(&self) -> (uint, Option<uint>) {
2039 let (lo, hi) = self.range.size_hint();
2043 let lo = lo.saturating_add(1);
2045 Some(x) => x.checked_add(&1),
2053 impl<A: Sub<A, A> + Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A>
2054 for RangeInclusive<A> {
2056 fn next_back(&mut self) -> Option<A> {
2057 if self.range.stop > self.range.state {
2058 let result = self.range.stop.clone();
2059 self.range.stop = self.range.stop - self.range.one;
2061 } else if !self.done && self.range.state == self.range.stop {
2063 Some(self.range.stop.clone())
2070 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2072 pub struct RangeStep<A> {
2079 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2081 pub fn range_step<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A, step: A) -> RangeStep<A> {
2082 let rev = step < Zero::zero();
2083 RangeStep{state: start, stop: stop, step: step, rev: rev}
2086 impl<A: CheckedAdd + Ord + Clone> Iterator<A> for RangeStep<A> {
2088 fn next(&mut self) -> Option<A> {
2089 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2090 let result = self.state.clone();
2091 match self.state.checked_add(&self.step) {
2092 Some(x) => self.state = x,
2093 None => self.state = self.stop.clone()
2102 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2104 pub struct RangeStepInclusive<A> {
2112 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2114 pub fn range_step_inclusive<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A,
2115 step: A) -> RangeStepInclusive<A> {
2116 let rev = step < Zero::zero();
2117 RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
2120 impl<A: CheckedAdd + Ord + Clone + Eq> Iterator<A> for RangeStepInclusive<A> {
2122 fn next(&mut self) -> Option<A> {
2123 if !self.done && ((self.rev && self.state >= self.stop) ||
2124 (!self.rev && self.state <= self.stop)) {
2125 let result = self.state.clone();
2126 match self.state.checked_add(&self.step) {
2127 Some(x) => self.state = x,
2128 None => self.done = true
2137 /// An iterator that repeats an element endlessly
2139 pub struct Repeat<A> {
2143 impl<A: Clone> Repeat<A> {
2144 /// Create a new `Repeat` that endlessly repeats the element `elt`.
2146 pub fn new(elt: A) -> Repeat<A> {
2147 Repeat{element: elt}
2151 impl<A: Clone> Iterator<A> for Repeat<A> {
2153 fn next(&mut self) -> Option<A> { self.idx(0) }
2155 fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2158 impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
2160 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2163 impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
2165 fn indexable(&self) -> uint { uint::MAX }
2167 fn idx(&self, _: uint) -> Option<A> { Some(self.element.clone()) }
2170 /// Functions for lexicographical ordering of sequences.
2172 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2173 /// that the elements implement both `Eq` and `Ord`.
2175 /// If two sequences are equal up until the point where one ends,
2176 /// the shorter sequence compares less.
2179 use cmp::{TotalEq, TotalOrd, Ord, Eq};
2180 use option::{Some, None};
2181 use super::Iterator;
2183 /// Compare `a` and `b` for equality using `TotalEq`
2184 pub fn equals<A: TotalEq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2186 match (a.next(), b.next()) {
2187 (None, None) => return true,
2188 (None, _) | (_, None) => return false,
2189 (Some(x), Some(y)) => if x != y { return false },
2194 /// Order `a` and `b` lexicographically using `TotalOrd`
2195 pub fn cmp<A: TotalOrd, T: Iterator<A>>(mut a: T, mut b: T) -> cmp::Ordering {
2197 match (a.next(), b.next()) {
2198 (None, None) => return cmp::Equal,
2199 (None, _ ) => return cmp::Less,
2200 (_ , None) => return cmp::Greater,
2201 (Some(x), Some(y)) => match x.cmp(&y) {
2203 non_eq => return non_eq,
2209 /// Compare `a` and `b` for equality (Using partial equality, `Eq`)
2210 pub fn eq<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2212 match (a.next(), b.next()) {
2213 (None, None) => return true,
2214 (None, _) | (_, None) => return false,
2215 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2220 /// Compare `a` and `b` for nonequality (Using partial equality, `Eq`)
2221 pub fn ne<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2223 match (a.next(), b.next()) {
2224 (None, None) => return false,
2225 (None, _) | (_, None) => return true,
2226 (Some(x), Some(y)) => if x.ne(&y) { return true },
2231 /// Return `a` < `b` lexicographically (Using partial order, `Ord`)
2232 pub fn lt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2234 match (a.next(), b.next()) {
2235 (None, None) => return false,
2236 (None, _ ) => return true,
2237 (_ , None) => return false,
2238 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2243 /// Return `a` <= `b` lexicographically (Using partial order, `Ord`)
2244 pub fn le<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2246 match (a.next(), b.next()) {
2247 (None, None) => return true,
2248 (None, _ ) => return true,
2249 (_ , None) => return false,
2250 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2255 /// Return `a` > `b` lexicographically (Using partial order, `Ord`)
2256 pub fn gt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2258 match (a.next(), b.next()) {
2259 (None, None) => return false,
2260 (None, _ ) => return false,
2261 (_ , None) => return true,
2262 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2267 /// Return `a` >= `b` lexicographically (Using partial order, `Ord`)
2268 pub fn ge<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2270 match (a.next(), b.next()) {
2271 (None, None) => return true,
2272 (None, _ ) => return false,
2273 (_ , None) => return true,
2274 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },
2281 use slice::ImmutableVector;
2283 let empty: [int, ..0] = [];
2287 assert!(!lt(xs.iter(), ys.iter()));
2288 assert!(!le(xs.iter(), ys.iter()));
2289 assert!( gt(xs.iter(), ys.iter()));
2290 assert!( ge(xs.iter(), ys.iter()));
2292 assert!( lt(ys.iter(), xs.iter()));
2293 assert!( le(ys.iter(), xs.iter()));
2294 assert!(!gt(ys.iter(), xs.iter()));
2295 assert!(!ge(ys.iter(), xs.iter()));
2297 assert!( lt(empty.iter(), xs.iter()));
2298 assert!( le(empty.iter(), xs.iter()));
2299 assert!(!gt(empty.iter(), xs.iter()));
2300 assert!(!ge(empty.iter(), xs.iter()));
2302 // Sequence with NaN
2304 let v = [0.0/0.0, 3.0];
2306 assert!(!lt(u.iter(), v.iter()));
2307 assert!(!le(u.iter(), v.iter()));
2308 assert!(!gt(u.iter(), v.iter()));
2309 assert!(!ge(u.iter(), v.iter()));
2315 assert!(lt(a.iter(), b.iter()) == (a[0] < b[0]));
2316 assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
2317 assert!(gt(a.iter(), b.iter()) == (a[0] > b[0]));
2318 assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0]));
2320 assert!(lt(c.iter(), b.iter()) == (c[0] < b[0]));
2321 assert!(le(c.iter(), b.iter()) == (c[0] <= b[0]));
2322 assert!(gt(c.iter(), b.iter()) == (c[0] > b[0]));
2323 assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0]));
2337 fn test_counter_from_iter() {
2338 let mut it = count(0, 5).take(10);
2339 let xs: ~[int] = FromIterator::from_iterator(&mut it);
2340 assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
2344 fn test_iterator_chain() {
2345 let xs = [0u, 1, 2, 3, 4, 5];
2346 let ys = [30u, 40, 50, 60];
2347 let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
2348 let mut it = xs.iter().chain(ys.iter());
2351 assert_eq!(x, expected[i]);
2354 assert_eq!(i, expected.len());
2356 let ys = count(30u, 10).take(4);
2357 let mut it = xs.iter().map(|&x| x).chain(ys);
2360 assert_eq!(x, expected[i]);
2363 assert_eq!(i, expected.len());
2367 fn test_filter_map() {
2368 let mut it = count(0u, 1u).take(10)
2369 .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None });
2370 assert_eq!(it.collect::<~[uint]>(), ~[0*0, 2*2, 4*4, 6*6, 8*8]);
2374 fn test_iterator_enumerate() {
2375 let xs = [0u, 1, 2, 3, 4, 5];
2376 let mut it = xs.iter().enumerate();
2383 fn test_iterator_peekable() {
2384 let xs = ~[0u, 1, 2, 3, 4, 5];
2385 let mut it = xs.iter().map(|&x|x).peekable();
2386 assert_eq!(it.peek().unwrap(), &0);
2387 assert_eq!(it.next().unwrap(), 0);
2388 assert_eq!(it.next().unwrap(), 1);
2389 assert_eq!(it.next().unwrap(), 2);
2390 assert_eq!(it.peek().unwrap(), &3);
2391 assert_eq!(it.peek().unwrap(), &3);
2392 assert_eq!(it.next().unwrap(), 3);
2393 assert_eq!(it.next().unwrap(), 4);
2394 assert_eq!(it.peek().unwrap(), &5);
2395 assert_eq!(it.next().unwrap(), 5);
2396 assert!(it.peek().is_none());
2397 assert!(it.next().is_none());
2401 fn test_iterator_take_while() {
2402 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2403 let ys = [0u, 1, 2, 3, 5, 13];
2404 let mut it = xs.iter().take_while(|&x| *x < 15u);
2407 assert_eq!(x, ys[i]);
2410 assert_eq!(i, ys.len());
2414 fn test_iterator_skip_while() {
2415 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2416 let ys = [15, 16, 17, 19];
2417 let mut it = xs.iter().skip_while(|&x| *x < 15u);
2420 assert_eq!(x, ys[i]);
2423 assert_eq!(i, ys.len());
2427 fn test_iterator_skip() {
2428 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
2429 let ys = [13, 15, 16, 17, 19, 20, 30];
2430 let mut it = xs.iter().skip(5);
2433 assert_eq!(x, ys[i]);
2436 assert_eq!(i, ys.len());
2440 fn test_iterator_take() {
2441 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2442 let ys = [0u, 1, 2, 3, 5];
2443 let mut it = xs.iter().take(5);
2446 assert_eq!(x, ys[i]);
2449 assert_eq!(i, ys.len());
2453 fn test_iterator_scan() {
2454 // test the type inference
2455 fn add(old: &mut int, new: &uint) -> Option<f64> {
2456 *old += *new as int;
2459 let xs = [0u, 1, 2, 3, 4];
2460 let ys = [0f64, 1.0, 3.0, 6.0, 10.0];
2462 let mut it = xs.iter().scan(0, add);
2465 assert_eq!(x, ys[i]);
2468 assert_eq!(i, ys.len());
2472 fn test_iterator_flat_map() {
2473 let xs = [0u, 3, 6];
2474 let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
2475 let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3));
2478 assert_eq!(x, ys[i]);
2481 assert_eq!(i, ys.len());
2486 let xs = [1u, 2, 3, 4];
2491 .inspect(|_| n += 1)
2492 .collect::<~[uint]>();
2494 assert_eq!(n, xs.len());
2495 assert_eq!(xs.as_slice(), ys.as_slice());
2500 fn count(st: &mut uint) -> Option<uint> {
2502 let ret = Some(*st);
2510 let mut it = Unfold::new(0, count);
2513 assert_eq!(counted, i);
2522 let it = count(0u, 1).take(cycle_len).cycle();
2523 assert_eq!(it.size_hint(), (uint::MAX, None));
2524 for (i, x) in it.take(100).enumerate() {
2525 assert_eq!(i % cycle_len, x);
2528 let mut it = count(0u, 1).take(0).cycle();
2529 assert_eq!(it.size_hint(), (0, Some(0)));
2530 assert_eq!(it.next(), None);
2534 fn test_iterator_nth() {
2535 let v = &[0, 1, 2, 3, 4];
2536 for i in range(0u, v.len()) {
2537 assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
2542 fn test_iterator_last() {
2543 let v = &[0, 1, 2, 3, 4];
2544 assert_eq!(v.iter().last().unwrap(), &4);
2545 assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
2549 fn test_iterator_len() {
2550 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2551 assert_eq!(v.slice(0, 4).iter().len(), 4);
2552 assert_eq!(v.slice(0, 10).iter().len(), 10);
2553 assert_eq!(v.slice(0, 0).iter().len(), 0);
2557 fn test_iterator_sum() {
2558 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2559 assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
2560 assert_eq!(v.iter().map(|&x| x).sum(), 55);
2561 assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
2565 fn test_iterator_product() {
2566 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2567 assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
2568 assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
2569 assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
2573 fn test_iterator_max() {
2574 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2575 assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
2576 assert_eq!(v.iter().map(|&x| x).max(), Some(10));
2577 assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
2581 fn test_iterator_min() {
2582 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2583 assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
2584 assert_eq!(v.iter().map(|&x| x).min(), Some(0));
2585 assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
2589 fn test_iterator_size_hint() {
2590 let c = count(0, 1);
2591 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2592 let v2 = &[10, 11, 12];
2595 assert_eq!(c.size_hint(), (uint::MAX, None));
2596 assert_eq!(vi.size_hint(), (10, Some(10)));
2598 assert_eq!(c.take(5).size_hint(), (5, Some(5)));
2599 assert_eq!(c.skip(5).size_hint().val1(), None);
2600 assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
2601 assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
2602 assert_eq!(c.enumerate().size_hint(), (uint::MAX, None));
2603 assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None));
2604 assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
2605 assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
2606 assert_eq!(c.filter(|_| false).size_hint(), (0, None));
2607 assert_eq!(c.map(|_| 0).size_hint(), (uint::MAX, None));
2608 assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
2610 assert_eq!(vi.take(5).size_hint(), (5, Some(5)));
2611 assert_eq!(vi.take(12).size_hint(), (10, Some(10)));
2612 assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
2613 assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
2614 assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
2615 assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
2616 assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
2617 assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13)));
2618 assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
2619 assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
2620 assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
2621 assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10)));
2622 assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
2627 let a = ~[1, 2, 3, 4, 5];
2628 let b: ~[int] = a.iter().map(|&x| x).collect();
2634 let v: ~&[int] = ~&[1, 2, 3, 4, 5];
2635 assert!(v.iter().all(|&x| x < 10));
2636 assert!(!v.iter().all(|&x| x % 2 == 0));
2637 assert!(!v.iter().all(|&x| x > 100));
2638 assert!(v.slice(0, 0).iter().all(|_| fail!()));
2643 let v: ~&[int] = ~&[1, 2, 3, 4, 5];
2644 assert!(v.iter().any(|&x| x < 10));
2645 assert!(v.iter().any(|&x| x % 2 == 0));
2646 assert!(!v.iter().any(|&x| x > 100));
2647 assert!(!v.slice(0, 0).iter().any(|_| fail!()));
2652 let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
2653 assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
2654 assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
2655 assert!(v.iter().find(|x| *x % 12 == 0).is_none());
2659 fn test_position() {
2660 let v = &[1, 3, 9, 27, 103, 14, 11];
2661 assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
2662 assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
2663 assert!(v.iter().position(|x| *x % 12 == 0).is_none());
2668 let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
2669 assert_eq!(xs.iter().count(|x| *x == 2), 3);
2670 assert_eq!(xs.iter().count(|x| *x == 5), 1);
2671 assert_eq!(xs.iter().count(|x| *x == 95), 0);
2676 let xs: &[int] = &[-3, 0, 1, 5, -10];
2677 assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
2682 let xs: &[int] = &[-3, 0, 1, 5, -10];
2683 assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
2688 let mut xs = range(0, 10);
2689 // sum the first five values
2690 let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
2691 assert_eq!(partial_sum, 10);
2692 assert_eq!(xs.next(), Some(5));
2697 let xs = [2, 4, 6, 8, 10, 12, 14, 16];
2698 let mut it = xs.iter();
2701 assert_eq!(it.rev().map(|&x| x).collect::<~[int]>(), ~[16, 14, 12, 10, 8, 6]);
2705 fn test_double_ended_map() {
2706 let xs = [1, 2, 3, 4, 5, 6];
2707 let mut it = xs.iter().map(|&x| x * -1);
2708 assert_eq!(it.next(), Some(-1));
2709 assert_eq!(it.next(), Some(-2));
2710 assert_eq!(it.next_back(), Some(-6));
2711 assert_eq!(it.next_back(), Some(-5));
2712 assert_eq!(it.next(), Some(-3));
2713 assert_eq!(it.next_back(), Some(-4));
2714 assert_eq!(it.next(), None);
2718 fn test_double_ended_enumerate() {
2719 let xs = [1, 2, 3, 4, 5, 6];
2720 let mut it = xs.iter().map(|&x| x).enumerate();
2721 assert_eq!(it.next(), Some((0, 1)));
2722 assert_eq!(it.next(), Some((1, 2)));
2723 assert_eq!(it.next_back(), Some((5, 6)));
2724 assert_eq!(it.next_back(), Some((4, 5)));
2725 assert_eq!(it.next_back(), Some((3, 4)));
2726 assert_eq!(it.next_back(), Some((2, 3)));
2727 assert_eq!(it.next(), None);
2731 fn test_double_ended_zip() {
2732 let xs = [1, 2, 3, 4, 5, 6];
2733 let ys = [1, 2, 3, 7];
2734 let a = xs.iter().map(|&x| x);
2735 let b = ys.iter().map(|&x| x);
2736 let mut it = a.zip(b);
2737 assert_eq!(it.next(), Some((1, 1)));
2738 assert_eq!(it.next(), Some((2, 2)));
2739 assert_eq!(it.next_back(), Some((4, 7)));
2740 assert_eq!(it.next_back(), Some((3, 3)));
2741 assert_eq!(it.next(), None);
2745 fn test_double_ended_filter() {
2746 let xs = [1, 2, 3, 4, 5, 6];
2747 let mut it = xs.iter().filter(|&x| *x & 1 == 0);
2748 assert_eq!(it.next_back().unwrap(), &6);
2749 assert_eq!(it.next_back().unwrap(), &4);
2750 assert_eq!(it.next().unwrap(), &2);
2751 assert_eq!(it.next_back(), None);
2755 fn test_double_ended_filter_map() {
2756 let xs = [1, 2, 3, 4, 5, 6];
2757 let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
2758 assert_eq!(it.next_back().unwrap(), 12);
2759 assert_eq!(it.next_back().unwrap(), 8);
2760 assert_eq!(it.next().unwrap(), 4);
2761 assert_eq!(it.next_back(), None);
2765 fn test_double_ended_chain() {
2766 let xs = [1, 2, 3, 4, 5];
2767 let ys = ~[7, 9, 11];
2768 let mut it = xs.iter().chain(ys.iter()).rev();
2769 assert_eq!(it.next().unwrap(), &11)
2770 assert_eq!(it.next().unwrap(), &9)
2771 assert_eq!(it.next_back().unwrap(), &1)
2772 assert_eq!(it.next_back().unwrap(), &2)
2773 assert_eq!(it.next_back().unwrap(), &3)
2774 assert_eq!(it.next_back().unwrap(), &4)
2775 assert_eq!(it.next_back().unwrap(), &5)
2776 assert_eq!(it.next_back().unwrap(), &7)
2777 assert_eq!(it.next_back(), None)
2781 fn test_rposition() {
2782 fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
2783 fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
2784 let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
2786 assert_eq!(v.iter().rposition(f), Some(3u));
2787 assert!(v.iter().rposition(g).is_none());
2792 fn test_rposition_fail() {
2793 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
2795 v.iter().rposition(|_elt| {
2806 fn check_randacc_iter<A: Eq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint)
2808 let mut b = a.clone();
2809 assert_eq!(len, b.indexable());
2811 for (i, elt) in a.enumerate() {
2812 assert!(Some(elt) == b.idx(i));
2816 assert!(None == b.idx(n));
2817 // call recursively to check after picking off an element
2820 check_randacc_iter(b, len-1);
2826 fn test_double_ended_flat_map() {
2829 let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
2830 assert_eq!(it.next_back().unwrap(), &8);
2831 assert_eq!(it.next().unwrap(), &5);
2832 assert_eq!(it.next_back().unwrap(), &7);
2833 assert_eq!(it.next_back().unwrap(), &6);
2834 assert_eq!(it.next_back().unwrap(), &8);
2835 assert_eq!(it.next().unwrap(), &6);
2836 assert_eq!(it.next_back().unwrap(), &7);
2837 assert_eq!(it.next_back(), None);
2838 assert_eq!(it.next(), None);
2839 assert_eq!(it.next_back(), None);
2843 fn test_random_access_chain() {
2844 let xs = [1, 2, 3, 4, 5];
2845 let ys = ~[7, 9, 11];
2846 let mut it = xs.iter().chain(ys.iter());
2847 assert_eq!(it.idx(0).unwrap(), &1);
2848 assert_eq!(it.idx(5).unwrap(), &7);
2849 assert_eq!(it.idx(7).unwrap(), &11);
2850 assert!(it.idx(8).is_none());
2856 assert_eq!(it.idx(0).unwrap(), &3);
2857 assert_eq!(it.idx(4).unwrap(), &9);
2858 assert!(it.idx(6).is_none());
2860 check_randacc_iter(it, xs.len() + ys.len() - 3);
2864 fn test_random_access_enumerate() {
2865 let xs = [1, 2, 3, 4, 5];
2866 check_randacc_iter(xs.iter().enumerate(), xs.len());
2870 fn test_random_access_rev() {
2871 let xs = [1, 2, 3, 4, 5];
2872 check_randacc_iter(xs.iter().rev(), xs.len());
2873 let mut it = xs.iter().rev();
2877 check_randacc_iter(it, xs.len() - 3);
2881 fn test_random_access_zip() {
2882 let xs = [1, 2, 3, 4, 5];
2883 let ys = [7, 9, 11];
2884 check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
2888 fn test_random_access_take() {
2889 let xs = [1, 2, 3, 4, 5];
2890 let empty: &[int] = [];
2891 check_randacc_iter(xs.iter().take(3), 3);
2892 check_randacc_iter(xs.iter().take(20), xs.len());
2893 check_randacc_iter(xs.iter().take(0), 0);
2894 check_randacc_iter(empty.iter().take(2), 0);
2898 fn test_random_access_skip() {
2899 let xs = [1, 2, 3, 4, 5];
2900 let empty: &[int] = [];
2901 check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
2902 check_randacc_iter(empty.iter().skip(2), 0);
2906 fn test_random_access_inspect() {
2907 let xs = [1, 2, 3, 4, 5];
2909 // test .map and .inspect that don't implement Clone
2910 let it = xs.iter().inspect(|_| {});
2911 assert_eq!(xs.len(), it.indexable());
2912 for (i, elt) in xs.iter().enumerate() {
2913 assert_eq!(Some(elt), it.idx(i));
2919 fn test_random_access_map() {
2920 let xs = [1, 2, 3, 4, 5];
2922 let it = xs.iter().map(|x| *x);
2923 assert_eq!(xs.len(), it.indexable());
2924 for (i, elt) in xs.iter().enumerate() {
2925 assert_eq!(Some(*elt), it.idx(i));
2930 fn test_random_access_cycle() {
2931 let xs = [1, 2, 3, 4, 5];
2932 let empty: &[int] = [];
2933 check_randacc_iter(xs.iter().cycle().take(27), 27);
2934 check_randacc_iter(empty.iter().cycle(), 0);
2938 fn test_double_ended_range() {
2939 assert_eq!(range(11i, 14).rev().collect::<~[int]>(), ~[13i, 12, 11]);
2940 for _ in range(10i, 0).rev() {
2941 fail!("unreachable");
2944 assert_eq!(range(11u, 14).rev().collect::<~[uint]>(), ~[13u, 12, 11]);
2945 for _ in range(10u, 0).rev() {
2946 fail!("unreachable");
2952 /// A mock type to check Range when ToPrimitive returns None
2955 impl ToPrimitive for Foo {
2956 fn to_i64(&self) -> Option<i64> { None }
2957 fn to_u64(&self) -> Option<u64> { None }
2960 impl Add<Foo, Foo> for Foo {
2961 fn add(&self, _: &Foo) -> Foo {
2967 fn eq(&self, _: &Foo) -> bool {
2973 fn lt(&self, _: &Foo) -> bool {
2978 impl Clone for Foo {
2979 fn clone(&self) -> Foo {
2984 impl Mul<Foo, Foo> for Foo {
2985 fn mul(&self, _: &Foo) -> Foo {
2990 impl num::One for Foo {
2996 assert_eq!(range(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4]);
2997 assert_eq!(range(-10i, -1).collect::<~[int]>(), ~[-10, -9, -8, -7, -6, -5, -4, -3, -2]);
2998 assert_eq!(range(0i, 5).rev().collect::<~[int]>(), ~[4, 3, 2, 1, 0]);
2999 assert_eq!(range(200, -5).collect::<~[int]>(), ~[]);
3000 assert_eq!(range(200, -5).rev().collect::<~[int]>(), ~[]);
3001 assert_eq!(range(200, 200).collect::<~[int]>(), ~[]);
3002 assert_eq!(range(200, 200).rev().collect::<~[int]>(), ~[]);
3004 assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
3005 // this test is only meaningful when sizeof uint < sizeof u64
3006 assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1)));
3007 assert_eq!(range(-10i, -1).size_hint(), (9, Some(9)));
3008 assert_eq!(range(Foo, Foo).size_hint(), (0, None));
3012 fn test_range_inclusive() {
3013 assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4, 5]);
3014 assert_eq!(range_inclusive(0i, 5).rev().collect::<~[int]>(), ~[5i, 4, 3, 2, 1, 0]);
3015 assert_eq!(range_inclusive(200, -5).collect::<~[int]>(), ~[]);
3016 assert_eq!(range_inclusive(200, -5).rev().collect::<~[int]>(), ~[]);
3017 assert_eq!(range_inclusive(200, 200).collect::<~[int]>(), ~[200]);
3018 assert_eq!(range_inclusive(200, 200).rev().collect::<~[int]>(), ~[200]);
3022 fn test_range_step() {
3023 assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15]);
3024 assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5]);
3025 assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
3026 assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
3027 assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), ~[]);
3028 assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), ~[]);
3032 fn test_range_step_inclusive() {
3033 assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15, 20]);
3034 assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5, 0]);
3035 assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
3036 assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
3037 assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), ~[]);
3038 assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), ~[200]);
3043 let mut ys = [1, 2, 3, 4, 5];
3044 ys.mut_iter().reverse_();
3045 assert!(ys == [5, 4, 3, 2, 1]);
3049 fn test_peekable_is_empty() {
3051 let mut it = a.iter().peekable();
3052 assert!( !it.is_empty() );
3054 assert!( it.is_empty() );
3059 let v: [int, ..0] = [];
3060 assert_eq!(v.iter().min_max(), NoElements);
3063 assert!(v.iter().min_max() == OneElement(&1));
3065 let v = [1i, 2, 3, 4, 5];
3066 assert!(v.iter().min_max() == MinMax(&1, &5));
3068 let v = [1i, 2, 3, 4, 5, 6];
3069 assert!(v.iter().min_max() == MinMax(&1, &6));
3071 let v = [1i, 1, 1, 1];
3072 assert!(v.iter().min_max() == MinMax(&1, &1));
3076 fn test_MinMaxResult() {
3077 let r: MinMaxResult<int> = NoElements;
3078 assert_eq!(r.into_option(), None)
3080 let r = OneElement(1);
3081 assert_eq!(r.into_option(), Some((1,1)));
3083 let r = MinMax(1,2);
3084 assert_eq!(r.into_option(), Some((1,2)));