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