]> git.lizzy.rs Git - rust.git/blob - src/libstd/iter.rs
create a sensible comparison trait hierarchy
[rust.git] / src / libstd / iter.rs
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.
4 //
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.
10
11 /*!
12
13 Composable external iterators
14
15 # The `Iterator` trait
16
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`.
20
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.
24
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
28 more.
29
30 ## Rust's `for` loop
31
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.
36
37 ```rust
38 let values = ~[1, 2, 3];
39
40 // "Syntactical sugar" taking advantage of an iterator
41 for &x in values.iter() {
42     println!("{}", x);
43 }
44
45 // Rough translation of the iteration without a `for` iterator.
46 let mut it = values.iter();
47 loop {
48     match it.next() {
49         Some(&x) => {
50             println!("{}", x);
51         }
52         None => { break }
53     }
54 }
55  ```
56
57 This `for` loop syntax can be applied to any iterator over any type.
58
59 ## Iteration protocol and more
60
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.
64
65 */
66
67 use cmp;
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};
72 use clone::Clone;
73 use uint;
74 use mem;
75
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;
80 }
81
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);
86 }
87
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.
91 ///
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
97 /// else.
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>;
101
102     /// Return a lower bound and upper bound on the remaining length of the iterator.
103     ///
104     /// The common use case for the estimate is pre-allocating space to store the results.
105     #[inline]
106     fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
107
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.
111     ///
112     /// # Example
113     ///
114     /// ```rust
115     /// let a = [0];
116     /// let b = [1];
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());
121     /// ```
122     #[inline]
123     fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
124         Chain{a: self, b: other, flag: false}
125     }
126
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
130     /// return None.
131     ///
132     /// # Example
133     ///
134     /// ```rust
135     /// let a = [0];
136     /// let b = [1];
137     /// let mut it = a.iter().zip(b.iter());
138     /// assert_eq!(it.next().unwrap(), (&0, &1));
139     /// assert!(it.next().is_none());
140     /// ```
141     #[inline]
142     fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
143         Zip{a: self, b: other}
144     }
145
146     /// Creates a new iterator which will apply the specified function to each
147     /// element returned by the first, yielding the mapped element instead.
148     ///
149     /// # Example
150     ///
151     /// ```rust
152     /// let a = [1, 2];
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());
157     /// ```
158     #[inline]
159     fn map<'r, B>(self, f: 'r |A| -> B) -> Map<'r, A, B, Self> {
160         Map{iter: self, f: f}
161     }
162
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.
166     ///
167     /// # Example
168     ///
169     /// ```rust
170     /// let a = [1, 2];
171     /// let mut it = a.iter().filter(|&x| *x > 1);
172     /// assert_eq!(it.next().unwrap(), &2);
173     /// assert!(it.next().is_none());
174     /// ```
175     #[inline]
176     fn filter<'r>(self, predicate: 'r |&A| -> bool) -> Filter<'r, A, Self> {
177         Filter{iter: self, predicate: predicate}
178     }
179
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.
183     ///
184     /// # Example
185     ///
186     /// ```rust
187     /// let a = [1, 2];
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());
191     /// ```
192     #[inline]
193     fn filter_map<'r, B>(self, f: 'r |A| -> Option<B>) -> FilterMap<'r, A, B, Self> {
194         FilterMap { iter: self, f: f }
195     }
196
197     /// Creates an iterator which yields a pair of the value returned by this
198     /// iterator plus the current index of iteration.
199     ///
200     /// # Example
201     ///
202     /// ```rust
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());
208     /// ```
209     #[inline]
210     fn enumerate(self) -> Enumerate<Self> {
211         Enumerate{iter: self, count: 0}
212     }
213
214
215     /// Creates an iterator that has a `.peek()` method
216     /// that returns an optional reference to the next element.
217     ///
218     /// # Example
219     ///
220     /// ```rust
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());
231     /// ```
232     #[inline]
233     fn peekable(self) -> Peekable<A, Self> {
234         Peekable{iter: self, peeked: None}
235     }
236
237     /// Creates an iterator which invokes the predicate on elements until it
238     /// returns false. Once the predicate returns false, all further elements are
239     /// yielded.
240     ///
241     /// # Example
242     ///
243     /// ```rust
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());
250     /// ```
251     #[inline]
252     fn skip_while<'r>(self, predicate: 'r |&A| -> bool) -> SkipWhile<'r, A, Self> {
253         SkipWhile{iter: self, flag: false, predicate: predicate}
254     }
255
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.
259     ///
260     /// # Example
261     ///
262     /// ```rust
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());
268     /// ```
269     #[inline]
270     fn take_while<'r>(self, predicate: 'r |&A| -> bool) -> TakeWhile<'r, A, Self> {
271         TakeWhile{iter: self, flag: false, predicate: predicate}
272     }
273
274     /// Creates an iterator which skips the first `n` elements of this iterator,
275     /// and then it yields all further items.
276     ///
277     /// # Example
278     ///
279     /// ```rust
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());
285     /// ```
286     #[inline]
287     fn skip(self, n: uint) -> Skip<Self> {
288         Skip{iter: self, n: n}
289     }
290
291     /// Creates an iterator which yields the first `n` elements of this
292     /// iterator, and then it will always return None.
293     ///
294     /// # Example
295     ///
296     /// ```rust
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());
303     /// ```
304     #[inline]
305     fn take(self, n: uint) -> Take<Self> {
306         Take{iter: self, n: n}
307     }
308
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.
313     ///
314     /// # Example
315     ///
316     /// ```rust
317     /// let a = [1, 2, 3, 4, 5];
318     /// let mut it = a.iter().scan(1, |fac, &x| {
319     ///   *fac = *fac * x;
320     ///   Some(*fac)
321     /// });
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());
328     /// ```
329     #[inline]
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}
333     }
334
335     /// Creates an iterator that maps each element to an iterator,
336     /// and yields the elements of the produced iterators
337     ///
338     /// # Example
339     ///
340     /// ```rust
341     /// use std::iter::count;
342     ///
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`
347     /// let mut i = 0;
348     /// for x in it {
349     ///     assert_eq!(x, ys[i]);
350     ///     i += 1;
351     /// }
352     /// ```
353     #[inline]
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 }
357     }
358
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.
362     ///
363     /// # Example
364     ///
365     /// ```rust
366     /// fn process<U: Iterator<int>>(it: U) -> int {
367     ///     let mut it = it.fuse();
368     ///     let mut sum = 0;
369     ///     for x in it {
370     ///         if x > 5 {
371     ///             continue;
372     ///         }
373     ///         sum += x;
374     ///     }
375     ///     // did we exhaust the iterator?
376     ///     if it.next().is_none() {
377     ///         sum += 1000;
378     ///     }
379     ///     sum
380     /// }
381     /// let x = ~[1,2,3,7,8,9];
382     /// assert_eq!(process(x.move_iter()), 1006);
383     /// ```
384     #[inline]
385     fn fuse(self) -> Fuse<Self> {
386         Fuse{iter: self, done: false}
387     }
388
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.
392     ///
393     /// # Example
394     ///
395     /// ```rust
396     /// use std::iter::AdditiveIterator;
397     ///
398     /// let xs = [1u, 4, 2, 3, 8, 9, 6];
399     /// let sum = xs.iter()
400     ///             .map(|&x| x)
401     ///             .inspect(|&x| debug!("filtering {}", x))
402     ///             .filter(|&x| x % 2 == 0)
403     ///             .inspect(|&x| debug!("{} made it through", x))
404     ///             .sum();
405     /// println!("{}", sum);
406     /// ```
407     #[inline]
408     fn inspect<'r>(self, f: 'r |&A|) -> Inspect<'r, A, Self> {
409         Inspect{iter: self, f: f}
410     }
411
412     /// Creates a wrapper around a mutable reference to the iterator.
413     ///
414     /// This is useful to allow applying iterator adaptors while still
415     /// retaining ownership of the original iterator value.
416     ///
417     /// # Example
418     ///
419     /// ```rust
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));
426     /// ```
427     fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
428         ByRef{iter: self}
429     }
430
431     /// Apply a function to each element, or stop iterating if the
432     /// function returns `false`.
433     ///
434     /// # Example
435     ///
436     /// ```rust
437     /// range(0, 5).advance(|x| {print!("{} ", x); true});
438     /// ```
439     #[inline]
440     fn advance(&mut self, f: |A| -> bool) -> bool {
441         loop {
442             match self.next() {
443                 Some(x) => {
444                     if !f(x) { return false; }
445                 }
446                 None => { return true; }
447             }
448         }
449     }
450
451     /// Loops through the entire iterator, collecting all of the elements into
452     /// a container implementing `FromIterator`.
453     ///
454     /// # Example
455     ///
456     /// ```rust
457     /// let a = [1, 2, 3, 4, 5];
458     /// let b: ~[int] = a.iter().map(|&x| x).collect();
459     /// assert!(a == b);
460     /// ```
461     #[inline]
462     fn collect<B: FromIterator<A>>(&mut self) -> B {
463         FromIterator::from_iterator(self)
464     }
465
466     /// Loops through the entire iterator, collecting all of the elements into
467     /// a unique vector. This is simply collect() specialized for vectors.
468     ///
469     /// # Example
470     ///
471     /// ```rust
472     /// let a = [1, 2, 3, 4, 5];
473     /// let b: ~[int] = a.iter().map(|&x| x).to_owned_vec();
474     /// assert!(a == b);
475     /// ```
476     #[inline]
477     fn to_owned_vec(&mut self) -> ~[A] {
478         self.collect()
479     }
480
481     /// Loops through `n` iterations, returning the `n`th element of the
482     /// iterator.
483     ///
484     /// # Example
485     ///
486     /// ```rust
487     /// let a = [1, 2, 3, 4, 5];
488     /// let mut it = a.iter();
489     /// assert!(it.nth(2).unwrap() == &3);
490     /// assert!(it.nth(2) == None);
491     /// ```
492     #[inline]
493     fn nth(&mut self, mut n: uint) -> Option<A> {
494         loop {
495             match self.next() {
496                 Some(x) => if n == 0 { return Some(x) },
497                 None => return None
498             }
499             n -= 1;
500         }
501     }
502
503     /// Loops through the entire iterator, returning the last element of the
504     /// iterator.
505     ///
506     /// # Example
507     ///
508     /// ```rust
509     /// let a = [1, 2, 3, 4, 5];
510     /// assert!(a.iter().last().unwrap() == &5);
511     /// ```
512     #[inline]
513     fn last(&mut self) -> Option<A> {
514         let mut last = None;
515         for x in *self { last = Some(x); }
516         last
517     }
518
519     /// Performs a fold operation over the entire iterator, returning the
520     /// eventual state at the end of the iteration.
521     ///
522     /// # Example
523     ///
524     /// ```rust
525     /// let a = [1, 2, 3, 4, 5];
526     /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
527     /// ```
528     #[inline]
529     fn fold<B>(&mut self, init: B, f: |B, A| -> B) -> B {
530         let mut accum = init;
531         loop {
532             match self.next() {
533                 Some(x) => { accum = f(accum, x); }
534                 None    => { break; }
535             }
536         }
537         accum
538     }
539
540     /// Counts the number of elements in this iterator.
541     ///
542     /// # Example
543     ///
544     /// ```rust
545     /// let a = [1, 2, 3, 4, 5];
546     /// let mut it = a.iter();
547     /// assert!(it.len() == 5);
548     /// assert!(it.len() == 0);
549     /// ```
550     #[inline]
551     fn len(&mut self) -> uint {
552         self.fold(0, |cnt, _x| cnt + 1)
553     }
554
555     /// Tests whether the predicate holds true for all elements in the iterator.
556     ///
557     /// # Example
558     ///
559     /// ```rust
560     /// let a = [1, 2, 3, 4, 5];
561     /// assert!(a.iter().all(|x| *x > 0));
562     /// assert!(!a.iter().all(|x| *x > 2));
563     /// ```
564     #[inline]
565     fn all(&mut self, f: |A| -> bool) -> bool {
566         for x in *self { if !f(x) { return false; } }
567         true
568     }
569
570     /// Tests whether any element of an iterator satisfies the specified
571     /// predicate.
572     ///
573     /// # Example
574     ///
575     /// ```rust
576     /// let a = [1, 2, 3, 4, 5];
577     /// let mut it = a.iter();
578     /// assert!(it.any(|x| *x == 3));
579     /// assert!(!it.any(|x| *x == 3));
580     /// ```
581     #[inline]
582     fn any(&mut self, f: |A| -> bool) -> bool {
583         for x in *self { if f(x) { return true; } }
584         false
585     }
586
587     /// Return the first element satisfying the specified predicate
588     #[inline]
589     fn find(&mut self, predicate: |&A| -> bool) -> Option<A> {
590         for x in *self {
591             if predicate(&x) { return Some(x) }
592         }
593         None
594     }
595
596     /// Return the index of the first element satisfying the specified predicate
597     #[inline]
598     fn position(&mut self, predicate: |A| -> bool) -> Option<uint> {
599         let mut i = 0;
600         for x in *self {
601             if predicate(x) {
602                 return Some(i);
603             }
604             i += 1;
605         }
606         None
607     }
608
609     /// Count the number of elements satisfying the specified predicate
610     #[inline]
611     fn count(&mut self, predicate: |A| -> bool) -> uint {
612         let mut i = 0;
613         for x in *self {
614             if predicate(x) { i += 1 }
615         }
616         i
617     }
618
619     /// Return the element that gives the maximum value from the
620     /// specified function.
621     ///
622     /// # Example
623     ///
624     /// ```rust
625     /// let xs = [-3i, 0, 1, 5, -10];
626     /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
627     /// ```
628     #[inline]
629     fn max_by<B: Ord>(&mut self, f: |&A| -> B) -> Option<A> {
630         self.fold(None, |max: Option<(A, B)>, x| {
631             let x_val = f(&x);
632             match max {
633                 None             => Some((x, x_val)),
634                 Some((y, y_val)) => if x_val > y_val {
635                     Some((x, x_val))
636                 } else {
637                     Some((y, y_val))
638                 }
639             }
640         }).map(|(x, _)| x)
641     }
642
643     /// Return the element that gives the minimum value from the
644     /// specified function.
645     ///
646     /// # Example
647     ///
648     /// ```rust
649     /// let xs = [-3i, 0, 1, 5, -10];
650     /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
651     /// ```
652     #[inline]
653     fn min_by<B: Ord>(&mut self, f: |&A| -> B) -> Option<A> {
654         self.fold(None, |min: Option<(A, B)>, x| {
655             let x_val = f(&x);
656             match min {
657                 None             => Some((x, x_val)),
658                 Some((y, y_val)) => if x_val < y_val {
659                     Some((x, x_val))
660                 } else {
661                     Some((y, y_val))
662                 }
663             }
664         }).map(|(x, _)| x)
665     }
666 }
667
668 /// A range iterator able to yield elements from both ends
669 pub trait DoubleEndedIterator<A>: Iterator<A> {
670     /// Yield an element from the end of the range, returning `None` if the range is empty.
671     fn next_back(&mut self) -> Option<A>;
672
673     /// Change the direction of the iterator
674     ///
675     /// The flipped iterator swaps the ends on an iterator that can already
676     /// be iterated from the front and from the back.
677     ///
678     ///
679     /// If the iterator also implements RandomAccessIterator, the flipped
680     /// iterator is also random access, with the indices starting at the back
681     /// of the original iterator.
682     ///
683     /// Note: Random access with flipped indices still only applies to the first
684     /// `uint::MAX` elements of the original iterator.
685     #[inline]
686     fn rev(self) -> Rev<Self> {
687         Rev{iter: self}
688     }
689 }
690
691 /// A double-ended iterator yielding mutable references
692 pub trait MutableDoubleEndedIterator {
693     // FIXME: #5898: should be called `reverse`
694     /// Use an iterator to reverse a container in-place
695     fn reverse_(&mut self);
696 }
697
698 impl<'a, A, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T {
699     // FIXME: #5898: should be called `reverse`
700     /// Use an iterator to reverse a container in-place
701     fn reverse_(&mut self) {
702         loop {
703             match (self.next(), self.next_back()) {
704                 (Some(x), Some(y)) => mem::swap(x, y),
705                 _ => break
706             }
707         }
708     }
709 }
710
711
712 /// An object implementing random access indexing by `uint`
713 ///
714 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
715 pub trait RandomAccessIterator<A>: Iterator<A> {
716     /// Return the number of indexable elements. At most `std::uint::MAX`
717     /// elements are indexable, even if the iterator represents a longer range.
718     fn indexable(&self) -> uint;
719
720     /// Return an element at an index
721     fn idx(&self, index: uint) -> Option<A>;
722 }
723
724 /// An iterator that knows its exact length
725 ///
726 /// This trait is a helper for iterators like the vector iterator, so that
727 /// it can support double-ended enumeration.
728 ///
729 /// `Iterator::size_hint` *must* return the exact size of the iterator.
730 /// Note that the size must fit in `uint`.
731 pub trait ExactSize<A> : DoubleEndedIterator<A> {
732     /// Return the index of the last element satisfying the specified predicate
733     ///
734     /// If no element matches, None is returned.
735     #[inline]
736     fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> {
737         let (lower, upper) = self.size_hint();
738         assert!(upper == Some(lower));
739         let mut i = lower;
740         loop {
741             match self.next_back() {
742                 None => break,
743                 Some(x) => {
744                     i = match i.checked_sub(&1) {
745                         Some(x) => x,
746                         None => fail!("rposition: incorrect ExactSize")
747                     };
748                     if predicate(x) {
749                         return Some(i)
750                     }
751                 }
752             }
753         }
754         None
755     }
756 }
757
758 // All adaptors that preserve the size of the wrapped iterator are fine
759 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
760 impl<A, T: ExactSize<A>> ExactSize<(uint, A)> for Enumerate<T> {}
761 impl<'a, A, T: ExactSize<A>> ExactSize<A> for Inspect<'a, A, T> {}
762 impl<A, T: ExactSize<A>> ExactSize<A> for Rev<T> {}
763 impl<'a, A, B, T: ExactSize<A>> ExactSize<B> for Map<'a, A, B, T> {}
764 impl<A, B, T: ExactSize<A>, U: ExactSize<B>> ExactSize<(A, B)> for Zip<T, U> {}
765
766 /// An double-ended iterator with the direction inverted
767 #[deriving(Clone)]
768 pub struct Rev<T> {
769     priv iter: T
770 }
771
772 impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> {
773     #[inline]
774     fn next(&mut self) -> Option<A> { self.iter.next_back() }
775     #[inline]
776     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
777 }
778
779 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> {
780     #[inline]
781     fn next_back(&mut self) -> Option<A> { self.iter.next() }
782 }
783
784 impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
785     for Rev<T> {
786     #[inline]
787     fn indexable(&self) -> uint { self.iter.indexable() }
788     #[inline]
789     fn idx(&self, index: uint) -> Option<A> {
790         self.iter.idx(self.indexable() - index - 1)
791     }
792 }
793
794 /// A mutable reference to an iterator
795 pub struct ByRef<'a, T> {
796     priv iter: &'a mut T
797 }
798
799 impl<'a, A, T: Iterator<A>> Iterator<A> for ByRef<'a, T> {
800     #[inline]
801     fn next(&mut self) -> Option<A> { self.iter.next() }
802     #[inline]
803     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
804 }
805
806 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for ByRef<'a, T> {
807     #[inline]
808     fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
809 }
810
811 /// A trait for iterators over elements which can be added together
812 pub trait AdditiveIterator<A> {
813     /// Iterates over the entire iterator, summing up all the elements
814     ///
815     /// # Example
816     ///
817     /// ```rust
818     /// use std::iter::AdditiveIterator;
819     ///
820     /// let a = [1, 2, 3, 4, 5];
821     /// let mut it = a.iter().map(|&x| x);
822     /// assert!(it.sum() == 15);
823     /// ```
824     fn sum(&mut self) -> A;
825 }
826
827 impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
828     #[inline]
829     fn sum(&mut self) -> A {
830         let zero: A = Zero::zero();
831         self.fold(zero, |s, x| s + x)
832     }
833 }
834
835 /// A trait for iterators over elements whose elements can be multiplied
836 /// together.
837 pub trait MultiplicativeIterator<A> {
838     /// Iterates over the entire iterator, multiplying all the elements
839     ///
840     /// # Example
841     ///
842     /// ```rust
843     /// use std::iter::{count, MultiplicativeIterator};
844     ///
845     /// fn factorial(n: uint) -> uint {
846     ///     count(1u, 1).take_while(|&i| i <= n).product()
847     /// }
848     /// assert!(factorial(0) == 1);
849     /// assert!(factorial(1) == 1);
850     /// assert!(factorial(5) == 120);
851     /// ```
852     fn product(&mut self) -> A;
853 }
854
855 impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
856     #[inline]
857     fn product(&mut self) -> A {
858         let one: A = One::one();
859         self.fold(one, |p, x| p * x)
860     }
861 }
862
863 /// A trait for iterators over elements which can be compared to one another.
864 /// The type of each element must ascribe to the `Ord` trait.
865 pub trait OrdIterator<A> {
866     /// Consumes the entire iterator to return the maximum element.
867     ///
868     /// # Example
869     ///
870     /// ```rust
871     /// let a = [1, 2, 3, 4, 5];
872     /// assert!(a.iter().max().unwrap() == &5);
873     /// ```
874     fn max(&mut self) -> Option<A>;
875
876     /// Consumes the entire iterator to return the minimum element.
877     ///
878     /// # Example
879     ///
880     /// ```rust
881     /// let a = [1, 2, 3, 4, 5];
882     /// assert!(a.iter().min().unwrap() == &1);
883     /// ```
884     fn min(&mut self) -> Option<A>;
885
886     /// `min_max` finds the minimum and maximum elements in the iterator.
887     ///
888     /// The return type `MinMaxResult` is an enum of three variants:
889     /// - `NoElements` if the iterator is empty.
890     /// - `OneElement(x)` if the iterator has exactly one element.
891     /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two values are equal if and only if
892     /// there is more than one element in the iterator and all elements are equal.
893     ///
894     /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
895     /// and so faster than calling `min` and `max separately which does `2 * n` comparisons.
896     ///
897     /// # Example
898     ///
899     /// ```rust
900     /// use std::iter::{NoElements, OneElement, MinMax};
901     ///
902     /// let v: [int, ..0] = [];
903     /// assert_eq!(v.iter().min_max(), NoElements);
904     ///
905     /// let v = [1i];
906     /// assert!(v.iter().min_max() == OneElement(&1));
907     ///
908     /// let v = [1i, 2, 3, 4, 5];
909     /// assert!(v.iter().min_max() == MinMax(&1, &5));
910     ///
911     /// let v = [1i, 2, 3, 4, 5, 6];
912     /// assert!(v.iter().min_max() == MinMax(&1, &6));
913     ///
914     /// let v = [1i, 1, 1, 1];
915     /// assert!(v.iter().min_max() == MinMax(&1, &1));
916     /// ```
917     fn min_max(&mut self) -> MinMaxResult<A>;
918 }
919
920 impl<A: Ord, T: Iterator<A>> OrdIterator<A> for T {
921     #[inline]
922     fn max(&mut self) -> Option<A> {
923         self.fold(None, |max, x| {
924             match max {
925                 None    => Some(x),
926                 Some(y) => Some(cmp::max(x, y))
927             }
928         })
929     }
930
931     #[inline]
932     fn min(&mut self) -> Option<A> {
933         self.fold(None, |min, x| {
934             match min {
935                 None    => Some(x),
936                 Some(y) => Some(cmp::min(x, y))
937             }
938         })
939     }
940
941     fn min_max(&mut self) -> MinMaxResult<A> {
942         let (mut min, mut max) = match self.next() {
943             None => return NoElements,
944             Some(x) => {
945                 match self.next() {
946                     None => return OneElement(x),
947                     Some(y) => if x < y {(x, y)} else {(y,x)}
948                 }
949             }
950         };
951
952         loop {
953             // `first` and `second` are the two next elements we want to look at.
954             // We first compare `first` and `second` (#1). The smaller one is then compared to
955             // current mininum (#2). The larger one is compared to current maximum (#3). This
956             // way we do 3 comparisons for 2 elements.
957             let first = match self.next() {
958                 None => break,
959                 Some(x) => x
960             };
961             let second = match self.next() {
962                 None => {
963                     if first < min {
964                         min = first;
965                     } else if first > max {
966                         max = first;
967                     }
968                     break;
969                 }
970                 Some(x) => x
971             };
972             if first < second {
973                 if first < min {min = first;}
974                 if max < second {max = second;}
975             } else {
976                 if second < min {min = second;}
977                 if max < first {max = first;}
978             }
979         }
980
981         MinMax(min, max)
982     }
983 }
984
985 /// `MinMaxResult` is an enum returned by `min_max`. See `OrdIterator::min_max` for more detail.
986 #[deriving(Clone, Eq, Show)]
987 pub enum MinMaxResult<T> {
988     /// Empty iterator
989     NoElements,
990
991     /// Iterator with one element, so the minimum and maximum are the same
992     OneElement(T),
993
994     /// More than one element in the iterator, the first element is not larger than the second
995     MinMax(T, T)
996 }
997
998 impl<T: Clone> MinMaxResult<T> {
999     /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1000     /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1001     /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1002     /// performing this operation will make one clone of `x`.
1003     ///
1004     /// # Example
1005     ///
1006     /// ```rust
1007     /// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
1008     ///
1009     /// let r: MinMaxResult<int> = NoElements;
1010     /// assert_eq!(r.into_option(), None)
1011     ///
1012     /// let r = OneElement(1);
1013     /// assert_eq!(r.into_option(), Some((1,1)));
1014     ///
1015     /// let r = MinMax(1,2);
1016     /// assert_eq!(r.into_option(), Some((1,2)));
1017     /// ```
1018     pub fn into_option(self) -> Option<(T,T)> {
1019         match self {
1020             NoElements => None,
1021             OneElement(x) => Some((x.clone(), x)),
1022             MinMax(x, y) => Some((x, y))
1023         }
1024     }
1025 }
1026
1027 /// A trait for iterators that are cloneable.
1028 pub trait CloneableIterator {
1029     /// Repeats an iterator endlessly
1030     ///
1031     /// # Example
1032     ///
1033     /// ```rust
1034     /// use std::iter::{CloneableIterator, count};
1035     ///
1036     /// let a = count(1,1).take(1);
1037     /// let mut cy = a.cycle();
1038     /// assert_eq!(cy.next(), Some(1));
1039     /// assert_eq!(cy.next(), Some(1));
1040     /// ```
1041     fn cycle(self) -> Cycle<Self>;
1042 }
1043
1044 impl<A, T: Clone + Iterator<A>> CloneableIterator for T {
1045     #[inline]
1046     fn cycle(self) -> Cycle<T> {
1047         Cycle{orig: self.clone(), iter: self}
1048     }
1049 }
1050
1051 /// An iterator that repeats endlessly
1052 #[deriving(Clone)]
1053 pub struct Cycle<T> {
1054     priv orig: T,
1055     priv iter: T,
1056 }
1057
1058 impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
1059     #[inline]
1060     fn next(&mut self) -> Option<A> {
1061         match self.iter.next() {
1062             None => { self.iter = self.orig.clone(); self.iter.next() }
1063             y => y
1064         }
1065     }
1066
1067     #[inline]
1068     fn size_hint(&self) -> (uint, Option<uint>) {
1069         // the cycle iterator is either empty or infinite
1070         match self.orig.size_hint() {
1071             sz @ (0, Some(0)) => sz,
1072             (0, _) => (0, None),
1073             _ => (uint::MAX, None)
1074         }
1075     }
1076 }
1077
1078 impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
1079     #[inline]
1080     fn indexable(&self) -> uint {
1081         if self.orig.indexable() > 0 {
1082             uint::MAX
1083         } else {
1084             0
1085         }
1086     }
1087
1088     #[inline]
1089     fn idx(&self, index: uint) -> Option<A> {
1090         let liter = self.iter.indexable();
1091         let lorig = self.orig.indexable();
1092         if lorig == 0 {
1093             None
1094         } else if index < liter {
1095             self.iter.idx(index)
1096         } else {
1097             self.orig.idx((index - liter) % lorig)
1098         }
1099     }
1100 }
1101
1102 /// An iterator which strings two iterators together
1103 #[deriving(Clone)]
1104 pub struct Chain<T, U> {
1105     priv a: T,
1106     priv b: U,
1107     priv flag: bool
1108 }
1109
1110 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
1111     #[inline]
1112     fn next(&mut self) -> Option<A> {
1113         if self.flag {
1114             self.b.next()
1115         } else {
1116             match self.a.next() {
1117                 Some(x) => return Some(x),
1118                 _ => ()
1119             }
1120             self.flag = true;
1121             self.b.next()
1122         }
1123     }
1124
1125     #[inline]
1126     fn size_hint(&self) -> (uint, Option<uint>) {
1127         let (a_lower, a_upper) = self.a.size_hint();
1128         let (b_lower, b_upper) = self.b.size_hint();
1129
1130         let lower = a_lower.saturating_add(b_lower);
1131
1132         let upper = match (a_upper, b_upper) {
1133             (Some(x), Some(y)) => x.checked_add(&y),
1134             _ => None
1135         };
1136
1137         (lower, upper)
1138     }
1139 }
1140
1141 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1142 for Chain<T, U> {
1143     #[inline]
1144     fn next_back(&mut self) -> Option<A> {
1145         match self.b.next_back() {
1146             Some(x) => Some(x),
1147             None => self.a.next_back()
1148         }
1149     }
1150 }
1151
1152 impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
1153 for Chain<T, U> {
1154     #[inline]
1155     fn indexable(&self) -> uint {
1156         let (a, b) = (self.a.indexable(), self.b.indexable());
1157         a.saturating_add(b)
1158     }
1159
1160     #[inline]
1161     fn idx(&self, index: uint) -> Option<A> {
1162         let len = self.a.indexable();
1163         if index < len {
1164             self.a.idx(index)
1165         } else {
1166             self.b.idx(index - len)
1167         }
1168     }
1169 }
1170
1171 /// An iterator which iterates two other iterators simultaneously
1172 #[deriving(Clone)]
1173 pub struct Zip<T, U> {
1174     priv a: T,
1175     priv b: U
1176 }
1177
1178 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
1179     #[inline]
1180     fn next(&mut self) -> Option<(A, B)> {
1181         match self.a.next() {
1182             None => None,
1183             Some(x) => match self.b.next() {
1184                 None => None,
1185                 Some(y) => Some((x, y))
1186             }
1187         }
1188     }
1189
1190     #[inline]
1191     fn size_hint(&self) -> (uint, Option<uint>) {
1192         let (a_lower, a_upper) = self.a.size_hint();
1193         let (b_lower, b_upper) = self.b.size_hint();
1194
1195         let lower = cmp::min(a_lower, b_lower);
1196
1197         let upper = match (a_upper, b_upper) {
1198             (Some(x), Some(y)) => Some(cmp::min(x,y)),
1199             (Some(x), None) => Some(x),
1200             (None, Some(y)) => Some(y),
1201             (None, None) => None
1202         };
1203
1204         (lower, upper)
1205     }
1206 }
1207
1208 impl<A, B, T: ExactSize<A>, U: ExactSize<B>> DoubleEndedIterator<(A, B)>
1209 for Zip<T, U> {
1210     #[inline]
1211     fn next_back(&mut self) -> Option<(A, B)> {
1212         let (a_sz, a_upper) = self.a.size_hint();
1213         let (b_sz, b_upper) = self.b.size_hint();
1214         assert!(a_upper == Some(a_sz));
1215         assert!(b_upper == Some(b_sz));
1216         if a_sz < b_sz {
1217             for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1218         } else if a_sz > b_sz {
1219             for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1220         }
1221         let (a_sz, _) = self.a.size_hint();
1222         let (b_sz, _) = self.b.size_hint();
1223         assert!(a_sz == b_sz);
1224         match (self.a.next_back(), self.b.next_back()) {
1225             (Some(x), Some(y)) => Some((x, y)),
1226             _ => None
1227         }
1228     }
1229 }
1230
1231 impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
1232 RandomAccessIterator<(A, B)> for Zip<T, U> {
1233     #[inline]
1234     fn indexable(&self) -> uint {
1235         cmp::min(self.a.indexable(), self.b.indexable())
1236     }
1237
1238     #[inline]
1239     fn idx(&self, index: uint) -> Option<(A, B)> {
1240         match self.a.idx(index) {
1241             None => None,
1242             Some(x) => match self.b.idx(index) {
1243                 None => None,
1244                 Some(y) => Some((x, y))
1245             }
1246         }
1247     }
1248 }
1249
1250 /// An iterator which maps the values of `iter` with `f`
1251 pub struct Map<'a, A, B, T> {
1252     priv iter: T,
1253     priv f: 'a |A| -> B
1254 }
1255
1256 impl<'a, A, B, T> Map<'a, A, B, T> {
1257     #[inline]
1258     fn do_map(&self, elt: Option<A>) -> Option<B> {
1259         match elt {
1260             Some(a) => Some((self.f)(a)),
1261             _ => None
1262         }
1263     }
1264 }
1265
1266 impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> {
1267     #[inline]
1268     fn next(&mut self) -> Option<B> {
1269         let next = self.iter.next();
1270         self.do_map(next)
1271     }
1272
1273     #[inline]
1274     fn size_hint(&self) -> (uint, Option<uint>) {
1275         self.iter.size_hint()
1276     }
1277 }
1278
1279 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> {
1280     #[inline]
1281     fn next_back(&mut self) -> Option<B> {
1282         let next = self.iter.next_back();
1283         self.do_map(next)
1284     }
1285 }
1286
1287 impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> {
1288     #[inline]
1289     fn indexable(&self) -> uint {
1290         self.iter.indexable()
1291     }
1292
1293     #[inline]
1294     fn idx(&self, index: uint) -> Option<B> {
1295         self.do_map(self.iter.idx(index))
1296     }
1297 }
1298
1299 /// An iterator which filters the elements of `iter` with `predicate`
1300 pub struct Filter<'a, A, T> {
1301     priv iter: T,
1302     priv predicate: 'a |&A| -> bool
1303 }
1304
1305 impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> {
1306     #[inline]
1307     fn next(&mut self) -> Option<A> {
1308         for x in self.iter {
1309             if (self.predicate)(&x) {
1310                 return Some(x);
1311             } else {
1312                 continue
1313             }
1314         }
1315         None
1316     }
1317
1318     #[inline]
1319     fn size_hint(&self) -> (uint, Option<uint>) {
1320         let (_, upper) = self.iter.size_hint();
1321         (0, upper) // can't know a lower bound, due to the predicate
1322     }
1323 }
1324
1325 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> {
1326     #[inline]
1327     fn next_back(&mut self) -> Option<A> {
1328         loop {
1329             match self.iter.next_back() {
1330                 None => return None,
1331                 Some(x) => {
1332                     if (self.predicate)(&x) {
1333                         return Some(x);
1334                     } else {
1335                         continue
1336                     }
1337                 }
1338             }
1339         }
1340     }
1341 }
1342
1343 /// An iterator which uses `f` to both filter and map elements from `iter`
1344 pub struct FilterMap<'a, A, B, T> {
1345     priv iter: T,
1346     priv f: 'a |A| -> Option<B>
1347 }
1348
1349 impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> {
1350     #[inline]
1351     fn next(&mut self) -> Option<B> {
1352         for x in self.iter {
1353             match (self.f)(x) {
1354                 Some(y) => return Some(y),
1355                 None => ()
1356             }
1357         }
1358         None
1359     }
1360
1361     #[inline]
1362     fn size_hint(&self) -> (uint, Option<uint>) {
1363         let (_, upper) = self.iter.size_hint();
1364         (0, upper) // can't know a lower bound, due to the predicate
1365     }
1366 }
1367
1368 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1369 for FilterMap<'a, A, B, T> {
1370     #[inline]
1371     fn next_back(&mut self) -> Option<B> {
1372         loop {
1373             match self.iter.next_back() {
1374                 None => return None,
1375                 Some(x) => {
1376                     match (self.f)(x) {
1377                         Some(y) => return Some(y),
1378                         None => ()
1379                     }
1380                 }
1381             }
1382         }
1383     }
1384 }
1385
1386 /// An iterator which yields the current count and the element during iteration
1387 #[deriving(Clone)]
1388 pub struct Enumerate<T> {
1389     priv iter: T,
1390     priv count: uint
1391 }
1392
1393 impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1394     #[inline]
1395     fn next(&mut self) -> Option<(uint, A)> {
1396         match self.iter.next() {
1397             Some(a) => {
1398                 let ret = Some((self.count, a));
1399                 self.count += 1;
1400                 ret
1401             }
1402             _ => None
1403         }
1404     }
1405
1406     #[inline]
1407     fn size_hint(&self) -> (uint, Option<uint>) {
1408         self.iter.size_hint()
1409     }
1410 }
1411
1412 impl<A, T: ExactSize<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
1413     #[inline]
1414     fn next_back(&mut self) -> Option<(uint, A)> {
1415         match self.iter.next_back() {
1416             Some(a) => {
1417                 let (lower, upper) = self.iter.size_hint();
1418                 assert!(upper == Some(lower));
1419                 Some((self.count + lower, a))
1420             }
1421             _ => None
1422         }
1423     }
1424 }
1425
1426 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
1427     #[inline]
1428     fn indexable(&self) -> uint {
1429         self.iter.indexable()
1430     }
1431
1432     #[inline]
1433     fn idx(&self, index: uint) -> Option<(uint, A)> {
1434         match self.iter.idx(index) {
1435             Some(a) => Some((self.count + index, a)),
1436             _ => None,
1437         }
1438     }
1439 }
1440
1441 /// An iterator with a `peek()` that returns an optional reference to the next element.
1442 pub struct Peekable<A, T> {
1443     priv iter: T,
1444     priv peeked: Option<A>,
1445 }
1446
1447 impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
1448     #[inline]
1449     fn next(&mut self) -> Option<A> {
1450         if self.peeked.is_some() { self.peeked.take() }
1451         else { self.iter.next() }
1452     }
1453
1454     #[inline]
1455     fn size_hint(&self) -> (uint, Option<uint>) {
1456         let (lo, hi) = self.iter.size_hint();
1457         if self.peeked.is_some() {
1458             let lo = lo.saturating_add(1);
1459             let hi = match hi {
1460                 Some(x) => x.checked_add(&1),
1461                 None => None
1462             };
1463             (lo, hi)
1464         } else {
1465             (lo, hi)
1466         }
1467     }
1468 }
1469
1470 impl<'a, A, T: Iterator<A>> Peekable<A, T> {
1471     /// Return a reference to the next element of the iterator with out advancing it,
1472     /// or None if the iterator is exhausted.
1473     #[inline]
1474     pub fn peek(&'a mut self) -> Option<&'a A> {
1475         if self.peeked.is_none() {
1476             self.peeked = self.iter.next();
1477         }
1478         match self.peeked {
1479             Some(ref value) => Some(value),
1480             None => None,
1481         }
1482     }
1483
1484     /// Check whether peekable iterator is empty or not.
1485     #[inline]
1486     pub fn is_empty(&mut self) -> bool {
1487         self.peek().is_none()
1488     }
1489 }
1490
1491 /// An iterator which rejects elements while `predicate` is true
1492 pub struct SkipWhile<'a, A, T> {
1493     priv iter: T,
1494     priv flag: bool,
1495     priv predicate: 'a |&A| -> bool
1496 }
1497
1498 impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> {
1499     #[inline]
1500     fn next(&mut self) -> Option<A> {
1501         let mut next = self.iter.next();
1502         if self.flag {
1503             next
1504         } else {
1505             loop {
1506                 match next {
1507                     Some(x) => {
1508                         if (self.predicate)(&x) {
1509                             next = self.iter.next();
1510                             continue
1511                         } else {
1512                             self.flag = true;
1513                             return Some(x)
1514                         }
1515                     }
1516                     None => return None
1517                 }
1518             }
1519         }
1520     }
1521
1522     #[inline]
1523     fn size_hint(&self) -> (uint, Option<uint>) {
1524         let (_, upper) = self.iter.size_hint();
1525         (0, upper) // can't know a lower bound, due to the predicate
1526     }
1527 }
1528
1529 /// An iterator which only accepts elements while `predicate` is true
1530 pub struct TakeWhile<'a, A, T> {
1531     priv iter: T,
1532     priv flag: bool,
1533     priv predicate: 'a |&A| -> bool
1534 }
1535
1536 impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> {
1537     #[inline]
1538     fn next(&mut self) -> Option<A> {
1539         if self.flag {
1540             None
1541         } else {
1542             match self.iter.next() {
1543                 Some(x) => {
1544                     if (self.predicate)(&x) {
1545                         Some(x)
1546                     } else {
1547                         self.flag = true;
1548                         None
1549                     }
1550                 }
1551                 None => None
1552             }
1553         }
1554     }
1555
1556     #[inline]
1557     fn size_hint(&self) -> (uint, Option<uint>) {
1558         let (_, upper) = self.iter.size_hint();
1559         (0, upper) // can't know a lower bound, due to the predicate
1560     }
1561 }
1562
1563 /// An iterator which skips over `n` elements of `iter`.
1564 #[deriving(Clone)]
1565 pub struct Skip<T> {
1566     priv iter: T,
1567     priv n: uint
1568 }
1569
1570 impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
1571     #[inline]
1572     fn next(&mut self) -> Option<A> {
1573         let mut next = self.iter.next();
1574         if self.n == 0 {
1575             next
1576         } else {
1577             let mut n = self.n;
1578             while n > 0 {
1579                 n -= 1;
1580                 match next {
1581                     Some(_) => {
1582                         next = self.iter.next();
1583                         continue
1584                     }
1585                     None => {
1586                         self.n = 0;
1587                         return None
1588                     }
1589                 }
1590             }
1591             self.n = 0;
1592             next
1593         }
1594     }
1595
1596     #[inline]
1597     fn size_hint(&self) -> (uint, Option<uint>) {
1598         let (lower, upper) = self.iter.size_hint();
1599
1600         let lower = lower.saturating_sub(self.n);
1601
1602         let upper = match upper {
1603             Some(x) => Some(x.saturating_sub(self.n)),
1604             None => None
1605         };
1606
1607         (lower, upper)
1608     }
1609 }
1610
1611 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
1612     #[inline]
1613     fn indexable(&self) -> uint {
1614         self.iter.indexable().saturating_sub(self.n)
1615     }
1616
1617     #[inline]
1618     fn idx(&self, index: uint) -> Option<A> {
1619         if index >= self.indexable() {
1620             None
1621         } else {
1622             self.iter.idx(index + self.n)
1623         }
1624     }
1625 }
1626
1627 /// An iterator which only iterates over the first `n` iterations of `iter`.
1628 #[deriving(Clone)]
1629 pub struct Take<T> {
1630     priv iter: T,
1631     priv n: uint
1632 }
1633
1634 impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
1635     #[inline]
1636     fn next(&mut self) -> Option<A> {
1637         if self.n != 0 {
1638             self.n -= 1;
1639             self.iter.next()
1640         } else {
1641             None
1642         }
1643     }
1644
1645     #[inline]
1646     fn size_hint(&self) -> (uint, Option<uint>) {
1647         let (lower, upper) = self.iter.size_hint();
1648
1649         let lower = cmp::min(lower, self.n);
1650
1651         let upper = match upper {
1652             Some(x) if x < self.n => Some(x),
1653             _ => Some(self.n)
1654         };
1655
1656         (lower, upper)
1657     }
1658 }
1659
1660 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
1661     #[inline]
1662     fn indexable(&self) -> uint {
1663         cmp::min(self.iter.indexable(), self.n)
1664     }
1665
1666     #[inline]
1667     fn idx(&self, index: uint) -> Option<A> {
1668         if index >= self.n {
1669             None
1670         } else {
1671             self.iter.idx(index)
1672         }
1673     }
1674 }
1675
1676
1677 /// An iterator to maintain state while iterating another iterator
1678 pub struct Scan<'a, A, B, T, St> {
1679     priv iter: T,
1680     priv f: 'a |&mut St, A| -> Option<B>,
1681
1682     /// The current internal state to be passed to the closure next.
1683     state: St
1684 }
1685
1686 impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> {
1687     #[inline]
1688     fn next(&mut self) -> Option<B> {
1689         self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1690     }
1691
1692     #[inline]
1693     fn size_hint(&self) -> (uint, Option<uint>) {
1694         let (_, upper) = self.iter.size_hint();
1695         (0, upper) // can't know a lower bound, due to the scan function
1696     }
1697 }
1698
1699 /// An iterator that maps each element to an iterator,
1700 /// and yields the elements of the produced iterators
1701 ///
1702 pub struct FlatMap<'a, A, T, U> {
1703     priv iter: T,
1704     priv f: 'a |A| -> U,
1705     priv frontiter: Option<U>,
1706     priv backiter: Option<U>,
1707 }
1708
1709 impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> {
1710     #[inline]
1711     fn next(&mut self) -> Option<B> {
1712         loop {
1713             for inner in self.frontiter.mut_iter() {
1714                 for x in *inner {
1715                     return Some(x)
1716                 }
1717             }
1718             match self.iter.next().map(|x| (self.f)(x)) {
1719                 None => return self.backiter.as_mut().and_then(|it| it.next()),
1720                 next => self.frontiter = next,
1721             }
1722         }
1723     }
1724
1725     #[inline]
1726     fn size_hint(&self) -> (uint, Option<uint>) {
1727         let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1728         let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1729         let lo = flo.saturating_add(blo);
1730         match (self.iter.size_hint(), fhi, bhi) {
1731             ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(&b)),
1732             _ => (lo, None)
1733         }
1734     }
1735 }
1736
1737 impl<'a,
1738      A, T: DoubleEndedIterator<A>,
1739      B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
1740      for FlatMap<'a, A, T, U> {
1741     #[inline]
1742     fn next_back(&mut self) -> Option<B> {
1743         loop {
1744             for inner in self.backiter.mut_iter() {
1745                 match inner.next_back() {
1746                     None => (),
1747                     y => return y
1748                 }
1749             }
1750             match self.iter.next_back().map(|x| (self.f)(x)) {
1751                 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1752                 next => self.backiter = next,
1753             }
1754         }
1755     }
1756 }
1757
1758 /// An iterator that yields `None` forever after the underlying iterator
1759 /// yields `None` once.
1760 #[deriving(Clone, DeepClone)]
1761 pub struct Fuse<T> {
1762     priv iter: T,
1763     priv done: bool
1764 }
1765
1766 impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
1767     #[inline]
1768     fn next(&mut self) -> Option<A> {
1769         if self.done {
1770             None
1771         } else {
1772             match self.iter.next() {
1773                 None => {
1774                     self.done = true;
1775                     None
1776                 }
1777                 x => x
1778             }
1779         }
1780     }
1781
1782     #[inline]
1783     fn size_hint(&self) -> (uint, Option<uint>) {
1784         if self.done {
1785             (0, Some(0))
1786         } else {
1787             self.iter.size_hint()
1788         }
1789     }
1790 }
1791
1792 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
1793     #[inline]
1794     fn next_back(&mut self) -> Option<A> {
1795         if self.done {
1796             None
1797         } else {
1798             match self.iter.next_back() {
1799                 None => {
1800                     self.done = true;
1801                     None
1802                 }
1803                 x => x
1804             }
1805         }
1806     }
1807 }
1808
1809 // Allow RandomAccessIterators to be fused without affecting random-access behavior
1810 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
1811     #[inline]
1812     fn indexable(&self) -> uint {
1813         self.iter.indexable()
1814     }
1815
1816     #[inline]
1817     fn idx(&self, index: uint) -> Option<A> {
1818         self.iter.idx(index)
1819     }
1820 }
1821
1822 impl<T> Fuse<T> {
1823     /// Resets the fuse such that the next call to .next() or .next_back() will
1824     /// call the underlying iterator again even if it previously returned None.
1825     #[inline]
1826     pub fn reset_fuse(&mut self) {
1827         self.done = false
1828     }
1829 }
1830
1831 /// An iterator that calls a function with a reference to each
1832 /// element before yielding it.
1833 pub struct Inspect<'a, A, T> {
1834     priv iter: T,
1835     priv f: 'a |&A|
1836 }
1837
1838 impl<'a, A, T> Inspect<'a, A, T> {
1839     #[inline]
1840     fn do_inspect(&self, elt: Option<A>) -> Option<A> {
1841         match elt {
1842             Some(ref a) => (self.f)(a),
1843             None => ()
1844         }
1845
1846         elt
1847     }
1848 }
1849
1850 impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> {
1851     #[inline]
1852     fn next(&mut self) -> Option<A> {
1853         let next = self.iter.next();
1854         self.do_inspect(next)
1855     }
1856
1857     #[inline]
1858     fn size_hint(&self) -> (uint, Option<uint>) {
1859         self.iter.size_hint()
1860     }
1861 }
1862
1863 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1864 for Inspect<'a, A, T> {
1865     #[inline]
1866     fn next_back(&mut self) -> Option<A> {
1867         let next = self.iter.next_back();
1868         self.do_inspect(next)
1869     }
1870 }
1871
1872 impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
1873 for Inspect<'a, A, T> {
1874     #[inline]
1875     fn indexable(&self) -> uint {
1876         self.iter.indexable()
1877     }
1878
1879     #[inline]
1880     fn idx(&self, index: uint) -> Option<A> {
1881         self.do_inspect(self.iter.idx(index))
1882     }
1883 }
1884
1885 /// An iterator which just modifies the contained state throughout iteration.
1886 pub struct Unfold<'a, A, St> {
1887     priv f: 'a |&mut St| -> Option<A>,
1888     /// Internal state that will be yielded on the next iteration
1889     state: St
1890 }
1891
1892 impl<'a, A, St> Unfold<'a, A, St> {
1893     /// Creates a new iterator with the specified closure as the "iterator
1894     /// function" and an initial state to eventually pass to the iterator
1895     #[inline]
1896     pub fn new<'a>(initial_state: St, f: 'a |&mut St| -> Option<A>)
1897                -> Unfold<'a, A, St> {
1898         Unfold {
1899             f: f,
1900             state: initial_state
1901         }
1902     }
1903 }
1904
1905 impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> {
1906     #[inline]
1907     fn next(&mut self) -> Option<A> {
1908         (self.f)(&mut self.state)
1909     }
1910
1911     #[inline]
1912     fn size_hint(&self) -> (uint, Option<uint>) {
1913         // no possible known bounds at this point
1914         (0, None)
1915     }
1916 }
1917
1918 /// An infinite iterator starting at `start` and advancing by `step` with each
1919 /// iteration
1920 #[deriving(Clone)]
1921 pub struct Counter<A> {
1922     /// The current state the counter is at (next value to be yielded)
1923     priv state: A,
1924     /// The amount that this iterator is stepping by
1925     priv step: A
1926 }
1927
1928 /// Creates a new counter with the specified start/step
1929 #[inline]
1930 pub fn count<A>(start: A, step: A) -> Counter<A> {
1931     Counter{state: start, step: step}
1932 }
1933
1934 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
1935     #[inline]
1936     fn next(&mut self) -> Option<A> {
1937         let result = self.state.clone();
1938         self.state = self.state + self.step;
1939         Some(result)
1940     }
1941
1942     #[inline]
1943     fn size_hint(&self) -> (uint, Option<uint>) {
1944         (uint::MAX, None) // Too bad we can't specify an infinite lower bound
1945     }
1946 }
1947
1948 /// An iterator over the range [start, stop)
1949 #[deriving(Clone, DeepClone)]
1950 pub struct Range<A> {
1951     priv state: A,
1952     priv stop: A,
1953     priv one: A
1954 }
1955
1956 /// Return an iterator over the range [start, stop)
1957 #[inline]
1958 pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
1959     Range{state: start, stop: stop, one: One::one()}
1960 }
1961
1962 // FIXME: #10414: Unfortunate type bound
1963 impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for Range<A> {
1964     #[inline]
1965     fn next(&mut self) -> Option<A> {
1966         if self.state < self.stop {
1967             let result = self.state.clone();
1968             self.state = self.state + self.one;
1969             Some(result)
1970         } else {
1971             None
1972         }
1973     }
1974
1975     #[inline]
1976     fn size_hint(&self) -> (uint, Option<uint>) {
1977         // This first checks if the elements are representable as i64. If they aren't, try u64 (to
1978         // handle cases like range(huge, huger)). We don't use uint/int because the difference of
1979         // the i64/u64 might lie within their range.
1980         let bound = match self.state.to_i64() {
1981             Some(a) => {
1982                 let sz = self.stop.to_i64().map(|b| b.checked_sub(&a));
1983                 match sz {
1984                     Some(Some(bound)) => bound.to_uint(),
1985                     _ => None,
1986                 }
1987             },
1988             None => match self.state.to_u64() {
1989                 Some(a) => {
1990                     let sz = self.stop.to_u64().map(|b| b.checked_sub(&a));
1991                     match sz {
1992                         Some(Some(bound)) => bound.to_uint(),
1993                         _ => None
1994                     }
1995                 },
1996                 None => None
1997             }
1998         };
1999
2000         match bound {
2001             Some(b) => (b, Some(b)),
2002             // Standard fallback for unbounded/unrepresentable bounds
2003             None => (0, None)
2004         }
2005     }
2006 }
2007
2008 /// `Int` is required to ensure the range will be the same regardless of
2009 /// the direction it is consumed.
2010 impl<A: Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
2011     #[inline]
2012     fn next_back(&mut self) -> Option<A> {
2013         if self.stop > self.state {
2014             self.stop = self.stop - self.one;
2015             Some(self.stop.clone())
2016         } else {
2017             None
2018         }
2019     }
2020 }
2021
2022 /// An iterator over the range [start, stop]
2023 #[deriving(Clone, DeepClone)]
2024 pub struct RangeInclusive<A> {
2025     priv range: Range<A>,
2026     priv done: bool
2027 }
2028
2029 /// Return an iterator over the range [start, stop]
2030 #[inline]
2031 pub fn range_inclusive<A: Add<A, A> + Ord + Clone + One + ToPrimitive>(start: A, stop: A)
2032     -> RangeInclusive<A> {
2033     RangeInclusive{range: range(start, stop), done: false}
2034 }
2035
2036 impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for RangeInclusive<A> {
2037     #[inline]
2038     fn next(&mut self) -> Option<A> {
2039         match self.range.next() {
2040             Some(x) => Some(x),
2041             None => {
2042                 if !self.done && self.range.state == self.range.stop {
2043                     self.done = true;
2044                     Some(self.range.stop.clone())
2045                 } else {
2046                     None
2047                 }
2048             }
2049         }
2050     }
2051
2052     #[inline]
2053     fn size_hint(&self) -> (uint, Option<uint>) {
2054         let (lo, hi) = self.range.size_hint();
2055         if self.done {
2056             (lo, hi)
2057         } else {
2058             let lo = lo.saturating_add(1);
2059             let hi = match hi {
2060                 Some(x) => x.checked_add(&1),
2061                 None => None
2062             };
2063             (lo, hi)
2064         }
2065     }
2066 }
2067
2068 impl<A: Sub<A, A> + Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A>
2069     for RangeInclusive<A> {
2070     #[inline]
2071     fn next_back(&mut self) -> Option<A> {
2072         if self.range.stop > self.range.state {
2073             let result = self.range.stop.clone();
2074             self.range.stop = self.range.stop - self.range.one;
2075             Some(result)
2076         } else if !self.done && self.range.state == self.range.stop {
2077             self.done = true;
2078             Some(self.range.stop.clone())
2079         } else {
2080             None
2081         }
2082     }
2083 }
2084
2085 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2086 #[deriving(Clone, DeepClone)]
2087 pub struct RangeStep<A> {
2088     priv state: A,
2089     priv stop: A,
2090     priv step: A,
2091     priv rev: bool
2092 }
2093
2094 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2095 #[inline]
2096 pub fn range_step<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A, step: A) -> RangeStep<A> {
2097     let rev = step < Zero::zero();
2098     RangeStep{state: start, stop: stop, step: step, rev: rev}
2099 }
2100
2101 impl<A: CheckedAdd + Ord + Clone> Iterator<A> for RangeStep<A> {
2102     #[inline]
2103     fn next(&mut self) -> Option<A> {
2104         if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2105             let result = self.state.clone();
2106             match self.state.checked_add(&self.step) {
2107                 Some(x) => self.state = x,
2108                 None => self.state = self.stop.clone()
2109             }
2110             Some(result)
2111         } else {
2112             None
2113         }
2114     }
2115 }
2116
2117 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2118 #[deriving(Clone, DeepClone)]
2119 pub struct RangeStepInclusive<A> {
2120     priv state: A,
2121     priv stop: A,
2122     priv step: A,
2123     priv rev: bool,
2124     priv done: bool
2125 }
2126
2127 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2128 #[inline]
2129 pub fn range_step_inclusive<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A,
2130                                                                 step: A) -> RangeStepInclusive<A> {
2131     let rev = step < Zero::zero();
2132     RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
2133 }
2134
2135 impl<A: CheckedAdd + Ord + Clone + Eq> Iterator<A> for RangeStepInclusive<A> {
2136     #[inline]
2137     fn next(&mut self) -> Option<A> {
2138         if !self.done && ((self.rev && self.state >= self.stop) ||
2139                           (!self.rev && self.state <= self.stop)) {
2140             let result = self.state.clone();
2141             match self.state.checked_add(&self.step) {
2142                 Some(x) => self.state = x,
2143                 None => self.done = true
2144             }
2145             Some(result)
2146         } else {
2147             None
2148         }
2149     }
2150 }
2151
2152 /// An iterator that repeats an element endlessly
2153 #[deriving(Clone, DeepClone)]
2154 pub struct Repeat<A> {
2155     priv element: A
2156 }
2157
2158 impl<A: Clone> Repeat<A> {
2159     /// Create a new `Repeat` that endlessly repeats the element `elt`.
2160     #[inline]
2161     pub fn new(elt: A) -> Repeat<A> {
2162         Repeat{element: elt}
2163     }
2164 }
2165
2166 impl<A: Clone> Iterator<A> for Repeat<A> {
2167     #[inline]
2168     fn next(&mut self) -> Option<A> { self.idx(0) }
2169     #[inline]
2170     fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2171 }
2172
2173 impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
2174     #[inline]
2175     fn next_back(&mut self) -> Option<A> { self.idx(0) }
2176 }
2177
2178 impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
2179     #[inline]
2180     fn indexable(&self) -> uint { uint::MAX }
2181     #[inline]
2182     fn idx(&self, _: uint) -> Option<A> { Some(self.element.clone()) }
2183 }
2184
2185 /// Functions for lexicographical ordering of sequences.
2186 ///
2187 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2188 /// that the elements implement both `Eq` and `Ord`.
2189 ///
2190 /// If two sequences are equal up until the point where one ends,
2191 /// the shorter sequence compares less.
2192 pub mod order {
2193     use cmp;
2194     use cmp::{TotalEq, TotalOrd, Ord, Eq};
2195     use option::{Some, None};
2196     use super::Iterator;
2197
2198     /// Compare `a` and `b` for equality using `TotalOrd`
2199     pub fn equals<A: TotalEq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2200         loop {
2201             match (a.next(), b.next()) {
2202                 (None, None) => return true,
2203                 (None, _) | (_, None) => return false,
2204                 (Some(x), Some(y)) => if !x.equals(&y) { return false },
2205             }
2206         }
2207     }
2208
2209     /// Order `a` and `b` lexicographically using `TotalOrd`
2210     pub fn cmp<A: TotalOrd, T: Iterator<A>>(mut a: T, mut b: T) -> cmp::Ordering {
2211         loop {
2212             match (a.next(), b.next()) {
2213                 (None, None) => return cmp::Equal,
2214                 (None, _   ) => return cmp::Less,
2215                 (_   , None) => return cmp::Greater,
2216                 (Some(x), Some(y)) => match x.cmp(&y) {
2217                     cmp::Equal => (),
2218                     non_eq => return non_eq,
2219                 },
2220             }
2221         }
2222     }
2223
2224     /// Compare `a` and `b` for equality (Using partial equality, `Eq`)
2225     pub fn eq<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2226         loop {
2227             match (a.next(), b.next()) {
2228                 (None, None) => return true,
2229                 (None, _) | (_, None) => return false,
2230                 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2231             }
2232         }
2233     }
2234
2235     /// Compare `a` and `b` for nonequality (Using partial equality, `Eq`)
2236     pub fn ne<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2237         loop {
2238             match (a.next(), b.next()) {
2239                 (None, None) => return false,
2240                 (None, _) | (_, None) => return true,
2241                 (Some(x), Some(y)) => if x.ne(&y) { return true },
2242             }
2243         }
2244     }
2245
2246     /// Return `a` < `b` lexicographically (Using partial order, `Ord`)
2247     pub fn lt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2248         loop {
2249             match (a.next(), b.next()) {
2250                 (None, None) => return false,
2251                 (None, _   ) => return true,
2252                 (_   , None) => return false,
2253                 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2254             }
2255         }
2256     }
2257
2258     /// Return `a` <= `b` lexicographically (Using partial order, `Ord`)
2259     pub fn le<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2260         loop {
2261             match (a.next(), b.next()) {
2262                 (None, None) => return true,
2263                 (None, _   ) => return true,
2264                 (_   , None) => return false,
2265                 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2266             }
2267         }
2268     }
2269
2270     /// Return `a` > `b` lexicographically (Using partial order, `Ord`)
2271     pub fn gt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2272         loop {
2273             match (a.next(), b.next()) {
2274                 (None, None) => return false,
2275                 (None, _   ) => return false,
2276                 (_   , None) => return true,
2277                 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2278             }
2279         }
2280     }
2281
2282     /// Return `a` >= `b` lexicographically (Using partial order, `Ord`)
2283     pub fn ge<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
2284         loop {
2285             match (a.next(), b.next()) {
2286                 (None, None) => return true,
2287                 (None, _   ) => return false,
2288                 (_   , None) => return true,
2289                 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },
2290             }
2291         }
2292     }
2293
2294     #[test]
2295     fn test_lt() {
2296         use vec::ImmutableVector;
2297
2298         let empty: [int, ..0] = [];
2299         let xs = [1,2,3];
2300         let ys = [1,2,0];
2301
2302         assert!(!lt(xs.iter(), ys.iter()));
2303         assert!(!le(xs.iter(), ys.iter()));
2304         assert!( gt(xs.iter(), ys.iter()));
2305         assert!( ge(xs.iter(), ys.iter()));
2306
2307         assert!( lt(ys.iter(), xs.iter()));
2308         assert!( le(ys.iter(), xs.iter()));
2309         assert!(!gt(ys.iter(), xs.iter()));
2310         assert!(!ge(ys.iter(), xs.iter()));
2311
2312         assert!( lt(empty.iter(), xs.iter()));
2313         assert!( le(empty.iter(), xs.iter()));
2314         assert!(!gt(empty.iter(), xs.iter()));
2315         assert!(!ge(empty.iter(), xs.iter()));
2316
2317         // Sequence with NaN
2318         let u = [1.0, 2.0];
2319         let v = [0.0/0.0, 3.0];
2320
2321         assert!(!lt(u.iter(), v.iter()));
2322         assert!(!le(u.iter(), v.iter()));
2323         assert!(!gt(u.iter(), v.iter()));
2324         assert!(!ge(u.iter(), v.iter()));
2325
2326         let a = [0.0/0.0];
2327         let b = [1.0];
2328         let c = [2.0];
2329
2330         assert!(lt(a.iter(), b.iter()) == (a[0] <  b[0]));
2331         assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
2332         assert!(gt(a.iter(), b.iter()) == (a[0] >  b[0]));
2333         assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0]));
2334
2335         assert!(lt(c.iter(), b.iter()) == (c[0] <  b[0]));
2336         assert!(le(c.iter(), b.iter()) == (c[0] <= b[0]));
2337         assert!(gt(c.iter(), b.iter()) == (c[0] >  b[0]));
2338         assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0]));
2339     }
2340 }
2341
2342 #[cfg(test)]
2343 mod tests {
2344     use super::*;
2345     use prelude::*;
2346
2347     use cmp;
2348     use uint;
2349     use num;
2350
2351     #[test]
2352     fn test_counter_from_iter() {
2353         let mut it = count(0, 5).take(10);
2354         let xs: ~[int] = FromIterator::from_iterator(&mut it);
2355         assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
2356     }
2357
2358     #[test]
2359     fn test_iterator_chain() {
2360         let xs = [0u, 1, 2, 3, 4, 5];
2361         let ys = [30u, 40, 50, 60];
2362         let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
2363         let mut it = xs.iter().chain(ys.iter());
2364         let mut i = 0;
2365         for &x in it {
2366             assert_eq!(x, expected[i]);
2367             i += 1;
2368         }
2369         assert_eq!(i, expected.len());
2370
2371         let ys = count(30u, 10).take(4);
2372         let mut it = xs.iter().map(|&x| x).chain(ys);
2373         let mut i = 0;
2374         for x in it {
2375             assert_eq!(x, expected[i]);
2376             i += 1;
2377         }
2378         assert_eq!(i, expected.len());
2379     }
2380
2381     #[test]
2382     fn test_filter_map() {
2383         let mut it = count(0u, 1u).take(10)
2384             .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None });
2385         assert_eq!(it.collect::<~[uint]>(), ~[0*0, 2*2, 4*4, 6*6, 8*8]);
2386     }
2387
2388     #[test]
2389     fn test_iterator_enumerate() {
2390         let xs = [0u, 1, 2, 3, 4, 5];
2391         let mut it = xs.iter().enumerate();
2392         for (i, &x) in it {
2393             assert_eq!(i, x);
2394         }
2395     }
2396
2397     #[test]
2398     fn test_iterator_peekable() {
2399         let xs = ~[0u, 1, 2, 3, 4, 5];
2400         let mut it = xs.iter().map(|&x|x).peekable();
2401         assert_eq!(it.peek().unwrap(), &0);
2402         assert_eq!(it.next().unwrap(), 0);
2403         assert_eq!(it.next().unwrap(), 1);
2404         assert_eq!(it.next().unwrap(), 2);
2405         assert_eq!(it.peek().unwrap(), &3);
2406         assert_eq!(it.peek().unwrap(), &3);
2407         assert_eq!(it.next().unwrap(), 3);
2408         assert_eq!(it.next().unwrap(), 4);
2409         assert_eq!(it.peek().unwrap(), &5);
2410         assert_eq!(it.next().unwrap(), 5);
2411         assert!(it.peek().is_none());
2412         assert!(it.next().is_none());
2413     }
2414
2415     #[test]
2416     fn test_iterator_take_while() {
2417         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2418         let ys = [0u, 1, 2, 3, 5, 13];
2419         let mut it = xs.iter().take_while(|&x| *x < 15u);
2420         let mut i = 0;
2421         for &x in it {
2422             assert_eq!(x, ys[i]);
2423             i += 1;
2424         }
2425         assert_eq!(i, ys.len());
2426     }
2427
2428     #[test]
2429     fn test_iterator_skip_while() {
2430         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2431         let ys = [15, 16, 17, 19];
2432         let mut it = xs.iter().skip_while(|&x| *x < 15u);
2433         let mut i = 0;
2434         for &x in it {
2435             assert_eq!(x, ys[i]);
2436             i += 1;
2437         }
2438         assert_eq!(i, ys.len());
2439     }
2440
2441     #[test]
2442     fn test_iterator_skip() {
2443         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
2444         let ys = [13, 15, 16, 17, 19, 20, 30];
2445         let mut it = xs.iter().skip(5);
2446         let mut i = 0;
2447         for &x in it {
2448             assert_eq!(x, ys[i]);
2449             i += 1;
2450         }
2451         assert_eq!(i, ys.len());
2452     }
2453
2454     #[test]
2455     fn test_iterator_take() {
2456         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
2457         let ys = [0u, 1, 2, 3, 5];
2458         let mut it = xs.iter().take(5);
2459         let mut i = 0;
2460         for &x in it {
2461             assert_eq!(x, ys[i]);
2462             i += 1;
2463         }
2464         assert_eq!(i, ys.len());
2465     }
2466
2467     #[test]
2468     fn test_iterator_scan() {
2469         // test the type inference
2470         fn add(old: &mut int, new: &uint) -> Option<f64> {
2471             *old += *new as int;
2472             Some(*old as f64)
2473         }
2474         let xs = [0u, 1, 2, 3, 4];
2475         let ys = [0f64, 1.0, 3.0, 6.0, 10.0];
2476
2477         let mut it = xs.iter().scan(0, add);
2478         let mut i = 0;
2479         for x in it {
2480             assert_eq!(x, ys[i]);
2481             i += 1;
2482         }
2483         assert_eq!(i, ys.len());
2484     }
2485
2486     #[test]
2487     fn test_iterator_flat_map() {
2488         let xs = [0u, 3, 6];
2489         let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
2490         let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3));
2491         let mut i = 0;
2492         for x in it {
2493             assert_eq!(x, ys[i]);
2494             i += 1;
2495         }
2496         assert_eq!(i, ys.len());
2497     }
2498
2499     #[test]
2500     fn test_inspect() {
2501         let xs = [1u, 2, 3, 4];
2502         let mut n = 0;
2503
2504         let ys = xs.iter()
2505                    .map(|&x| x)
2506                    .inspect(|_| n += 1)
2507                    .collect::<~[uint]>();
2508
2509         assert_eq!(n, xs.len());
2510         assert_eq!(xs.as_slice(), ys.as_slice());
2511     }
2512
2513     #[test]
2514     fn test_unfoldr() {
2515         fn count(st: &mut uint) -> Option<uint> {
2516             if *st < 10 {
2517                 let ret = Some(*st);
2518                 *st += 1;
2519                 ret
2520             } else {
2521                 None
2522             }
2523         }
2524
2525         let mut it = Unfold::new(0, count);
2526         let mut i = 0;
2527         for counted in it {
2528             assert_eq!(counted, i);
2529             i += 1;
2530         }
2531         assert_eq!(i, 10);
2532     }
2533
2534     #[test]
2535     fn test_cycle() {
2536         let cycle_len = 3;
2537         let it = count(0u, 1).take(cycle_len).cycle();
2538         assert_eq!(it.size_hint(), (uint::MAX, None));
2539         for (i, x) in it.take(100).enumerate() {
2540             assert_eq!(i % cycle_len, x);
2541         }
2542
2543         let mut it = count(0u, 1).take(0).cycle();
2544         assert_eq!(it.size_hint(), (0, Some(0)));
2545         assert_eq!(it.next(), None);
2546     }
2547
2548     #[test]
2549     fn test_iterator_nth() {
2550         let v = &[0, 1, 2, 3, 4];
2551         for i in range(0u, v.len()) {
2552             assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
2553         }
2554     }
2555
2556     #[test]
2557     fn test_iterator_last() {
2558         let v = &[0, 1, 2, 3, 4];
2559         assert_eq!(v.iter().last().unwrap(), &4);
2560         assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
2561     }
2562
2563     #[test]
2564     fn test_iterator_len() {
2565         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2566         assert_eq!(v.slice(0, 4).iter().len(), 4);
2567         assert_eq!(v.slice(0, 10).iter().len(), 10);
2568         assert_eq!(v.slice(0, 0).iter().len(), 0);
2569     }
2570
2571     #[test]
2572     fn test_iterator_sum() {
2573         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2574         assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
2575         assert_eq!(v.iter().map(|&x| x).sum(), 55);
2576         assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
2577     }
2578
2579     #[test]
2580     fn test_iterator_product() {
2581         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2582         assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
2583         assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
2584         assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
2585     }
2586
2587     #[test]
2588     fn test_iterator_max() {
2589         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2590         assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
2591         assert_eq!(v.iter().map(|&x| x).max(), Some(10));
2592         assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
2593     }
2594
2595     #[test]
2596     fn test_iterator_min() {
2597         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2598         assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
2599         assert_eq!(v.iter().map(|&x| x).min(), Some(0));
2600         assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
2601     }
2602
2603     #[test]
2604     fn test_iterator_size_hint() {
2605         let c = count(0, 1);
2606         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
2607         let v2 = &[10, 11, 12];
2608         let vi = v.iter();
2609
2610         assert_eq!(c.size_hint(), (uint::MAX, None));
2611         assert_eq!(vi.size_hint(), (10, Some(10)));
2612
2613         assert_eq!(c.take(5).size_hint(), (5, Some(5)));
2614         assert_eq!(c.skip(5).size_hint().val1(), None);
2615         assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
2616         assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
2617         assert_eq!(c.enumerate().size_hint(), (uint::MAX, None));
2618         assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None));
2619         assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
2620         assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
2621         assert_eq!(c.filter(|_| false).size_hint(), (0, None));
2622         assert_eq!(c.map(|_| 0).size_hint(), (uint::MAX, None));
2623         assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
2624
2625         assert_eq!(vi.take(5).size_hint(), (5, Some(5)));
2626         assert_eq!(vi.take(12).size_hint(), (10, Some(10)));
2627         assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
2628         assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
2629         assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
2630         assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
2631         assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
2632         assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13)));
2633         assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
2634         assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
2635         assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
2636         assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10)));
2637         assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
2638     }
2639
2640     #[test]
2641     fn test_collect() {
2642         let a = ~[1, 2, 3, 4, 5];
2643         let b: ~[int] = a.iter().map(|&x| x).collect();
2644         assert_eq!(a, b);
2645     }
2646
2647     #[test]
2648     fn test_all() {
2649         let v: ~&[int] = ~&[1, 2, 3, 4, 5];
2650         assert!(v.iter().all(|&x| x < 10));
2651         assert!(!v.iter().all(|&x| x % 2 == 0));
2652         assert!(!v.iter().all(|&x| x > 100));
2653         assert!(v.slice(0, 0).iter().all(|_| fail!()));
2654     }
2655
2656     #[test]
2657     fn test_any() {
2658         let v: ~&[int] = ~&[1, 2, 3, 4, 5];
2659         assert!(v.iter().any(|&x| x < 10));
2660         assert!(v.iter().any(|&x| x % 2 == 0));
2661         assert!(!v.iter().any(|&x| x > 100));
2662         assert!(!v.slice(0, 0).iter().any(|_| fail!()));
2663     }
2664
2665     #[test]
2666     fn test_find() {
2667         let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
2668         assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
2669         assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
2670         assert!(v.iter().find(|x| *x % 12 == 0).is_none());
2671     }
2672
2673     #[test]
2674     fn test_position() {
2675         let v = &[1, 3, 9, 27, 103, 14, 11];
2676         assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
2677         assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
2678         assert!(v.iter().position(|x| *x % 12 == 0).is_none());
2679     }
2680
2681     #[test]
2682     fn test_count() {
2683         let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
2684         assert_eq!(xs.iter().count(|x| *x == 2), 3);
2685         assert_eq!(xs.iter().count(|x| *x == 5), 1);
2686         assert_eq!(xs.iter().count(|x| *x == 95), 0);
2687     }
2688
2689     #[test]
2690     fn test_max_by() {
2691         let xs: &[int] = &[-3, 0, 1, 5, -10];
2692         assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
2693     }
2694
2695     #[test]
2696     fn test_min_by() {
2697         let xs: &[int] = &[-3, 0, 1, 5, -10];
2698         assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
2699     }
2700
2701     #[test]
2702     fn test_by_ref() {
2703         let mut xs = range(0, 10);
2704         // sum the first five values
2705         let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
2706         assert_eq!(partial_sum, 10);
2707         assert_eq!(xs.next(), Some(5));
2708     }
2709
2710     #[test]
2711     fn test_rev() {
2712         let xs = [2, 4, 6, 8, 10, 12, 14, 16];
2713         let mut it = xs.iter();
2714         it.next();
2715         it.next();
2716         assert_eq!(it.rev().map(|&x| x).collect::<~[int]>(), ~[16, 14, 12, 10, 8, 6]);
2717     }
2718
2719     #[test]
2720     fn test_double_ended_map() {
2721         let xs = [1, 2, 3, 4, 5, 6];
2722         let mut it = xs.iter().map(|&x| x * -1);
2723         assert_eq!(it.next(), Some(-1));
2724         assert_eq!(it.next(), Some(-2));
2725         assert_eq!(it.next_back(), Some(-6));
2726         assert_eq!(it.next_back(), Some(-5));
2727         assert_eq!(it.next(), Some(-3));
2728         assert_eq!(it.next_back(), Some(-4));
2729         assert_eq!(it.next(), None);
2730     }
2731
2732     #[test]
2733     fn test_double_ended_enumerate() {
2734         let xs = [1, 2, 3, 4, 5, 6];
2735         let mut it = xs.iter().map(|&x| x).enumerate();
2736         assert_eq!(it.next(), Some((0, 1)));
2737         assert_eq!(it.next(), Some((1, 2)));
2738         assert_eq!(it.next_back(), Some((5, 6)));
2739         assert_eq!(it.next_back(), Some((4, 5)));
2740         assert_eq!(it.next_back(), Some((3, 4)));
2741         assert_eq!(it.next_back(), Some((2, 3)));
2742         assert_eq!(it.next(), None);
2743     }
2744
2745     #[test]
2746     fn test_double_ended_zip() {
2747         let xs = [1, 2, 3, 4, 5, 6];
2748         let ys = [1, 2, 3, 7];
2749         let a = xs.iter().map(|&x| x);
2750         let b = ys.iter().map(|&x| x);
2751         let mut it = a.zip(b);
2752         assert_eq!(it.next(), Some((1, 1)));
2753         assert_eq!(it.next(), Some((2, 2)));
2754         assert_eq!(it.next_back(), Some((4, 7)));
2755         assert_eq!(it.next_back(), Some((3, 3)));
2756         assert_eq!(it.next(), None);
2757     }
2758
2759     #[test]
2760     fn test_double_ended_filter() {
2761         let xs = [1, 2, 3, 4, 5, 6];
2762         let mut it = xs.iter().filter(|&x| *x & 1 == 0);
2763         assert_eq!(it.next_back().unwrap(), &6);
2764         assert_eq!(it.next_back().unwrap(), &4);
2765         assert_eq!(it.next().unwrap(), &2);
2766         assert_eq!(it.next_back(), None);
2767     }
2768
2769     #[test]
2770     fn test_double_ended_filter_map() {
2771         let xs = [1, 2, 3, 4, 5, 6];
2772         let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
2773         assert_eq!(it.next_back().unwrap(), 12);
2774         assert_eq!(it.next_back().unwrap(), 8);
2775         assert_eq!(it.next().unwrap(), 4);
2776         assert_eq!(it.next_back(), None);
2777     }
2778
2779     #[test]
2780     fn test_double_ended_chain() {
2781         let xs = [1, 2, 3, 4, 5];
2782         let ys = ~[7, 9, 11];
2783         let mut it = xs.iter().chain(ys.iter()).rev();
2784         assert_eq!(it.next().unwrap(), &11)
2785         assert_eq!(it.next().unwrap(), &9)
2786         assert_eq!(it.next_back().unwrap(), &1)
2787         assert_eq!(it.next_back().unwrap(), &2)
2788         assert_eq!(it.next_back().unwrap(), &3)
2789         assert_eq!(it.next_back().unwrap(), &4)
2790         assert_eq!(it.next_back().unwrap(), &5)
2791         assert_eq!(it.next_back().unwrap(), &7)
2792         assert_eq!(it.next_back(), None)
2793     }
2794
2795     #[test]
2796     fn test_rposition() {
2797         fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
2798         fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
2799         let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
2800
2801         assert_eq!(v.iter().rposition(f), Some(3u));
2802         assert!(v.iter().rposition(g).is_none());
2803     }
2804
2805     #[test]
2806     #[should_fail]
2807     fn test_rposition_fail() {
2808         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
2809         let mut i = 0;
2810         v.iter().rposition(|_elt| {
2811             if i == 2 {
2812                 fail!()
2813             }
2814             i += 1;
2815             false
2816         });
2817     }
2818
2819
2820     #[cfg(test)]
2821     fn check_randacc_iter<A: Eq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint)
2822     {
2823         let mut b = a.clone();
2824         assert_eq!(len, b.indexable());
2825         let mut n = 0;
2826         for (i, elt) in a.enumerate() {
2827             assert!(Some(elt) == b.idx(i));
2828             n += 1;
2829         }
2830         assert_eq!(n, len);
2831         assert!(None == b.idx(n));
2832         // call recursively to check after picking off an element
2833         if len > 0 {
2834             b.next();
2835             check_randacc_iter(b, len-1);
2836         }
2837     }
2838
2839
2840     #[test]
2841     fn test_double_ended_flat_map() {
2842         let u = [0u,1];
2843         let v = [5,6,7,8];
2844         let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
2845         assert_eq!(it.next_back().unwrap(), &8);
2846         assert_eq!(it.next().unwrap(),      &5);
2847         assert_eq!(it.next_back().unwrap(), &7);
2848         assert_eq!(it.next_back().unwrap(), &6);
2849         assert_eq!(it.next_back().unwrap(), &8);
2850         assert_eq!(it.next().unwrap(),      &6);
2851         assert_eq!(it.next_back().unwrap(), &7);
2852         assert_eq!(it.next_back(), None);
2853         assert_eq!(it.next(),      None);
2854         assert_eq!(it.next_back(), None);
2855     }
2856
2857     #[test]
2858     fn test_random_access_chain() {
2859         let xs = [1, 2, 3, 4, 5];
2860         let ys = ~[7, 9, 11];
2861         let mut it = xs.iter().chain(ys.iter());
2862         assert_eq!(it.idx(0).unwrap(), &1);
2863         assert_eq!(it.idx(5).unwrap(), &7);
2864         assert_eq!(it.idx(7).unwrap(), &11);
2865         assert!(it.idx(8).is_none());
2866
2867         it.next();
2868         it.next();
2869         it.next_back();
2870
2871         assert_eq!(it.idx(0).unwrap(), &3);
2872         assert_eq!(it.idx(4).unwrap(), &9);
2873         assert!(it.idx(6).is_none());
2874
2875         check_randacc_iter(it, xs.len() + ys.len() - 3);
2876     }
2877
2878     #[test]
2879     fn test_random_access_enumerate() {
2880         let xs = [1, 2, 3, 4, 5];
2881         check_randacc_iter(xs.iter().enumerate(), xs.len());
2882     }
2883
2884     #[test]
2885     fn test_random_access_rev() {
2886         let xs = [1, 2, 3, 4, 5];
2887         check_randacc_iter(xs.iter().rev(), xs.len());
2888         let mut it = xs.iter().rev();
2889         it.next();
2890         it.next_back();
2891         it.next();
2892         check_randacc_iter(it, xs.len() - 3);
2893     }
2894
2895     #[test]
2896     fn test_random_access_zip() {
2897         let xs = [1, 2, 3, 4, 5];
2898         let ys = [7, 9, 11];
2899         check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
2900     }
2901
2902     #[test]
2903     fn test_random_access_take() {
2904         let xs = [1, 2, 3, 4, 5];
2905         let empty: &[int] = [];
2906         check_randacc_iter(xs.iter().take(3), 3);
2907         check_randacc_iter(xs.iter().take(20), xs.len());
2908         check_randacc_iter(xs.iter().take(0), 0);
2909         check_randacc_iter(empty.iter().take(2), 0);
2910     }
2911
2912     #[test]
2913     fn test_random_access_skip() {
2914         let xs = [1, 2, 3, 4, 5];
2915         let empty: &[int] = [];
2916         check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
2917         check_randacc_iter(empty.iter().skip(2), 0);
2918     }
2919
2920     #[test]
2921     fn test_random_access_inspect() {
2922         let xs = [1, 2, 3, 4, 5];
2923
2924         // test .map and .inspect that don't implement Clone
2925         let it = xs.iter().inspect(|_| {});
2926         assert_eq!(xs.len(), it.indexable());
2927         for (i, elt) in xs.iter().enumerate() {
2928             assert_eq!(Some(elt), it.idx(i));
2929         }
2930
2931     }
2932
2933     #[test]
2934     fn test_random_access_map() {
2935         let xs = [1, 2, 3, 4, 5];
2936
2937         let it = xs.iter().map(|x| *x);
2938         assert_eq!(xs.len(), it.indexable());
2939         for (i, elt) in xs.iter().enumerate() {
2940             assert_eq!(Some(*elt), it.idx(i));
2941         }
2942     }
2943
2944     #[test]
2945     fn test_random_access_cycle() {
2946         let xs = [1, 2, 3, 4, 5];
2947         let empty: &[int] = [];
2948         check_randacc_iter(xs.iter().cycle().take(27), 27);
2949         check_randacc_iter(empty.iter().cycle(), 0);
2950     }
2951
2952     #[test]
2953     fn test_double_ended_range() {
2954         assert_eq!(range(11i, 14).rev().collect::<~[int]>(), ~[13i, 12, 11]);
2955         for _ in range(10i, 0).rev() {
2956             fail!("unreachable");
2957         }
2958
2959         assert_eq!(range(11u, 14).rev().collect::<~[uint]>(), ~[13u, 12, 11]);
2960         for _ in range(10u, 0).rev() {
2961             fail!("unreachable");
2962         }
2963     }
2964
2965     #[test]
2966     fn test_range() {
2967         /// A mock type to check Range when ToPrimitive returns None
2968         struct Foo;
2969
2970         impl ToPrimitive for Foo {
2971             fn to_i64(&self) -> Option<i64> { None }
2972             fn to_u64(&self) -> Option<u64> { None }
2973         }
2974
2975         impl Add<Foo, Foo> for Foo {
2976             fn add(&self, _: &Foo) -> Foo {
2977                 Foo
2978             }
2979         }
2980
2981         impl Eq for Foo {
2982             fn eq(&self, _: &Foo) -> bool {
2983                 true
2984             }
2985         }
2986
2987         impl Ord for Foo {
2988             fn lt(&self, _: &Foo) -> bool {
2989                 false
2990             }
2991         }
2992
2993         impl Clone for Foo {
2994             fn clone(&self) -> Foo {
2995                 Foo
2996             }
2997         }
2998
2999         impl Mul<Foo, Foo> for Foo {
3000             fn mul(&self, _: &Foo) -> Foo {
3001                 Foo
3002             }
3003         }
3004
3005         impl num::One for Foo {
3006             fn one() -> Foo {
3007                 Foo
3008             }
3009         }
3010
3011         assert_eq!(range(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4]);
3012         assert_eq!(range(-10i, -1).collect::<~[int]>(), ~[-10, -9, -8, -7, -6, -5, -4, -3, -2]);
3013         assert_eq!(range(0i, 5).rev().collect::<~[int]>(), ~[4, 3, 2, 1, 0]);
3014         assert_eq!(range(200, -5).collect::<~[int]>(), ~[]);
3015         assert_eq!(range(200, -5).rev().collect::<~[int]>(), ~[]);
3016         assert_eq!(range(200, 200).collect::<~[int]>(), ~[]);
3017         assert_eq!(range(200, 200).rev().collect::<~[int]>(), ~[]);
3018
3019         assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
3020         // this test is only meaningful when sizeof uint < sizeof u64
3021         assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1)));
3022         assert_eq!(range(-10i, -1).size_hint(), (9, Some(9)));
3023         assert_eq!(range(Foo, Foo).size_hint(), (0, None));
3024     }
3025
3026     #[test]
3027     fn test_range_inclusive() {
3028         assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4, 5]);
3029         assert_eq!(range_inclusive(0i, 5).rev().collect::<~[int]>(), ~[5i, 4, 3, 2, 1, 0]);
3030         assert_eq!(range_inclusive(200, -5).collect::<~[int]>(), ~[]);
3031         assert_eq!(range_inclusive(200, -5).rev().collect::<~[int]>(), ~[]);
3032         assert_eq!(range_inclusive(200, 200).collect::<~[int]>(), ~[200]);
3033         assert_eq!(range_inclusive(200, 200).rev().collect::<~[int]>(), ~[200]);
3034     }
3035
3036     #[test]
3037     fn test_range_step() {
3038         assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15]);
3039         assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5]);
3040         assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
3041         assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
3042         assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), ~[]);
3043         assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), ~[]);
3044     }
3045
3046     #[test]
3047     fn test_range_step_inclusive() {
3048         assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15, 20]);
3049         assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5, 0]);
3050         assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
3051         assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
3052         assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), ~[]);
3053         assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), ~[200]);
3054     }
3055
3056     #[test]
3057     fn test_reverse() {
3058         let mut ys = [1, 2, 3, 4, 5];
3059         ys.mut_iter().reverse_();
3060         assert!(ys == [5, 4, 3, 2, 1]);
3061     }
3062
3063     #[test]
3064     fn test_peekable_is_empty() {
3065         let a = [1];
3066         let mut it = a.iter().peekable();
3067         assert!( !it.is_empty() );
3068         it.next();
3069         assert!( it.is_empty() );
3070     }
3071
3072     #[test]
3073     fn test_min_max() {
3074         let v: [int, ..0] = [];
3075         assert_eq!(v.iter().min_max(), NoElements);
3076
3077         let v = [1i];
3078         assert!(v.iter().min_max() == OneElement(&1));
3079
3080         let v = [1i, 2, 3, 4, 5];
3081         assert!(v.iter().min_max() == MinMax(&1, &5));
3082
3083         let v = [1i, 2, 3, 4, 5, 6];
3084         assert!(v.iter().min_max() == MinMax(&1, &6));
3085
3086         let v = [1i, 1, 1, 1];
3087         assert!(v.iter().min_max() == MinMax(&1, &1));
3088     }
3089
3090     #[test]
3091     fn test_MinMaxResult() {
3092         let r: MinMaxResult<int> = NoElements;
3093         assert_eq!(r.into_option(), None)
3094
3095         let r = OneElement(1);
3096         assert_eq!(r.into_option(), Some((1,1)));
3097
3098         let r = MinMax(1,2);
3099         assert_eq!(r.into_option(), Some((1,2)));
3100     }
3101 }