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