]> git.lizzy.rs Git - rust.git/blob - src/libstd/iterator.rs
29f54bd10fba152bffdd3805c9d5aa6936400eb0
[rust.git] / src / libstd / iterator.rs
1 // Copyright 2013 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 /*! Composable external iterators
12
13 The `Iterator` trait defines an interface for objects which implement iteration as a state machine.
14
15 Algorithms like `zip` are provided as `Iterator` implementations which wrap other objects
16 implementing the `Iterator` trait.
17
18 */
19
20 use cmp;
21 use num::{Zero, One, Saturating};
22 use option::{Option, Some, None};
23 use ops::{Add, Mul};
24 use cmp::Ord;
25 use clone::Clone;
26 use uint;
27
28 /// Conversion from an `Iterator`
29 pub trait FromIterator<A, T: Iterator<A>> {
30     /// Build a container with elements from an external iterator.
31     fn from_iterator(iterator: &mut T) -> Self;
32 }
33
34 /// A type growable from an `Iterator` implementation
35 pub trait Extendable<A, T: Iterator<A>>: FromIterator<A, T> {
36     /// Extend a container with the elements yielded by an iterator
37     fn extend(&mut self, iterator: &mut T);
38 }
39
40 /// An interface for dealing with "external iterators". These types of iterators
41 /// can be resumed at any time as all state is stored internally as opposed to
42 /// being located on the call stack.
43 pub trait Iterator<A> {
44     /// Advance the iterator and return the next value. Return `None` when the end is reached.
45     fn next(&mut self) -> Option<A>;
46
47     /// Return a lower bound and upper bound on the remaining length of the iterator.
48     ///
49     /// The common use case for the estimate is pre-allocating space to store the results.
50     #[inline]
51     fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
52 }
53
54 /// A range iterator able to yield elements from both ends
55 pub trait DoubleEndedIterator<A>: Iterator<A> {
56     /// Yield an element from the end of the range, returning `None` if the range is empty.
57     fn next_back(&mut self) -> Option<A>;
58 }
59
60 /// An object implementing random access indexing by `uint`
61 ///
62 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
63 pub trait RandomAccessIterator<A>: Iterator<A> {
64     /// Return the number of indexable elements. At most `std::uint::max_value`
65     /// elements are indexable, even if the iterator represents a longer range.
66     fn indexable(&self) -> uint;
67
68     /// Return an element at an index
69     fn idx(&self, index: uint) -> Option<A>;
70 }
71
72 /// Iterator adaptors provided for every `DoubleEndedIterator` implementation.
73 ///
74 /// In the future these will be default methods instead of a utility trait.
75 pub trait DoubleEndedIteratorUtil {
76     /// Flip the direction of the iterator
77     fn invert(self) -> Invert<Self>;
78 }
79
80 /// Iterator adaptors provided for every `DoubleEndedIterator` implementation.
81 ///
82 /// In the future these will be default methods instead of a utility trait.
83 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIteratorUtil for T {
84     /// Flip the direction of the iterator
85     ///
86     /// The inverted iterator flips the ends on an iterator that can already
87     /// be iterated from the front and from the back.
88     ///
89     ///
90     /// If the iterator also implements RandomAccessIterator, the inverted
91     /// iterator is also random access, with the indices starting at the back
92     /// of the original iterator.
93     ///
94     /// Note: Random access with inverted indices still only applies to the first
95     /// `uint::max_value` elements of the original iterator.
96     #[inline]
97     fn invert(self) -> Invert<T> {
98         Invert{iter: self}
99     }
100 }
101
102 /// An double-ended iterator with the direction inverted
103 #[deriving(Clone)]
104 pub struct Invert<T> {
105     priv iter: T
106 }
107
108 impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Invert<T> {
109     #[inline]
110     fn next(&mut self) -> Option<A> { self.iter.next_back() }
111     #[inline]
112     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
113 }
114
115 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Invert<T> {
116     #[inline]
117     fn next_back(&mut self) -> Option<A> { self.iter.next() }
118 }
119
120 impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
121     for Invert<T> {
122     #[inline]
123     fn indexable(&self) -> uint { self.iter.indexable() }
124     #[inline]
125     fn idx(&self, index: uint) -> Option<A> {
126         self.iter.idx(self.indexable() - index - 1)
127     }
128 }
129
130 /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
131 /// implementations of the `Iterator` trait.
132 ///
133 /// In the future these will be default methods instead of a utility trait.
134 pub trait IteratorUtil<A> {
135     /// Chain this iterator with another, returning a new iterator which will
136     /// finish iterating over the current iterator, and then it will iterate
137     /// over the other specified iterator.
138     ///
139     /// # Example
140     ///
141     /// ~~~ {.rust}
142     /// let a = [0];
143     /// let b = [1];
144     /// let mut it = a.iter().chain_(b.iter());
145     /// assert_eq!(it.next().get(), &0);
146     /// assert_eq!(it.next().get(), &1);
147     /// assert!(it.next().is_none());
148     /// ~~~
149     fn chain_<U: Iterator<A>>(self, other: U) -> Chain<Self, U>;
150
151     /// Creates an iterator which iterates over both this and the specified
152     /// iterators simultaneously, yielding the two elements as pairs. When
153     /// either iterator returns None, all further invocations of next() will
154     /// return None.
155     ///
156     /// # Example
157     ///
158     /// ~~~ {.rust}
159     /// let a = [0];
160     /// let b = [1];
161     /// let mut it = a.iter().zip(b.iter());
162     /// assert_eq!(it.next().get(), (&0, &1));
163     /// assert!(it.next().is_none());
164     /// ~~~
165     fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U>;
166
167     // FIXME: #5898: should be called map
168     /// Creates a new iterator which will apply the specified function to each
169     /// element returned by the first, yielding the mapped element instead.
170     ///
171     /// # Example
172     ///
173     /// ~~~ {.rust}
174     /// let a = [1, 2];
175     /// let mut it = a.iter().transform(|&x| 2 * x);
176     /// assert_eq!(it.next().get(), 2);
177     /// assert_eq!(it.next().get(), 4);
178     /// assert!(it.next().is_none());
179     /// ~~~
180     fn transform<'r, B>(self, f: &'r fn(A) -> B) -> Map<'r, A, B, Self>;
181
182     /// Creates an iterator which applies the predicate to each element returned
183     /// by this iterator. Only elements which have the predicate evaluate to
184     /// `true` will be yielded.
185     ///
186     /// # Example
187     ///
188     /// ~~~ {.rust}
189     /// let a = [1, 2];
190     /// let mut it = a.iter().filter(|&x| *x > 1);
191     /// assert_eq!(it.next().get(), &2);
192     /// assert!(it.next().is_none());
193     /// ~~~
194     fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> Filter<'r, A, Self>;
195
196     /// Creates an iterator which both filters and maps elements.
197     /// If the specified function returns None, the element is skipped.
198     /// Otherwise the option is unwrapped and the new value is yielded.
199     ///
200     /// # Example
201     ///
202     /// ~~~ {.rust}
203     /// let a = [1, 2];
204     /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
205     /// assert_eq!(it.next().get(), 4);
206     /// assert!(it.next().is_none());
207     /// ~~~
208     fn filter_map<'r,  B>(self, f: &'r fn(A) -> Option<B>) -> FilterMap<'r, A, B, Self>;
209
210     /// Creates an iterator which yields a pair of the value returned by this
211     /// iterator plus the current index of iteration.
212     ///
213     /// # Example
214     ///
215     /// ~~~ {.rust}
216     /// let a = [100, 200];
217     /// let mut it = a.iter().enumerate();
218     /// assert_eq!(it.next().get(), (0, &100));
219     /// assert_eq!(it.next().get(), (1, &200));
220     /// assert!(it.next().is_none());
221     /// ~~~
222     fn enumerate(self) -> Enumerate<Self>;
223
224     /// Creates an iterator which invokes the predicate on elements until it
225     /// returns false. Once the predicate returns false, all further elements are
226     /// yielded.
227     ///
228     /// # Example
229     ///
230     /// ~~~ {.rust}
231     /// let a = [1, 2, 3, 2, 1];
232     /// let mut it = a.iter().skip_while(|&a| *a < 3);
233     /// assert_eq!(it.next().get(), &3);
234     /// assert_eq!(it.next().get(), &2);
235     /// assert_eq!(it.next().get(), &1);
236     /// assert!(it.next().is_none());
237     /// ~~~
238     fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhile<'r, A, Self>;
239
240     /// Creates an iterator which yields elements so long as the predicate
241     /// returns true. After the predicate returns false for the first time, no
242     /// further elements will be yielded.
243     ///
244     /// # Example
245     ///
246     /// ~~~ {.rust}
247     /// let a = [1, 2, 3, 2, 1];
248     /// let mut it = a.iter().take_while(|&a| *a < 3);
249     /// assert_eq!(it.next().get(), &1);
250     /// assert_eq!(it.next().get(), &2);
251     /// assert!(it.next().is_none());
252     /// ~~~
253     fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) -> TakeWhile<'r, A, Self>;
254
255     /// Creates an iterator which skips the first `n` elements of this iterator,
256     /// and then it yields all further items.
257     ///
258     /// # Example
259     ///
260     /// ~~~ {.rust}
261     /// let a = [1, 2, 3, 4, 5];
262     /// let mut it = a.iter().skip(3);
263     /// assert_eq!(it.next().get(), &4);
264     /// assert_eq!(it.next().get(), &5);
265     /// assert!(it.next().is_none());
266     /// ~~~
267     fn skip(self, n: uint) -> Skip<Self>;
268
269     // FIXME: #5898: should be called take
270     /// Creates an iterator which yields the first `n` elements of this
271     /// iterator, and then it will always return None.
272     ///
273     /// # Example
274     ///
275     /// ~~~ {.rust}
276     /// let a = [1, 2, 3, 4, 5];
277     /// let mut it = a.iter().take_(3);
278     /// assert_eq!(it.next().get(), &1);
279     /// assert_eq!(it.next().get(), &2);
280     /// assert_eq!(it.next().get(), &3);
281     /// assert!(it.next().is_none());
282     /// ~~~
283     fn take_(self, n: uint) -> Take<Self>;
284
285     /// Creates a new iterator which behaves in a similar fashion to foldl.
286     /// There is a state which is passed between each iteration and can be
287     /// mutated as necessary. The yielded values from the closure are yielded
288     /// from the Scan instance when not None.
289     ///
290     /// # Example
291     ///
292     /// ~~~ {.rust}
293     /// let a = [1, 2, 3, 4, 5];
294     /// let mut it = a.iter().scan(1, |fac, &x| {
295     ///   *fac = *fac * x;
296     ///   Some(*fac)
297     /// });
298     /// assert_eq!(it.next().get(), 1);
299     /// assert_eq!(it.next().get(), 2);
300     /// assert_eq!(it.next().get(), 6);
301     /// assert_eq!(it.next().get(), 24);
302     /// assert_eq!(it.next().get(), 120);
303     /// assert!(it.next().is_none());
304     /// ~~~
305     fn scan<'r, St, B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>)
306         -> Scan<'r, A, B, Self, St>;
307
308     /// Creates an iterator that maps each element to an iterator,
309     /// and yields the elements of the produced iterators
310     ///
311     /// # Example
312     ///
313     /// ~~~ {.rust}
314     /// let xs = [2u, 3];
315     /// let ys = [0u, 1, 0, 1, 2];
316     /// let mut it = xs.iter().flat_map_(|&x| count(0u, 1).take_(x));
317     /// // Check that `it` has the same elements as `ys`
318     /// let mut i = 0;
319     /// for x: uint in it {
320     ///     assert_eq!(x, ys[i]);
321     ///     i += 1;
322     /// }
323     /// ~~~
324     // FIXME: #5898: should be called `flat_map`
325     fn flat_map_<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U)
326         -> FlatMap<'r, A, Self, U>;
327
328     /// Creates an iterator that calls a function with a reference to each
329     /// element before yielding it. This is often useful for debugging an
330     /// iterator pipeline.
331     ///
332     /// # Example
333     ///
334     /// ~~~ {.rust}
335     ///let xs = [1u, 4, 2, 3, 8, 9, 6];
336     ///let sum = xs.iter()
337     ///            .transform(|&x| x)
338     ///            .peek_(|&x| debug!("filtering %u", x))
339     ///            .filter(|&x| x % 2 == 0)
340     ///            .peek_(|&x| debug!("%u made it through", x))
341     ///            .sum();
342     ///println(sum.to_str());
343     /// ~~~
344     // FIXME: #5898: should be called `peek`
345     fn peek_<'r>(self, f: &'r fn(&A)) -> Peek<'r, A, Self>;
346
347     /// An adaptation of an external iterator to the for-loop protocol of rust.
348     ///
349     /// # Example
350     ///
351     /// ~~~ {.rust}
352     /// use std::iterator::Counter;
353     ///
354     /// for i in count(0, 10) {
355     ///     printfln!("%d", i);
356     /// }
357     /// ~~~
358     fn advance(&mut self, f: &fn(A) -> bool) -> bool;
359
360     /// Loops through the entire iterator, collecting all of the elements into
361     /// a container implementing `FromIterator`.
362     ///
363     /// # Example
364     ///
365     /// ~~~ {.rust}
366     /// let a = [1, 2, 3, 4, 5];
367     /// let b: ~[int] = a.iter().transform(|&x| x).collect();
368     /// assert!(a == b);
369     /// ~~~
370     fn collect<B: FromIterator<A, Self>>(&mut self) -> B;
371
372     /// Loops through the entire iterator, collecting all of the elements into
373     /// a unique vector. This is simply collect() specialized for vectors.
374     ///
375     /// # Example
376     ///
377     /// ~~~ {.rust}
378     /// let a = [1, 2, 3, 4, 5];
379     /// let b: ~[int] = a.iter().transform(|&x| x).to_owned_vec();
380     /// assert!(a == b);
381     /// ~~~
382     fn to_owned_vec(&mut self) -> ~[A];
383
384     /// Loops through `n` iterations, returning the `n`th element of the
385     /// iterator.
386     ///
387     /// # Example
388     ///
389     /// ~~~ {.rust}
390     /// let a = [1, 2, 3, 4, 5];
391     /// let mut it = a.iter();
392     /// assert!(it.nth(2).get() == &3);
393     /// assert!(it.nth(2) == None);
394     /// ~~~
395     fn nth(&mut self, n: uint) -> Option<A>;
396
397     /// Loops through the entire iterator, returning the last element of the
398     /// iterator.
399     ///
400     /// # Example
401     ///
402     /// ~~~ {.rust}
403     /// let a = [1, 2, 3, 4, 5];
404     /// assert!(a.iter().last().get() == &5);
405     /// ~~~
406     // FIXME: #5898: should be called `last`
407     fn last_(&mut self) -> Option<A>;
408
409     /// Performs a fold operation over the entire iterator, returning the
410     /// eventual state at the end of the iteration.
411     ///
412     /// # Example
413     ///
414     /// ~~~ {.rust}
415     /// let a = [1, 2, 3, 4, 5];
416     /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
417     /// ~~~
418     fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B;
419
420     // FIXME: #5898: should be called len
421     /// Counts the number of elements in this iterator.
422     ///
423     /// # Example
424     ///
425     /// ~~~ {.rust}
426     /// let a = [1, 2, 3, 4, 5];
427     /// let mut it = a.iter();
428     /// assert!(it.len_() == 5);
429     /// assert!(it.len_() == 0);
430     /// ~~~
431     fn len_(&mut self) -> uint;
432
433     /// Tests whether the predicate holds true for all elements in the iterator.
434     ///
435     /// # Example
436     ///
437     /// ~~~ {.rust}
438     /// let a = [1, 2, 3, 4, 5];
439     /// assert!(a.iter().all(|&x| *x > 0));
440     /// assert!(!a.iter().all(|&x| *x > 2));
441     /// ~~~
442     fn all(&mut self, f: &fn(A) -> bool) -> bool;
443
444     /// Tests whether any element of an iterator satisfies the specified
445     /// predicate.
446     ///
447     /// # Example
448     ///
449     /// ~~~ {.rust}
450     /// let a = [1, 2, 3, 4, 5];
451     /// let mut it = a.iter();
452     /// assert!(it.any(|&x| *x == 3));
453     /// assert!(!it.any(|&x| *x == 3));
454     /// ~~~
455     fn any(&mut self, f: &fn(A) -> bool) -> bool;
456
457     /// Return the first element satisfying the specified predicate
458     fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A>;
459
460     /// Return the index of the first element satisfying the specified predicate
461     fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint>;
462
463     /// Count the number of elements satisfying the specified predicate
464     fn count(&mut self, predicate: &fn(A) -> bool) -> uint;
465
466     /// Return the element that gives the maximum value from the specfied function
467     ///
468     /// # Example
469     ///
470     /// ~~~ {.rust}
471     /// let xs = [-3, 0, 1, 5, -10];
472     /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
473     /// ~~~
474     fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>;
475
476     /// Return the element that gives the minimum value from the specfied function
477     ///
478     /// # Example
479     ///
480     /// ~~~ {.rust}
481     /// let xs = [-3, 0, 1, 5, -10];
482     /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
483     /// ~~~
484     fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>;
485 }
486
487 /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
488 /// implementations of the `Iterator` trait.
489 ///
490 /// In the future these will be default methods instead of a utility trait.
491 impl<A, T: Iterator<A>> IteratorUtil<A> for T {
492     #[inline]
493     fn chain_<U: Iterator<A>>(self, other: U) -> Chain<T, U> {
494         Chain{a: self, b: other, flag: false}
495     }
496
497     #[inline]
498     fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<T, U> {
499         Zip{a: self, b: other}
500     }
501
502     // FIXME: #5898: should be called map
503     #[inline]
504     fn transform<'r, B>(self, f: &'r fn(A) -> B) -> Map<'r, A, B, T> {
505         Map{iter: self, f: f}
506     }
507
508     #[inline]
509     fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> Filter<'r, A, T> {
510         Filter{iter: self, predicate: predicate}
511     }
512
513     #[inline]
514     fn filter_map<'r, B>(self, f: &'r fn(A) -> Option<B>) -> FilterMap<'r, A, B, T> {
515         FilterMap { iter: self, f: f }
516     }
517
518     #[inline]
519     fn enumerate(self) -> Enumerate<T> {
520         Enumerate{iter: self, count: 0}
521     }
522
523     #[inline]
524     fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhile<'r, A, T> {
525         SkipWhile{iter: self, flag: false, predicate: predicate}
526     }
527
528     #[inline]
529     fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) -> TakeWhile<'r, A, T> {
530         TakeWhile{iter: self, flag: false, predicate: predicate}
531     }
532
533     #[inline]
534     fn skip(self, n: uint) -> Skip<T> {
535         Skip{iter: self, n: n}
536     }
537
538     // FIXME: #5898: should be called take
539     #[inline]
540     fn take_(self, n: uint) -> Take<T> {
541         Take{iter: self, n: n}
542     }
543
544     #[inline]
545     fn scan<'r, St, B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>)
546         -> Scan<'r, A, B, T, St> {
547         Scan{iter: self, f: f, state: initial_state}
548     }
549
550     #[inline]
551     fn flat_map_<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U)
552         -> FlatMap<'r, A, T, U> {
553         FlatMap{iter: self, f: f, frontiter: None, backiter: None }
554     }
555
556     // FIXME: #5898: should be called `peek`
557     #[inline]
558     fn peek_<'r>(self, f: &'r fn(&A)) -> Peek<'r, A, T> {
559         Peek{iter: self, f: f}
560     }
561
562     /// A shim implementing the `for` loop iteration protocol for iterator objects
563     #[inline]
564     fn advance(&mut self, f: &fn(A) -> bool) -> bool {
565         loop {
566             match self.next() {
567                 Some(x) => {
568                     if !f(x) { return false; }
569                 }
570                 None => { return true; }
571             }
572         }
573     }
574
575     #[inline]
576     fn collect<B: FromIterator<A, T>>(&mut self) -> B {
577         FromIterator::from_iterator(self)
578     }
579
580     #[inline]
581     fn to_owned_vec(&mut self) -> ~[A] {
582         self.collect()
583     }
584
585     /// Return the `n`th item yielded by an iterator.
586     #[inline]
587     fn nth(&mut self, mut n: uint) -> Option<A> {
588         loop {
589             match self.next() {
590                 Some(x) => if n == 0 { return Some(x) },
591                 None => return None
592             }
593             n -= 1;
594         }
595     }
596
597     /// Return the last item yielded by an iterator.
598     #[inline]
599     fn last_(&mut self) -> Option<A> {
600         let mut last = None;
601         for x in *self { last = Some(x); }
602         last
603     }
604
605     /// Reduce an iterator to an accumulated value
606     #[inline]
607     fn fold<B>(&mut self, init: B, f: &fn(B, A) -> B) -> B {
608         let mut accum = init;
609         loop {
610             match self.next() {
611                 Some(x) => { accum = f(accum, x); }
612                 None    => { break; }
613             }
614         }
615         accum
616     }
617
618     /// Count the number of items yielded by an iterator
619     #[inline]
620     fn len_(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) }
621
622     #[inline]
623     fn all(&mut self, f: &fn(A) -> bool) -> bool {
624         for x in *self { if !f(x) { return false; } }
625         true
626     }
627
628     #[inline]
629     fn any(&mut self, f: &fn(A) -> bool) -> bool {
630         for x in *self { if f(x) { return true; } }
631         false
632     }
633
634     /// Return the first element satisfying the specified predicate
635     #[inline]
636     fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A> {
637         for x in *self {
638             if predicate(&x) { return Some(x) }
639         }
640         None
641     }
642
643     /// Return the index of the first element satisfying the specified predicate
644     #[inline]
645     fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
646         let mut i = 0;
647         for x in *self {
648             if predicate(x) {
649                 return Some(i);
650             }
651             i += 1;
652         }
653         None
654     }
655
656     #[inline]
657     fn count(&mut self, predicate: &fn(A) -> bool) -> uint {
658         let mut i = 0;
659         for x in *self {
660             if predicate(x) { i += 1 }
661         }
662         i
663     }
664
665     #[inline]
666     fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A> {
667         self.fold(None, |max: Option<(A, B)>, x| {
668             let x_val = f(&x);
669             match max {
670                 None             => Some((x, x_val)),
671                 Some((y, y_val)) => if x_val > y_val {
672                     Some((x, x_val))
673                 } else {
674                     Some((y, y_val))
675                 }
676             }
677         }).map_move(|(x, _)| x)
678     }
679
680     #[inline]
681     fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A> {
682         self.fold(None, |min: Option<(A, B)>, x| {
683             let x_val = f(&x);
684             match min {
685                 None             => Some((x, x_val)),
686                 Some((y, y_val)) => if x_val < y_val {
687                     Some((x, x_val))
688                 } else {
689                     Some((y, y_val))
690                 }
691             }
692         }).map_move(|(x, _)| x)
693     }
694 }
695
696 /// A trait for iterators over elements which can be added together
697 pub trait AdditiveIterator<A> {
698     /// Iterates over the entire iterator, summing up all the elements
699     ///
700     /// # Example
701     ///
702     /// ~~~ {.rust}
703     /// let a = [1, 2, 3, 4, 5];
704     /// let mut it = a.iter().transform(|&x| x);
705     /// assert!(it.sum() == 15);
706     /// ~~~
707     fn sum(&mut self) -> A;
708 }
709
710 impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
711     #[inline]
712     fn sum(&mut self) -> A { self.fold(Zero::zero::<A>(), |s, x| s + x) }
713 }
714
715 /// A trait for iterators over elements whose elements can be multiplied
716 /// together.
717 pub trait MultiplicativeIterator<A> {
718     /// Iterates over the entire iterator, multiplying all the elements
719     ///
720     /// # Example
721     ///
722     /// ~~~ {.rust}
723     /// use std::iterator::Counter;
724     ///
725     /// fn factorial(n: uint) -> uint {
726     ///     count(1u, 1).take_while(|&i| i <= n).product()
727     /// }
728     /// assert!(factorial(0) == 1);
729     /// assert!(factorial(1) == 1);
730     /// assert!(factorial(5) == 120);
731     /// ~~~
732     fn product(&mut self) -> A;
733 }
734
735 impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
736     #[inline]
737     fn product(&mut self) -> A { self.fold(One::one::<A>(), |p, x| p * x) }
738 }
739
740 /// A trait for iterators over elements which can be compared to one another.
741 /// The type of each element must ascribe to the `Ord` trait.
742 pub trait OrdIterator<A> {
743     /// Consumes the entire iterator to return the maximum element.
744     ///
745     /// # Example
746     ///
747     /// ~~~ {.rust}
748     /// let a = [1, 2, 3, 4, 5];
749     /// assert!(a.iter().max().get() == &5);
750     /// ~~~
751     fn max(&mut self) -> Option<A>;
752
753     /// Consumes the entire iterator to return the minimum element.
754     ///
755     /// # Example
756     ///
757     /// ~~~ {.rust}
758     /// let a = [1, 2, 3, 4, 5];
759     /// assert!(a.iter().min().get() == &1);
760     /// ~~~
761     fn min(&mut self) -> Option<A>;
762 }
763
764 impl<A: Ord, T: Iterator<A>> OrdIterator<A> for T {
765     #[inline]
766     fn max(&mut self) -> Option<A> {
767         self.fold(None, |max, x| {
768             match max {
769                 None    => Some(x),
770                 Some(y) => Some(cmp::max(x, y))
771             }
772         })
773     }
774
775     #[inline]
776     fn min(&mut self) -> Option<A> {
777         self.fold(None, |min, x| {
778             match min {
779                 None    => Some(x),
780                 Some(y) => Some(cmp::min(x, y))
781             }
782         })
783     }
784 }
785
786 /// A trait for iterators that are clonable.
787 pub trait ClonableIterator {
788     /// Repeats an iterator endlessly
789     ///
790     /// # Example
791     ///
792     /// ~~~ {.rust}
793     /// let a = count(1,1).take_(1);
794     /// let mut cy = a.cycle();
795     /// assert_eq!(cy.next(), Some(1));
796     /// assert_eq!(cy.next(), Some(1));
797     /// ~~~
798     fn cycle(self) -> Cycle<Self>;
799 }
800
801 impl<A, T: Clone + Iterator<A>> ClonableIterator for T {
802     #[inline]
803     fn cycle(self) -> Cycle<T> {
804         Cycle{orig: self.clone(), iter: self}
805     }
806 }
807
808 /// An iterator that repeats endlessly
809 #[deriving(Clone)]
810 pub struct Cycle<T> {
811     priv orig: T,
812     priv iter: T,
813 }
814
815 impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
816     #[inline]
817     fn next(&mut self) -> Option<A> {
818         match self.iter.next() {
819             None => { self.iter = self.orig.clone(); self.iter.next() }
820             y => y
821         }
822     }
823
824     #[inline]
825     fn size_hint(&self) -> (uint, Option<uint>) {
826         // the cycle iterator is either empty or infinite
827         match self.orig.size_hint() {
828             sz @ (0, Some(0)) => sz,
829             (0, _) => (0, None),
830             _ => (uint::max_value, None)
831         }
832     }
833 }
834
835 impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
836     #[inline]
837     fn indexable(&self) -> uint {
838         if self.orig.indexable() > 0 {
839             uint::max_value
840         } else {
841             0
842         }
843     }
844
845     #[inline]
846     fn idx(&self, index: uint) -> Option<A> {
847         let liter = self.iter.indexable();
848         let lorig = self.orig.indexable();
849         if lorig == 0 {
850             None
851         } else if index < liter {
852             self.iter.idx(index)
853         } else {
854             self.orig.idx((index - liter) % lorig)
855         }
856     }
857 }
858
859 /// An iterator which strings two iterators together
860 #[deriving(Clone)]
861 pub struct Chain<T, U> {
862     priv a: T,
863     priv b: U,
864     priv flag: bool
865 }
866
867 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
868     #[inline]
869     fn next(&mut self) -> Option<A> {
870         if self.flag {
871             self.b.next()
872         } else {
873             match self.a.next() {
874                 Some(x) => return Some(x),
875                 _ => ()
876             }
877             self.flag = true;
878             self.b.next()
879         }
880     }
881
882     #[inline]
883     fn size_hint(&self) -> (uint, Option<uint>) {
884         let (a_lower, a_upper) = self.a.size_hint();
885         let (b_lower, b_upper) = self.b.size_hint();
886
887         let lower = a_lower.saturating_add(b_lower);
888
889         let upper = match (a_upper, b_upper) {
890             (Some(x), Some(y)) => Some(x.saturating_add(y)),
891             _ => None
892         };
893
894         (lower, upper)
895     }
896 }
897
898 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
899 for Chain<T, U> {
900     #[inline]
901     fn next_back(&mut self) -> Option<A> {
902         match self.b.next_back() {
903             Some(x) => Some(x),
904             None => self.a.next_back()
905         }
906     }
907 }
908
909 impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
910 for Chain<T, U> {
911     #[inline]
912     fn indexable(&self) -> uint {
913         let (a, b) = (self.a.indexable(), self.b.indexable());
914         a.saturating_add(b)
915     }
916
917     #[inline]
918     fn idx(&self, index: uint) -> Option<A> {
919         let len = self.a.indexable();
920         if index < len {
921             self.a.idx(index)
922         } else {
923             self.b.idx(index - len)
924         }
925     }
926 }
927
928 /// An iterator which iterates two other iterators simultaneously
929 #[deriving(Clone)]
930 pub struct Zip<T, U> {
931     priv a: T,
932     priv b: U
933 }
934
935 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
936     #[inline]
937     fn next(&mut self) -> Option<(A, B)> {
938         match (self.a.next(), self.b.next()) {
939             (Some(x), Some(y)) => Some((x, y)),
940             _ => None
941         }
942     }
943
944     #[inline]
945     fn size_hint(&self) -> (uint, Option<uint>) {
946         let (a_lower, a_upper) = self.a.size_hint();
947         let (b_lower, b_upper) = self.b.size_hint();
948
949         let lower = cmp::min(a_lower, b_lower);
950
951         let upper = match (a_upper, b_upper) {
952             (Some(x), Some(y)) => Some(cmp::min(x,y)),
953             (Some(x), None) => Some(x),
954             (None, Some(y)) => Some(y),
955             (None, None) => None
956         };
957
958         (lower, upper)
959     }
960 }
961
962 impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
963 RandomAccessIterator<(A, B)> for Zip<T, U> {
964     #[inline]
965     fn indexable(&self) -> uint {
966         cmp::min(self.a.indexable(), self.b.indexable())
967     }
968
969     #[inline]
970     fn idx(&self, index: uint) -> Option<(A, B)> {
971         match (self.a.idx(index), self.b.idx(index)) {
972             (Some(x), Some(y)) => Some((x, y)),
973             _ => None
974         }
975     }
976 }
977
978 /// An iterator which maps the values of `iter` with `f`
979 pub struct Map<'self, A, B, T> {
980     priv iter: T,
981     priv f: &'self fn(A) -> B
982 }
983
984 impl<'self, A, B, T> Map<'self, A, B, T> {
985     #[inline]
986     fn do_map(&self, elt: Option<A>) -> Option<B> {
987         match elt {
988             Some(a) => Some((self.f)(a)),
989             _ => None
990         }
991     }
992 }
993
994 impl<'self, A, B, T: Iterator<A>> Iterator<B> for Map<'self, A, B, T> {
995     #[inline]
996     fn next(&mut self) -> Option<B> {
997         let next = self.iter.next();
998         self.do_map(next)
999     }
1000
1001     #[inline]
1002     fn size_hint(&self) -> (uint, Option<uint>) {
1003         self.iter.size_hint()
1004     }
1005 }
1006
1007 impl<'self, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1008 for Map<'self, A, B, T> {
1009     #[inline]
1010     fn next_back(&mut self) -> Option<B> {
1011         let next = self.iter.next_back();
1012         self.do_map(next)
1013     }
1014 }
1015
1016 impl<'self, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B>
1017 for Map<'self, A, B, T> {
1018     #[inline]
1019     fn indexable(&self) -> uint {
1020         self.iter.indexable()
1021     }
1022
1023     #[inline]
1024     fn idx(&self, index: uint) -> Option<B> {
1025         self.do_map(self.iter.idx(index))
1026     }
1027 }
1028
1029 /// An iterator which filters the elements of `iter` with `predicate`
1030 pub struct Filter<'self, A, T> {
1031     priv iter: T,
1032     priv predicate: &'self fn(&A) -> bool
1033 }
1034
1035 impl<'self, A, T: Iterator<A>> Iterator<A> for Filter<'self, A, T> {
1036     #[inline]
1037     fn next(&mut self) -> Option<A> {
1038         for x in self.iter {
1039             if (self.predicate)(&x) {
1040                 return Some(x);
1041             } else {
1042                 loop
1043             }
1044         }
1045         None
1046     }
1047
1048     #[inline]
1049     fn size_hint(&self) -> (uint, Option<uint>) {
1050         let (_, upper) = self.iter.size_hint();
1051         (0, upper) // can't know a lower bound, due to the predicate
1052     }
1053 }
1054
1055 impl<'self, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'self, A, T> {
1056     #[inline]
1057     fn next_back(&mut self) -> Option<A> {
1058         loop {
1059             match self.iter.next_back() {
1060                 None => return None,
1061                 Some(x) => {
1062                     if (self.predicate)(&x) {
1063                         return Some(x);
1064                     } else {
1065                         loop
1066                     }
1067                 }
1068             }
1069         }
1070     }
1071 }
1072
1073 /// An iterator which uses `f` to both filter and map elements from `iter`
1074 pub struct FilterMap<'self, A, B, T> {
1075     priv iter: T,
1076     priv f: &'self fn(A) -> Option<B>
1077 }
1078
1079 impl<'self, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'self, A, B, T> {
1080     #[inline]
1081     fn next(&mut self) -> Option<B> {
1082         for x in self.iter {
1083             match (self.f)(x) {
1084                 Some(y) => return Some(y),
1085                 None => ()
1086             }
1087         }
1088         None
1089     }
1090
1091     #[inline]
1092     fn size_hint(&self) -> (uint, Option<uint>) {
1093         let (_, upper) = self.iter.size_hint();
1094         (0, upper) // can't know a lower bound, due to the predicate
1095     }
1096 }
1097
1098 impl<'self, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1099 for FilterMap<'self, A, B, T> {
1100     #[inline]
1101     fn next_back(&mut self) -> Option<B> {
1102         loop {
1103             match self.iter.next_back() {
1104                 None => return None,
1105                 Some(x) => {
1106                     match (self.f)(x) {
1107                         Some(y) => return Some(y),
1108                         None => ()
1109                     }
1110                 }
1111             }
1112         }
1113     }
1114 }
1115
1116 /// An iterator which yields the current count and the element during iteration
1117 #[deriving(Clone)]
1118 pub struct Enumerate<T> {
1119     priv iter: T,
1120     priv count: uint
1121 }
1122
1123 impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1124     #[inline]
1125     fn next(&mut self) -> Option<(uint, A)> {
1126         match self.iter.next() {
1127             Some(a) => {
1128                 let ret = Some((self.count, a));
1129                 self.count += 1;
1130                 ret
1131             }
1132             _ => None
1133         }
1134     }
1135
1136     #[inline]
1137     fn size_hint(&self) -> (uint, Option<uint>) {
1138         self.iter.size_hint()
1139     }
1140 }
1141
1142 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
1143     #[inline]
1144     fn indexable(&self) -> uint {
1145         self.iter.indexable()
1146     }
1147
1148     #[inline]
1149     fn idx(&self, index: uint) -> Option<(uint, A)> {
1150         match self.iter.idx(index) {
1151             Some(a) => Some((self.count + index, a)),
1152             _ => None,
1153         }
1154     }
1155 }
1156
1157 /// An iterator which rejects elements while `predicate` is true
1158 pub struct SkipWhile<'self, A, T> {
1159     priv iter: T,
1160     priv flag: bool,
1161     priv predicate: &'self fn(&A) -> bool
1162 }
1163
1164 impl<'self, A, T: Iterator<A>> Iterator<A> for SkipWhile<'self, A, T> {
1165     #[inline]
1166     fn next(&mut self) -> Option<A> {
1167         let mut next = self.iter.next();
1168         if self.flag {
1169             next
1170         } else {
1171             loop {
1172                 match next {
1173                     Some(x) => {
1174                         if (self.predicate)(&x) {
1175                             next = self.iter.next();
1176                             loop
1177                         } else {
1178                             self.flag = true;
1179                             return Some(x)
1180                         }
1181                     }
1182                     None => return None
1183                 }
1184             }
1185         }
1186     }
1187
1188     #[inline]
1189     fn size_hint(&self) -> (uint, Option<uint>) {
1190         let (_, upper) = self.iter.size_hint();
1191         (0, upper) // can't know a lower bound, due to the predicate
1192     }
1193 }
1194
1195 /// An iterator which only accepts elements while `predicate` is true
1196 pub struct TakeWhile<'self, A, T> {
1197     priv iter: T,
1198     priv flag: bool,
1199     priv predicate: &'self fn(&A) -> bool
1200 }
1201
1202 impl<'self, A, T: Iterator<A>> Iterator<A> for TakeWhile<'self, A, T> {
1203     #[inline]
1204     fn next(&mut self) -> Option<A> {
1205         if self.flag {
1206             None
1207         } else {
1208             match self.iter.next() {
1209                 Some(x) => {
1210                     if (self.predicate)(&x) {
1211                         Some(x)
1212                     } else {
1213                         self.flag = true;
1214                         None
1215                     }
1216                 }
1217                 None => None
1218             }
1219         }
1220     }
1221
1222     #[inline]
1223     fn size_hint(&self) -> (uint, Option<uint>) {
1224         let (_, upper) = self.iter.size_hint();
1225         (0, upper) // can't know a lower bound, due to the predicate
1226     }
1227 }
1228
1229 /// An iterator which skips over `n` elements of `iter`.
1230 #[deriving(Clone)]
1231 pub struct Skip<T> {
1232     priv iter: T,
1233     priv n: uint
1234 }
1235
1236 impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
1237     #[inline]
1238     fn next(&mut self) -> Option<A> {
1239         let mut next = self.iter.next();
1240         if self.n == 0 {
1241             next
1242         } else {
1243             let mut n = self.n;
1244             while n > 0 {
1245                 n -= 1;
1246                 match next {
1247                     Some(_) => {
1248                         next = self.iter.next();
1249                         loop
1250                     }
1251                     None => {
1252                         self.n = 0;
1253                         return None
1254                     }
1255                 }
1256             }
1257             self.n = 0;
1258             next
1259         }
1260     }
1261
1262     #[inline]
1263     fn size_hint(&self) -> (uint, Option<uint>) {
1264         let (lower, upper) = self.iter.size_hint();
1265
1266         let lower = lower.saturating_sub(self.n);
1267
1268         let upper = match upper {
1269             Some(x) => Some(x.saturating_sub(self.n)),
1270             None => None
1271         };
1272
1273         (lower, upper)
1274     }
1275 }
1276
1277 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
1278     #[inline]
1279     fn indexable(&self) -> uint {
1280         self.iter.indexable().saturating_sub(self.n)
1281     }
1282
1283     #[inline]
1284     fn idx(&self, index: uint) -> Option<A> {
1285         if index >= self.indexable() {
1286             None
1287         } else {
1288             self.iter.idx(index + self.n)
1289         }
1290     }
1291 }
1292
1293 /// An iterator which only iterates over the first `n` iterations of `iter`.
1294 #[deriving(Clone)]
1295 pub struct Take<T> {
1296     priv iter: T,
1297     priv n: uint
1298 }
1299
1300 impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
1301     #[inline]
1302     fn next(&mut self) -> Option<A> {
1303         if self.n != 0 {
1304             self.n -= 1;
1305             self.iter.next()
1306         } else {
1307             None
1308         }
1309     }
1310
1311     #[inline]
1312     fn size_hint(&self) -> (uint, Option<uint>) {
1313         let (lower, upper) = self.iter.size_hint();
1314
1315         let lower = cmp::min(lower, self.n);
1316
1317         let upper = match upper {
1318             Some(x) if x < self.n => Some(x),
1319             _ => Some(self.n)
1320         };
1321
1322         (lower, upper)
1323     }
1324 }
1325
1326 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
1327     #[inline]
1328     fn indexable(&self) -> uint {
1329         cmp::min(self.iter.indexable(), self.n)
1330     }
1331
1332     #[inline]
1333     fn idx(&self, index: uint) -> Option<A> {
1334         if index >= self.n {
1335             None
1336         } else {
1337             self.iter.idx(index)
1338         }
1339     }
1340 }
1341
1342
1343 /// An iterator to maintain state while iterating another iterator
1344 pub struct Scan<'self, A, B, T, St> {
1345     priv iter: T,
1346     priv f: &'self fn(&mut St, A) -> Option<B>,
1347
1348     /// The current internal state to be passed to the closure next.
1349     state: St
1350 }
1351
1352 impl<'self, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'self, A, B, T, St> {
1353     #[inline]
1354     fn next(&mut self) -> Option<B> {
1355         self.iter.next().chain(|a| (self.f)(&mut self.state, a))
1356     }
1357
1358     #[inline]
1359     fn size_hint(&self) -> (uint, Option<uint>) {
1360         let (_, upper) = self.iter.size_hint();
1361         (0, upper) // can't know a lower bound, due to the scan function
1362     }
1363 }
1364
1365 /// An iterator that maps each element to an iterator,
1366 /// and yields the elements of the produced iterators
1367 ///
1368 pub struct FlatMap<'self, A, T, U> {
1369     priv iter: T,
1370     priv f: &'self fn(A) -> U,
1371     priv frontiter: Option<U>,
1372     priv backiter: Option<U>,
1373 }
1374
1375 impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for
1376     FlatMap<'self, A, T, U> {
1377     #[inline]
1378     fn next(&mut self) -> Option<B> {
1379         loop {
1380             for inner in self.frontiter.mut_iter() {
1381                 for x in *inner {
1382                     return Some(x)
1383                 }
1384             }
1385             match self.iter.next().map_move(|x| (self.f)(x)) {
1386                 None => return self.backiter.chain_mut_ref(|it| it.next()),
1387                 next => self.frontiter = next,
1388             }
1389         }
1390     }
1391
1392     #[inline]
1393     fn size_hint(&self) -> (uint, Option<uint>) {
1394         let (flo, fhi) = self.frontiter.map_default((0, Some(0)), |it| it.size_hint());
1395         let (blo, bhi) = self.backiter.map_default((0, Some(0)), |it| it.size_hint());
1396         let lo = flo.saturating_add(blo);
1397         match (self.iter.size_hint(), fhi, bhi) {
1398             ((0, Some(0)), Some(a), Some(b)) => (lo, Some(a.saturating_add(b))),
1399             _ => (lo, None)
1400         }
1401     }
1402 }
1403
1404 impl<'self,
1405      A, T: DoubleEndedIterator<A>,
1406      B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
1407      for FlatMap<'self, A, T, U> {
1408     #[inline]
1409     fn next_back(&mut self) -> Option<B> {
1410         loop {
1411             for inner in self.backiter.mut_iter() {
1412                 match inner.next_back() {
1413                     None => (),
1414                     y => return y
1415                 }
1416             }
1417             match self.iter.next_back().map_move(|x| (self.f)(x)) {
1418                 None => return self.frontiter.chain_mut_ref(|it| it.next_back()),
1419                 next => self.backiter = next,
1420             }
1421         }
1422     }
1423 }
1424
1425 /// An iterator that calls a function with a reference to each
1426 /// element before yielding it.
1427 pub struct Peek<'self, A, T> {
1428     priv iter: T,
1429     priv f: &'self fn(&A)
1430 }
1431
1432 impl<'self, A, T> Peek<'self, A, T> {
1433     #[inline]
1434     fn do_peek(&self, elt: Option<A>) -> Option<A> {
1435         match elt {
1436             Some(ref a) => (self.f)(a),
1437             None => ()
1438         }
1439
1440         elt
1441     }
1442 }
1443
1444 impl<'self, A, T: Iterator<A>> Iterator<A> for Peek<'self, A, T> {
1445     #[inline]
1446     fn next(&mut self) -> Option<A> {
1447         let next = self.iter.next();
1448         self.do_peek(next)
1449     }
1450
1451     #[inline]
1452     fn size_hint(&self) -> (uint, Option<uint>) {
1453         self.iter.size_hint()
1454     }
1455 }
1456
1457 impl<'self, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Peek<'self, A, T> {
1458     #[inline]
1459     fn next_back(&mut self) -> Option<A> {
1460         let next = self.iter.next_back();
1461         self.do_peek(next)
1462     }
1463 }
1464
1465 impl<'self, A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Peek<'self, A, T> {
1466     #[inline]
1467     fn indexable(&self) -> uint {
1468         self.iter.indexable()
1469     }
1470
1471     #[inline]
1472     fn idx(&self, index: uint) -> Option<A> {
1473         self.do_peek(self.iter.idx(index))
1474     }
1475 }
1476
1477 /// An iterator which just modifies the contained state throughout iteration.
1478 pub struct Unfoldr<'self, A, St> {
1479     priv f: &'self fn(&mut St) -> Option<A>,
1480     /// Internal state that will be yielded on the next iteration
1481     state: St
1482 }
1483
1484 impl<'self, A, St> Unfoldr<'self, A, St> {
1485     /// Creates a new iterator with the specified closure as the "iterator
1486     /// function" and an initial state to eventually pass to the iterator
1487     #[inline]
1488     pub fn new<'a>(initial_state: St, f: &'a fn(&mut St) -> Option<A>)
1489         -> Unfoldr<'a, A, St> {
1490         Unfoldr {
1491             f: f,
1492             state: initial_state
1493         }
1494     }
1495 }
1496
1497 impl<'self, A, St> Iterator<A> for Unfoldr<'self, A, St> {
1498     #[inline]
1499     fn next(&mut self) -> Option<A> {
1500         (self.f)(&mut self.state)
1501     }
1502 }
1503
1504 /// An infinite iterator starting at `start` and advancing by `step` with each
1505 /// iteration
1506 #[deriving(Clone)]
1507 pub struct Counter<A> {
1508     /// The current state the counter is at (next value to be yielded)
1509     state: A,
1510     /// The amount that this iterator is stepping by
1511     step: A
1512 }
1513
1514 /// Creates a new counter with the specified start/step
1515 #[inline]
1516 pub fn count<A>(start: A, step: A) -> Counter<A> {
1517     Counter{state: start, step: step}
1518 }
1519
1520 /// A range of numbers from [0, N)
1521 #[deriving(Clone, DeepClone)]
1522 pub struct Range<A> {
1523     priv state: A,
1524     priv stop: A,
1525     priv one: A
1526 }
1527
1528 /// Return an iterator over the range [start, stop)
1529 #[inline]
1530 pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
1531     Range{state: start, stop: stop, one: One::one()}
1532 }
1533
1534 impl<A: Add<A, A> + Ord + Clone + One> Iterator<A> for Range<A> {
1535     #[inline]
1536     fn next(&mut self) -> Option<A> {
1537         if self.state < self.stop {
1538             let result = self.state.clone();
1539             self.state = self.state + self.one;
1540             Some(result)
1541         } else {
1542             None
1543         }
1544     }
1545 }
1546
1547 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
1548     #[inline]
1549     fn next(&mut self) -> Option<A> {
1550         let result = self.state.clone();
1551         self.state = self.state + self.step;
1552         Some(result)
1553     }
1554
1555     #[inline]
1556     fn size_hint(&self) -> (uint, Option<uint>) {
1557         (uint::max_value, None) // Too bad we can't specify an infinite lower bound
1558     }
1559 }
1560
1561 /// An iterator that repeats an element endlessly
1562 #[deriving(Clone, DeepClone)]
1563 pub struct Repeat<A> {
1564     priv element: A
1565 }
1566
1567 impl<A: Clone> Repeat<A> {
1568     /// Create a new `Repeat` that enlessly repeats the element `elt`.
1569     #[inline]
1570     pub fn new(elt: A) -> Repeat<A> {
1571         Repeat{element: elt}
1572     }
1573 }
1574
1575 impl<A: Clone> Iterator<A> for Repeat<A> {
1576     #[inline]
1577     fn next(&mut self) -> Option<A> { self.idx(0) }
1578     #[inline]
1579     fn size_hint(&self) -> (uint, Option<uint>) { (uint::max_value, None) }
1580 }
1581
1582 impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
1583     #[inline]
1584     fn next_back(&mut self) -> Option<A> { self.idx(0) }
1585 }
1586
1587 impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
1588     #[inline]
1589     fn indexable(&self) -> uint { uint::max_value }
1590     #[inline]
1591     fn idx(&self, _: uint) -> Option<A> { Some(self.element.clone()) }
1592 }
1593
1594 #[cfg(test)]
1595 mod tests {
1596     use super::*;
1597     use prelude::*;
1598
1599     use cmp;
1600     use uint;
1601
1602     #[test]
1603     fn test_counter_from_iter() {
1604         let mut it = count(0, 5).take_(10);
1605         let xs: ~[int] = FromIterator::from_iterator(&mut it);
1606         assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
1607     }
1608
1609     #[test]
1610     fn test_iterator_chain() {
1611         let xs = [0u, 1, 2, 3, 4, 5];
1612         let ys = [30u, 40, 50, 60];
1613         let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
1614         let mut it = xs.iter().chain_(ys.iter());
1615         let mut i = 0;
1616         for &x in it {
1617             assert_eq!(x, expected[i]);
1618             i += 1;
1619         }
1620         assert_eq!(i, expected.len());
1621
1622         let ys = count(30u, 10).take_(4);
1623         let mut it = xs.iter().transform(|&x| x).chain_(ys);
1624         let mut i = 0;
1625         for x in it {
1626             assert_eq!(x, expected[i]);
1627             i += 1;
1628         }
1629         assert_eq!(i, expected.len());
1630     }
1631
1632     #[test]
1633     fn test_filter_map() {
1634         let mut it = count(0u, 1u).take_(10)
1635             .filter_map(|x| if x.is_even() { Some(x*x) } else { None });
1636         assert_eq!(it.collect::<~[uint]>(), ~[0*0, 2*2, 4*4, 6*6, 8*8]);
1637     }
1638
1639     #[test]
1640     fn test_iterator_enumerate() {
1641         let xs = [0u, 1, 2, 3, 4, 5];
1642         let mut it = xs.iter().enumerate();
1643         for (i, &x) in it {
1644             assert_eq!(i, x);
1645         }
1646     }
1647
1648     #[test]
1649     fn test_iterator_take_while() {
1650         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
1651         let ys = [0u, 1, 2, 3, 5, 13];
1652         let mut it = xs.iter().take_while(|&x| *x < 15u);
1653         let mut i = 0;
1654         for &x in it {
1655             assert_eq!(x, ys[i]);
1656             i += 1;
1657         }
1658         assert_eq!(i, ys.len());
1659     }
1660
1661     #[test]
1662     fn test_iterator_skip_while() {
1663         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
1664         let ys = [15, 16, 17, 19];
1665         let mut it = xs.iter().skip_while(|&x| *x < 15u);
1666         let mut i = 0;
1667         for &x in it {
1668             assert_eq!(x, ys[i]);
1669             i += 1;
1670         }
1671         assert_eq!(i, ys.len());
1672     }
1673
1674     #[test]
1675     fn test_iterator_skip() {
1676         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
1677         let ys = [13, 15, 16, 17, 19, 20, 30];
1678         let mut it = xs.iter().skip(5);
1679         let mut i = 0;
1680         for &x in it {
1681             assert_eq!(x, ys[i]);
1682             i += 1;
1683         }
1684         assert_eq!(i, ys.len());
1685     }
1686
1687     #[test]
1688     fn test_iterator_take() {
1689         let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
1690         let ys = [0u, 1, 2, 3, 5];
1691         let mut it = xs.iter().take_(5);
1692         let mut i = 0;
1693         for &x in it {
1694             assert_eq!(x, ys[i]);
1695             i += 1;
1696         }
1697         assert_eq!(i, ys.len());
1698     }
1699
1700     #[test]
1701     fn test_iterator_scan() {
1702         // test the type inference
1703         fn add(old: &mut int, new: &uint) -> Option<float> {
1704             *old += *new as int;
1705             Some(*old as float)
1706         }
1707         let xs = [0u, 1, 2, 3, 4];
1708         let ys = [0f, 1f, 3f, 6f, 10f];
1709
1710         let mut it = xs.iter().scan(0, add);
1711         let mut i = 0;
1712         for x in it {
1713             assert_eq!(x, ys[i]);
1714             i += 1;
1715         }
1716         assert_eq!(i, ys.len());
1717     }
1718
1719     #[test]
1720     fn test_iterator_flat_map() {
1721         let xs = [0u, 3, 6];
1722         let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
1723         let mut it = xs.iter().flat_map_(|&x| count(x, 1).take_(3));
1724         let mut i = 0;
1725         for x in it {
1726             assert_eq!(x, ys[i]);
1727             i += 1;
1728         }
1729         assert_eq!(i, ys.len());
1730     }
1731
1732     #[test]
1733     fn test_peek() {
1734         let xs = [1u, 2, 3, 4];
1735         let mut n = 0;
1736
1737         let ys = xs.iter()
1738                    .transform(|&x| x)
1739                    .peek_(|_| n += 1)
1740                    .collect::<~[uint]>();
1741
1742         assert_eq!(n, xs.len());
1743         assert_eq!(xs, ys.as_slice());
1744     }
1745
1746     #[test]
1747     fn test_unfoldr() {
1748         fn count(st: &mut uint) -> Option<uint> {
1749             if *st < 10 {
1750                 let ret = Some(*st);
1751                 *st += 1;
1752                 ret
1753             } else {
1754                 None
1755             }
1756         }
1757
1758         let mut it = Unfoldr::new(0, count);
1759         let mut i = 0;
1760         for counted in it {
1761             assert_eq!(counted, i);
1762             i += 1;
1763         }
1764         assert_eq!(i, 10);
1765     }
1766
1767     #[test]
1768     fn test_cycle() {
1769         let cycle_len = 3;
1770         let it = count(0u, 1).take_(cycle_len).cycle();
1771         assert_eq!(it.size_hint(), (uint::max_value, None));
1772         for (i, x) in it.take_(100).enumerate() {
1773             assert_eq!(i % cycle_len, x);
1774         }
1775
1776         let mut it = count(0u, 1).take_(0).cycle();
1777         assert_eq!(it.size_hint(), (0, Some(0)));
1778         assert_eq!(it.next(), None);
1779     }
1780
1781     #[test]
1782     fn test_iterator_nth() {
1783         let v = &[0, 1, 2, 3, 4];
1784         for i in range(0u, v.len()) {
1785             assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
1786         }
1787     }
1788
1789     #[test]
1790     fn test_iterator_last() {
1791         let v = &[0, 1, 2, 3, 4];
1792         assert_eq!(v.iter().last_().unwrap(), &4);
1793         assert_eq!(v.slice(0, 1).iter().last_().unwrap(), &0);
1794     }
1795
1796     #[test]
1797     fn test_iterator_len() {
1798         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1799         assert_eq!(v.slice(0, 4).iter().len_(), 4);
1800         assert_eq!(v.slice(0, 10).iter().len_(), 10);
1801         assert_eq!(v.slice(0, 0).iter().len_(), 0);
1802     }
1803
1804     #[test]
1805     fn test_iterator_sum() {
1806         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1807         assert_eq!(v.slice(0, 4).iter().transform(|&x| x).sum(), 6);
1808         assert_eq!(v.iter().transform(|&x| x).sum(), 55);
1809         assert_eq!(v.slice(0, 0).iter().transform(|&x| x).sum(), 0);
1810     }
1811
1812     #[test]
1813     fn test_iterator_product() {
1814         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1815         assert_eq!(v.slice(0, 4).iter().transform(|&x| x).product(), 0);
1816         assert_eq!(v.slice(1, 5).iter().transform(|&x| x).product(), 24);
1817         assert_eq!(v.slice(0, 0).iter().transform(|&x| x).product(), 1);
1818     }
1819
1820     #[test]
1821     fn test_iterator_max() {
1822         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1823         assert_eq!(v.slice(0, 4).iter().transform(|&x| x).max(), Some(3));
1824         assert_eq!(v.iter().transform(|&x| x).max(), Some(10));
1825         assert_eq!(v.slice(0, 0).iter().transform(|&x| x).max(), None);
1826     }
1827
1828     #[test]
1829     fn test_iterator_min() {
1830         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1831         assert_eq!(v.slice(0, 4).iter().transform(|&x| x).min(), Some(0));
1832         assert_eq!(v.iter().transform(|&x| x).min(), Some(0));
1833         assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None);
1834     }
1835
1836     #[test]
1837     fn test_iterator_size_hint() {
1838         let c = count(0, 1);
1839         let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1840         let v2 = &[10, 11, 12];
1841         let vi = v.iter();
1842
1843         assert_eq!(c.size_hint(), (uint::max_value, None));
1844         assert_eq!(vi.size_hint(), (10, Some(10)));
1845
1846         assert_eq!(c.take_(5).size_hint(), (5, Some(5)));
1847         assert_eq!(c.skip(5).size_hint().second(), None);
1848         assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
1849         assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
1850         assert_eq!(c.enumerate().size_hint(), (uint::max_value, None));
1851         assert_eq!(c.chain_(vi.transform(|&i| i)).size_hint(), (uint::max_value, None));
1852         assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
1853         assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
1854         assert_eq!(c.filter(|_| false).size_hint(), (0, None));
1855         assert_eq!(c.transform(|_| 0).size_hint(), (uint::max_value, None));
1856         assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
1857
1858         assert_eq!(vi.take_(5).size_hint(), (5, Some(5)));
1859         assert_eq!(vi.take_(12).size_hint(), (10, Some(10)));
1860         assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
1861         assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
1862         assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
1863         assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
1864         assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
1865         assert_eq!(vi.chain_(v2.iter()).size_hint(), (13, Some(13)));
1866         assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
1867         assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
1868         assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
1869         assert_eq!(vi.transform(|i| i+1).size_hint(), (10, Some(10)));
1870         assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
1871     }
1872
1873     #[test]
1874     fn test_collect() {
1875         let a = ~[1, 2, 3, 4, 5];
1876         let b: ~[int] = a.iter().transform(|&x| x).collect();
1877         assert_eq!(a, b);
1878     }
1879
1880     #[test]
1881     fn test_all() {
1882         let v = ~&[1, 2, 3, 4, 5];
1883         assert!(v.iter().all(|&x| x < 10));
1884         assert!(!v.iter().all(|&x| x.is_even()));
1885         assert!(!v.iter().all(|&x| x > 100));
1886         assert!(v.slice(0, 0).iter().all(|_| fail!()));
1887     }
1888
1889     #[test]
1890     fn test_any() {
1891         let v = ~&[1, 2, 3, 4, 5];
1892         assert!(v.iter().any(|&x| x < 10));
1893         assert!(v.iter().any(|&x| x.is_even()));
1894         assert!(!v.iter().any(|&x| x > 100));
1895         assert!(!v.slice(0, 0).iter().any(|_| fail!()));
1896     }
1897
1898     #[test]
1899     fn test_find() {
1900         let v = &[1, 3, 9, 27, 103, 14, 11];
1901         assert_eq!(*v.iter().find_(|x| *x & 1 == 0).unwrap(), 14);
1902         assert_eq!(*v.iter().find_(|x| *x % 3 == 0).unwrap(), 3);
1903         assert!(v.iter().find_(|x| *x % 12 == 0).is_none());
1904     }
1905
1906     #[test]
1907     fn test_position() {
1908         let v = &[1, 3, 9, 27, 103, 14, 11];
1909         assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
1910         assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
1911         assert!(v.iter().position(|x| *x % 12 == 0).is_none());
1912     }
1913
1914     #[test]
1915     fn test_count() {
1916         let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
1917         assert_eq!(xs.iter().count(|x| *x == 2), 3);
1918         assert_eq!(xs.iter().count(|x| *x == 5), 1);
1919         assert_eq!(xs.iter().count(|x| *x == 95), 0);
1920     }
1921
1922     #[test]
1923     fn test_max_by() {
1924         let xs = [-3, 0, 1, 5, -10];
1925         assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
1926     }
1927
1928     #[test]
1929     fn test_min_by() {
1930         let xs = [-3, 0, 1, 5, -10];
1931         assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
1932     }
1933
1934     #[test]
1935     fn test_invert() {
1936         let xs = [2, 4, 6, 8, 10, 12, 14, 16];
1937         let mut it = xs.iter();
1938         it.next();
1939         it.next();
1940         assert_eq!(it.invert().transform(|&x| x).collect::<~[int]>(), ~[16, 14, 12, 10, 8, 6]);
1941     }
1942
1943     #[test]
1944     fn test_double_ended_map() {
1945         let xs = [1, 2, 3, 4, 5, 6];
1946         let mut it = xs.iter().transform(|&x| x * -1);
1947         assert_eq!(it.next(), Some(-1));
1948         assert_eq!(it.next(), Some(-2));
1949         assert_eq!(it.next_back(), Some(-6));
1950         assert_eq!(it.next_back(), Some(-5));
1951         assert_eq!(it.next(), Some(-3));
1952         assert_eq!(it.next_back(), Some(-4));
1953         assert_eq!(it.next(), None);
1954     }
1955
1956     #[test]
1957     fn test_double_ended_filter() {
1958         let xs = [1, 2, 3, 4, 5, 6];
1959         let mut it = xs.iter().filter(|&x| *x & 1 == 0);
1960         assert_eq!(it.next_back().unwrap(), &6);
1961         assert_eq!(it.next_back().unwrap(), &4);
1962         assert_eq!(it.next().unwrap(), &2);
1963         assert_eq!(it.next_back(), None);
1964     }
1965
1966     #[test]
1967     fn test_double_ended_filter_map() {
1968         let xs = [1, 2, 3, 4, 5, 6];
1969         let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
1970         assert_eq!(it.next_back().unwrap(), 12);
1971         assert_eq!(it.next_back().unwrap(), 8);
1972         assert_eq!(it.next().unwrap(), 4);
1973         assert_eq!(it.next_back(), None);
1974     }
1975
1976     #[test]
1977     fn test_double_ended_chain() {
1978         let xs = [1, 2, 3, 4, 5];
1979         let ys = ~[7, 9, 11];
1980         let mut it = xs.iter().chain_(ys.iter()).invert();
1981         assert_eq!(it.next().unwrap(), &11)
1982         assert_eq!(it.next().unwrap(), &9)
1983         assert_eq!(it.next_back().unwrap(), &1)
1984         assert_eq!(it.next_back().unwrap(), &2)
1985         assert_eq!(it.next_back().unwrap(), &3)
1986         assert_eq!(it.next_back().unwrap(), &4)
1987         assert_eq!(it.next_back().unwrap(), &5)
1988         assert_eq!(it.next_back().unwrap(), &7)
1989         assert_eq!(it.next_back(), None)
1990     }
1991
1992     #[cfg(test)]
1993     fn check_randacc_iter<A: Eq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint)
1994     {
1995         let mut b = a.clone();
1996         assert_eq!(len, b.indexable());
1997         let mut n = 0;
1998         for (i, elt) in a.enumerate() {
1999             assert_eq!(Some(elt), b.idx(i));
2000             n += 1;
2001         }
2002         assert_eq!(n, len);
2003         assert_eq!(None, b.idx(n));
2004         // call recursively to check after picking off an element
2005         if len > 0 {
2006             b.next();
2007             check_randacc_iter(b, len-1);
2008         }
2009     }
2010
2011
2012     #[test]
2013     fn test_double_ended_flat_map() {
2014         let u = [0u,1];
2015         let v = [5,6,7,8];
2016         let mut it = u.iter().flat_map_(|x| v.slice(*x, v.len()).iter());
2017         assert_eq!(it.next_back().unwrap(), &8);
2018         assert_eq!(it.next().unwrap(),      &5);
2019         assert_eq!(it.next_back().unwrap(), &7);
2020         assert_eq!(it.next_back().unwrap(), &6);
2021         assert_eq!(it.next_back().unwrap(), &8);
2022         assert_eq!(it.next().unwrap(),      &6);
2023         assert_eq!(it.next_back().unwrap(), &7);
2024         assert_eq!(it.next_back(), None);
2025         assert_eq!(it.next(),      None);
2026         assert_eq!(it.next_back(), None);
2027     }
2028
2029     #[test]
2030     fn test_random_access_chain() {
2031         let xs = [1, 2, 3, 4, 5];
2032         let ys = ~[7, 9, 11];
2033         let mut it = xs.iter().chain_(ys.iter());
2034         assert_eq!(it.idx(0).unwrap(), &1);
2035         assert_eq!(it.idx(5).unwrap(), &7);
2036         assert_eq!(it.idx(7).unwrap(), &11);
2037         assert!(it.idx(8).is_none());
2038
2039         it.next();
2040         it.next();
2041         it.next_back();
2042
2043         assert_eq!(it.idx(0).unwrap(), &3);
2044         assert_eq!(it.idx(4).unwrap(), &9);
2045         assert!(it.idx(6).is_none());
2046
2047         check_randacc_iter(it, xs.len() + ys.len() - 3);
2048     }
2049
2050     #[test]
2051     fn test_random_access_enumerate() {
2052         let xs = [1, 2, 3, 4, 5];
2053         check_randacc_iter(xs.iter().enumerate(), xs.len());
2054     }
2055
2056     #[test]
2057     fn test_random_access_invert() {
2058         let xs = [1, 2, 3, 4, 5];
2059         check_randacc_iter(xs.iter().invert(), xs.len());
2060         let mut it = xs.iter().invert();
2061         it.next();
2062         it.next_back();
2063         it.next();
2064         check_randacc_iter(it, xs.len() - 3);
2065     }
2066
2067     #[test]
2068     fn test_random_access_zip() {
2069         let xs = [1, 2, 3, 4, 5];
2070         let ys = [7, 9, 11];
2071         check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
2072     }
2073
2074     #[test]
2075     fn test_random_access_take() {
2076         let xs = [1, 2, 3, 4, 5];
2077         let empty: &[int] = [];
2078         check_randacc_iter(xs.iter().take_(3), 3);
2079         check_randacc_iter(xs.iter().take_(20), xs.len());
2080         check_randacc_iter(xs.iter().take_(0), 0);
2081         check_randacc_iter(empty.iter().take_(2), 0);
2082     }
2083
2084     #[test]
2085     fn test_random_access_skip() {
2086         let xs = [1, 2, 3, 4, 5];
2087         let empty: &[int] = [];
2088         check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
2089         check_randacc_iter(empty.iter().skip(2), 0);
2090     }
2091
2092     #[test]
2093     fn test_random_access_peek() {
2094         let xs = [1, 2, 3, 4, 5];
2095
2096         // test .transform and .peek_ that don't implement Clone
2097         let it = xs.iter().peek_(|_| {});
2098         assert_eq!(xs.len(), it.indexable());
2099         for (i, elt) in xs.iter().enumerate() {
2100             assert_eq!(Some(elt), it.idx(i));
2101         }
2102
2103     }
2104
2105     #[test]
2106     fn test_random_access_transform() {
2107         let xs = [1, 2, 3, 4, 5];
2108
2109         // test .transform and .peek_ that don't implement Clone
2110         let it = xs.iter().transform(|x| *x);
2111         assert_eq!(xs.len(), it.indexable());
2112         for (i, elt) in xs.iter().enumerate() {
2113             assert_eq!(Some(*elt), it.idx(i));
2114         }
2115     }
2116
2117     #[test]
2118     fn test_random_access_cycle() {
2119         let xs = [1, 2, 3, 4, 5];
2120         let empty: &[int] = [];
2121         check_randacc_iter(xs.iter().cycle().take_(27), 27);
2122         check_randacc_iter(empty.iter().cycle(), 0);
2123     }
2124 }