]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / libcore / iter.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Composable external iterators
12 //!
13 //! # The `Iterator` trait
14 //!
15 //! This module defines Rust's core iteration trait. The `Iterator` trait has one
16 //! unimplemented method, `next`. All other methods are derived through default
17 //! methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.
18 //!
19 //! The goal of this module is to unify iteration across all containers in Rust.
20 //! An iterator can be considered as a state machine which is used to track which
21 //! element will be yielded next.
22 //!
23 //! There are various extensions also defined in this module to assist with various
24 //! types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
25 //! the `FromIterator` trait for creating a container from an iterator, and much
26 //! more.
27 //!
28 //! ## Rust's `for` loop
29 //!
30 //! The special syntax used by rust's `for` loop is based around the `Iterator`
31 //! trait defined in this module. For loops can be viewed as a syntactical expansion
32 //! into a `loop`, for example, the `for` loop in this example is essentially
33 //! translated to the `loop` below.
34 //!
35 //! ```rust
36 //! let values = vec![1i, 2, 3];
37 //!
38 //! // "Syntactical sugar" taking advantage of an iterator
39 //! for &x in values.iter() {
40 //!     println!("{}", x);
41 //! }
42 //!
43 //! // Rough translation of the iteration without a `for` iterator.
44 //! let mut it = values.iter();
45 //! loop {
46 //!     match it.next() {
47 //!         Some(&x) => {
48 //!             println!("{}", x);
49 //!         }
50 //!         None => { break }
51 //!     }
52 //! }
53 //! ```
54 //!
55 //! This `for` loop syntax can be applied to any iterator over any type.
56
57 pub use self::MinMaxResult::*;
58
59 use clone::Clone;
60 use cmp;
61 use cmp::Ord;
62 use mem;
63 use num::{ToPrimitive, Int};
64 use ops::{Add, Deref};
65 use option::Option;
66 use option::Option::{Some, None};
67 use uint;
68
69 #[deprecated = "renamed to Extend"] pub use self::Extend as Extendable;
70
71 /// Conversion from an `Iterator`
72 #[unstable = "may be replaced by a more general conversion trait"]
73 pub trait FromIterator<A> {
74     /// Build a container with elements from an external iterator.
75     fn from_iter<T: Iterator<A>>(iterator: T) -> Self;
76 }
77
78 /// A type growable from an `Iterator` implementation
79 #[unstable = "just renamed as part of collections reform"]
80 pub trait Extend<A> {
81     /// Extend a container with the elements yielded by an arbitrary iterator
82     fn extend<T: Iterator<A>>(&mut self, iterator: T);
83 }
84
85 /// An interface for dealing with "external iterators". These types of iterators
86 /// can be resumed at any time as all state is stored internally as opposed to
87 /// being located on the call stack.
88 ///
89 /// The Iterator protocol states that an iterator yields a (potentially-empty,
90 /// potentially-infinite) sequence of values, and returns `None` to signal that
91 /// it's finished. The Iterator protocol does not define behavior after `None`
92 /// is returned. A concrete Iterator implementation may choose to behave however
93 /// it wishes, either by returning `None` infinitely, or by doing something
94 /// else.
95 #[lang="iterator"]
96 #[unstable = "just split up for object safety"]
97 pub trait Iterator<A> {
98     /// Advance the iterator and return the next value. Return `None` when the end is reached.
99     fn next(&mut self) -> Option<A>;
100
101     /// Returns a lower and upper bound on the remaining length of the iterator.
102     ///
103     /// An upper bound of `None` means either there is no known upper bound, or the upper bound
104     /// does not fit within a `uint`.
105     #[inline]
106     fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
107 }
108
109 #[unstable = "new convention for extension traits"]
110 /// An extension trait providing numerous methods applicable to all iterators.
111 pub trait IteratorExt<A>: Iterator<A> {
112     /// Chain this iterator with another, returning a new iterator which will
113     /// finish iterating over the current iterator, and then it will iterate
114     /// over the other specified iterator.
115     ///
116     /// # Example
117     ///
118     /// ```rust
119     /// let a = [0i];
120     /// let b = [1i];
121     /// let mut it = a.iter().chain(b.iter());
122     /// assert_eq!(it.next().unwrap(), &0);
123     /// assert_eq!(it.next().unwrap(), &1);
124     /// assert!(it.next().is_none());
125     /// ```
126     #[inline]
127     #[stable]
128     fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
129         Chain{a: self, b: other, flag: false}
130     }
131
132     /// Creates an iterator which iterates over both this and the specified
133     /// iterators simultaneously, yielding the two elements as pairs. When
134     /// either iterator returns None, all further invocations of next() will
135     /// return None.
136     ///
137     /// # Example
138     ///
139     /// ```rust
140     /// let a = [0i];
141     /// let b = [1i];
142     /// let mut it = a.iter().zip(b.iter());
143     /// let (x0, x1) = (0i, 1i);
144     /// assert_eq!(it.next().unwrap(), (&x0, &x1));
145     /// assert!(it.next().is_none());
146     /// ```
147     #[inline]
148     #[stable]
149     fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
150         Zip{a: self, b: other}
151     }
152
153     /// Creates a new iterator which will apply the specified function to each
154     /// element returned by the first, yielding the mapped element instead.
155     ///
156     /// # Example
157     ///
158     /// ```rust
159     /// let a = [1i, 2];
160     /// let mut it = a.iter().map(|&x| 2 * x);
161     /// assert_eq!(it.next().unwrap(), 2);
162     /// assert_eq!(it.next().unwrap(), 4);
163     /// assert!(it.next().is_none());
164     /// ```
165     #[inline]
166     #[unstable = "waiting for unboxed closures"]
167     fn map<'r, B>(self, f: |A|: 'r -> B) -> Map<'r, A, B, Self> {
168         Map{iter: self, f: f}
169     }
170
171     /// Creates an iterator which applies the predicate to each element returned
172     /// by this iterator. Only elements which have the predicate evaluate to
173     /// `true` will be yielded.
174     ///
175     /// # Example
176     ///
177     /// ```rust
178     /// let a = [1i, 2];
179     /// let mut it = a.iter().filter(|&x| *x > 1);
180     /// assert_eq!(it.next().unwrap(), &2);
181     /// assert!(it.next().is_none());
182     /// ```
183     #[inline]
184     #[unstable = "waiting for unboxed closures"]
185     fn filter<'r>(self, predicate: |&A|: 'r -> bool) -> Filter<'r, A, Self> {
186         Filter{iter: self, predicate: predicate}
187     }
188
189     /// Creates an iterator which both filters and maps elements.
190     /// If the specified function returns None, the element is skipped.
191     /// Otherwise the option is unwrapped and the new value is yielded.
192     ///
193     /// # Example
194     ///
195     /// ```rust
196     /// let a = [1i, 2];
197     /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
198     /// assert_eq!(it.next().unwrap(), 4);
199     /// assert!(it.next().is_none());
200     /// ```
201     #[inline]
202     #[unstable = "waiting for unboxed closures"]
203     fn filter_map<'r, B>(self, f: |A|: 'r -> Option<B>) -> FilterMap<'r, A, B, Self> {
204         FilterMap { iter: self, f: f }
205     }
206
207     /// Creates an iterator which yields a pair of the value returned by this
208     /// iterator plus the current index of iteration.
209     ///
210     /// # Example
211     ///
212     /// ```rust
213     /// let a = [100i, 200];
214     /// let mut it = a.iter().enumerate();
215     /// let (x100, x200) = (100i, 200i);
216     /// assert_eq!(it.next().unwrap(), (0, &x100));
217     /// assert_eq!(it.next().unwrap(), (1, &x200));
218     /// assert!(it.next().is_none());
219     /// ```
220     #[inline]
221     #[stable]
222     fn enumerate(self) -> Enumerate<Self> {
223         Enumerate{iter: self, count: 0}
224     }
225
226
227     /// Creates an iterator that has a `.peek()` method
228     /// that returns an optional reference to the next element.
229     ///
230     /// # Example
231     ///
232     /// ```rust
233     /// let xs = [100i, 200, 300];
234     /// let mut it = xs.iter().map(|x| *x).peekable();
235     /// assert_eq!(*it.peek().unwrap(), 100);
236     /// assert_eq!(it.next().unwrap(), 100);
237     /// assert_eq!(it.next().unwrap(), 200);
238     /// assert_eq!(*it.peek().unwrap(), 300);
239     /// assert_eq!(*it.peek().unwrap(), 300);
240     /// assert_eq!(it.next().unwrap(), 300);
241     /// assert!(it.peek().is_none());
242     /// assert!(it.next().is_none());
243     /// ```
244     #[inline]
245     #[stable]
246     fn peekable(self) -> Peekable<A, Self> {
247         Peekable{iter: self, peeked: None}
248     }
249
250     /// Creates an iterator which invokes the predicate on elements until it
251     /// returns false. Once the predicate returns false, all further elements are
252     /// yielded.
253     ///
254     /// # Example
255     ///
256     /// ```rust
257     /// let a = [1i, 2, 3, 2, 1];
258     /// let mut it = a.iter().skip_while(|&a| *a < 3);
259     /// assert_eq!(it.next().unwrap(), &3);
260     /// assert_eq!(it.next().unwrap(), &2);
261     /// assert_eq!(it.next().unwrap(), &1);
262     /// assert!(it.next().is_none());
263     /// ```
264     #[inline]
265     #[unstable = "waiting for unboxed closures"]
266     fn skip_while<'r>(self, predicate: |&A|: 'r -> bool) -> SkipWhile<'r, A, Self> {
267         SkipWhile{iter: self, flag: false, predicate: predicate}
268     }
269
270     /// Creates an iterator which yields elements so long as the predicate
271     /// returns true. After the predicate returns false for the first time, no
272     /// further elements will be yielded.
273     ///
274     /// # Example
275     ///
276     /// ```rust
277     /// let a = [1i, 2, 3, 2, 1];
278     /// let mut it = a.iter().take_while(|&a| *a < 3);
279     /// assert_eq!(it.next().unwrap(), &1);
280     /// assert_eq!(it.next().unwrap(), &2);
281     /// assert!(it.next().is_none());
282     /// ```
283     #[inline]
284     #[unstable = "waiting for unboxed closures, may want to require peek"]
285     fn take_while<'r>(self, predicate: |&A|: 'r -> bool) -> TakeWhile<'r, A, Self> {
286         TakeWhile{iter: self, flag: false, predicate: predicate}
287     }
288
289     /// Creates an iterator which skips the first `n` elements of this iterator,
290     /// and then it yields all further items.
291     ///
292     /// # Example
293     ///
294     /// ```rust
295     /// let a = [1i, 2, 3, 4, 5];
296     /// let mut it = a.iter().skip(3);
297     /// assert_eq!(it.next().unwrap(), &4);
298     /// assert_eq!(it.next().unwrap(), &5);
299     /// assert!(it.next().is_none());
300     /// ```
301     #[inline]
302     #[stable]
303     fn skip(self, n: uint) -> Skip<Self> {
304         Skip{iter: self, n: n}
305     }
306
307     /// Creates an iterator which yields the first `n` elements of this
308     /// iterator, and then it will always return None.
309     ///
310     /// # Example
311     ///
312     /// ```rust
313     /// let a = [1i, 2, 3, 4, 5];
314     /// let mut it = a.iter().take(3);
315     /// assert_eq!(it.next().unwrap(), &1);
316     /// assert_eq!(it.next().unwrap(), &2);
317     /// assert_eq!(it.next().unwrap(), &3);
318     /// assert!(it.next().is_none());
319     /// ```
320     #[inline]
321     #[stable]
322     fn take(self, n: uint) -> Take<Self> {
323         Take{iter: self, n: n}
324     }
325
326     /// Creates a new iterator which behaves in a similar fashion to fold.
327     /// There is a state which is passed between each iteration and can be
328     /// mutated as necessary. The yielded values from the closure are yielded
329     /// from the Scan instance when not None.
330     ///
331     /// # Example
332     ///
333     /// ```rust
334     /// let a = [1i, 2, 3, 4, 5];
335     /// let mut it = a.iter().scan(1, |fac, &x| {
336     ///   *fac = *fac * x;
337     ///   Some(*fac)
338     /// });
339     /// assert_eq!(it.next().unwrap(), 1);
340     /// assert_eq!(it.next().unwrap(), 2);
341     /// assert_eq!(it.next().unwrap(), 6);
342     /// assert_eq!(it.next().unwrap(), 24);
343     /// assert_eq!(it.next().unwrap(), 120);
344     /// assert!(it.next().is_none());
345     /// ```
346     #[inline]
347     #[unstable = "waiting for unboxed closures"]
348     fn scan<'r, St, B>(self, initial_state: St, f: |&mut St, A|: 'r -> Option<B>)
349         -> Scan<'r, A, B, Self, St> {
350         Scan{iter: self, f: f, state: initial_state}
351     }
352
353     /// Creates an iterator that maps each element to an iterator,
354     /// and yields the elements of the produced iterators
355     ///
356     /// # Example
357     ///
358     /// ```rust
359     /// use std::iter::count;
360     ///
361     /// let xs = [2u, 3];
362     /// let ys = [0u, 1, 0, 1, 2];
363     /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
364     /// // Check that `it` has the same elements as `ys`
365     /// let mut i = 0;
366     /// for x in it {
367     ///     assert_eq!(x, ys[i]);
368     ///     i += 1;
369     /// }
370     /// ```
371     #[inline]
372     #[unstable = "waiting for unboxed closures"]
373     fn flat_map<'r, B, U: Iterator<B>>(self, f: |A|: 'r -> U)
374         -> FlatMap<'r, A, Self, U> {
375         FlatMap{iter: self, f: f, frontiter: None, backiter: None }
376     }
377
378     /// Creates an iterator that yields `None` forever after the underlying
379     /// iterator yields `None`. Random-access iterator behavior is not
380     /// affected, only single and double-ended iterator behavior.
381     ///
382     /// # Example
383     ///
384     /// ```rust
385     /// fn process<U: Iterator<int>>(it: U) -> int {
386     ///     let mut it = it.fuse();
387     ///     let mut sum = 0;
388     ///     for x in it {
389     ///         if x > 5 {
390     ///             break;
391     ///         }
392     ///         sum += x;
393     ///     }
394     ///     // did we exhaust the iterator?
395     ///     if it.next().is_none() {
396     ///         sum += 1000;
397     ///     }
398     ///     sum
399     /// }
400     /// let x = vec![1i,2,3,7,8,9];
401     /// assert_eq!(process(x.into_iter()), 6);
402     /// let x = vec![1i,2,3];
403     /// assert_eq!(process(x.into_iter()), 1006);
404     /// ```
405     #[inline]
406     #[stable]
407     fn fuse(self) -> Fuse<Self> {
408         Fuse{iter: self, done: false}
409     }
410
411     /// Creates an iterator that calls a function with a reference to each
412     /// element before yielding it. This is often useful for debugging an
413     /// iterator pipeline.
414     ///
415     /// # Example
416     ///
417     /// ```rust
418     /// use std::iter::AdditiveIterator;
419     ///
420     /// let xs = [1u, 4, 2, 3, 8, 9, 6];
421     /// let sum = xs.iter()
422     ///             .map(|&x| x)
423     ///             .inspect(|&x| println!("filtering {}", x))
424     ///             .filter(|&x| x % 2 == 0)
425     ///             .inspect(|&x| println!("{} made it through", x))
426     ///             .sum();
427     /// println!("{}", sum);
428     /// ```
429     #[inline]
430     #[unstable = "waiting for unboxed closures"]
431     fn inspect<'r>(self, f: |&A|: 'r) -> Inspect<'r, A, Self> {
432         Inspect{iter: self, f: f}
433     }
434
435     /// Creates a wrapper around a mutable reference to the iterator.
436     ///
437     /// This is useful to allow applying iterator adaptors while still
438     /// retaining ownership of the original iterator value.
439     ///
440     /// # Example
441     ///
442     /// ```rust
443     /// let mut xs = range(0u, 10);
444     /// // sum the first five values
445     /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
446     /// assert!(partial_sum == 10);
447     /// // xs.next() is now `5`
448     /// assert!(xs.next() == Some(5));
449     /// ```
450     #[stable]
451     fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
452         ByRef{iter: self}
453     }
454
455     /// Loops through the entire iterator, collecting all of the elements into
456     /// a container implementing `FromIterator`.
457     ///
458     /// # Example
459     ///
460     /// ```rust
461     /// let a = [1i, 2, 3, 4, 5];
462     /// let b: Vec<int> = a.iter().map(|&x| x).collect();
463     /// assert!(a.as_slice() == b.as_slice());
464     /// ```
465     #[inline]
466     #[unstable = "waiting for general conversion traits, just changed to take self by value"]
467     fn collect<B: FromIterator<A>>(self) -> B {
468         FromIterator::from_iter(self)
469     }
470
471     /// Loops through `n` iterations, returning the `n`th element of the
472     /// iterator.
473     ///
474     /// # Example
475     ///
476     /// ```rust
477     /// let a = [1i, 2, 3, 4, 5];
478     /// let mut it = a.iter();
479     /// assert!(it.nth(2).unwrap() == &3);
480     /// assert!(it.nth(2) == None);
481     /// ```
482     #[inline]
483     #[stable]
484     fn nth(&mut self, mut n: uint) -> Option<A> {
485         for x in *self {
486             if n == 0 { return Some(x) }
487             n -= 1;
488         }
489         None
490     }
491
492     /// Loops through the entire iterator, returning the last element of the
493     /// iterator.
494     ///
495     /// # Example
496     ///
497     /// ```rust
498     /// let a = [1i, 2, 3, 4, 5];
499     /// assert!(a.iter().last().unwrap() == &5);
500     /// ```
501     #[inline]
502     #[unstable = "just changed to take self by value"]
503     fn last(mut self) -> Option<A> {
504         let mut last = None;
505         for x in self { last = Some(x); }
506         last
507     }
508
509     /// Performs a fold operation over the entire iterator, returning the
510     /// eventual state at the end of the iteration.
511     ///
512     /// # Example
513     ///
514     /// ```rust
515     /// let a = [1i, 2, 3, 4, 5];
516     /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
517     /// ```
518     #[inline]
519     #[unstable = "waiting for unboxed closures, just changed to take self by value"]
520     fn fold<B>(mut self, init: B, f: |B, A| -> B) -> B {
521         let mut accum = init;
522         for x in self {
523             accum = f(accum, x);
524         }
525         accum
526     }
527
528     /// Counts the number of elements in this iterator.
529     ///
530     /// # Example
531     ///
532     /// ```rust
533     /// let a = [1i, 2, 3, 4, 5];
534     /// let mut it = a.iter();
535     /// assert!(it.count() == 5);
536     /// ```
537     #[inline]
538     #[unstable = "just changed to take self by value"]
539     fn count(self) -> uint {
540         self.fold(0, |cnt, _x| cnt + 1)
541     }
542
543     /// Tests whether the predicate holds true for all elements in the iterator.
544     ///
545     /// # Example
546     ///
547     /// ```rust
548     /// let a = [1i, 2, 3, 4, 5];
549     /// assert!(a.iter().all(|x| *x > 0));
550     /// assert!(!a.iter().all(|x| *x > 2));
551     /// ```
552     #[inline]
553     #[unstable = "waiting for unboxed closures, just changed to take self by value"]
554     fn all(mut self, f: |A| -> bool) -> bool {
555         for x in self { if !f(x) { return false; } }
556         true
557     }
558
559     /// Tests whether any element of an iterator satisfies the specified
560     /// predicate.
561     ///
562     /// # Example
563     ///
564     /// ```rust
565     /// let a = [1i, 2, 3, 4, 5];
566     /// let mut it = a.iter();
567     /// assert!(it.any(|x| *x == 3));
568     /// assert!(!it.any(|x| *x == 3));
569     /// ```
570     #[inline]
571     #[unstable = "waiting for unboxed closures"]
572     fn any(&mut self, f: |A| -> bool) -> bool {
573         for x in *self { if f(x) { return true; } }
574         false
575     }
576
577     /// Returns the first element satisfying the specified predicate.
578     ///
579     /// Does not consume the iterator past the first found element.
580     #[inline]
581     #[unstable = "waiting for unboxed closures"]
582     fn find(&mut self, predicate: |&A| -> bool) -> Option<A> {
583         for x in *self {
584             if predicate(&x) { return Some(x) }
585         }
586         None
587     }
588
589     /// Return the index of the first element satisfying the specified predicate
590     #[inline]
591     #[unstable = "waiting for unboxed closures"]
592     fn position(&mut self, predicate: |A| -> bool) -> Option<uint> {
593         let mut i = 0;
594         for x in *self {
595             if predicate(x) {
596                 return Some(i);
597             }
598             i += 1;
599         }
600         None
601     }
602
603     /// Return the element that gives the maximum value from the
604     /// specified function.
605     ///
606     /// # Example
607     ///
608     /// ```rust
609     /// use core::num::SignedInt;
610     ///
611     /// let xs = [-3i, 0, 1, 5, -10];
612     /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
613     /// ```
614     #[inline]
615     #[unstable = "waiting for unboxed closures, just changed to take self by value"]
616     fn max_by<B: Ord>(self, f: |&A| -> B) -> Option<A> {
617         self.fold(None, |max: Option<(A, B)>, x| {
618             let x_val = f(&x);
619             match max {
620                 None             => Some((x, x_val)),
621                 Some((y, y_val)) => if x_val > y_val {
622                     Some((x, x_val))
623                 } else {
624                     Some((y, y_val))
625                 }
626             }
627         }).map(|(x, _)| x)
628     }
629
630     /// Return the element that gives the minimum value from the
631     /// specified function.
632     ///
633     /// # Example
634     ///
635     /// ```rust
636     /// use core::num::SignedInt;
637     ///
638     /// let xs = [-3i, 0, 1, 5, -10];
639     /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
640     /// ```
641     #[inline]
642     #[unstable = "waiting for unboxed closures, just changed to take self by value"]
643     fn min_by<B: Ord>(self, f: |&A| -> B) -> Option<A> {
644         self.fold(None, |min: Option<(A, B)>, x| {
645             let x_val = f(&x);
646             match min {
647                 None             => Some((x, x_val)),
648                 Some((y, y_val)) => if x_val < y_val {
649                     Some((x, x_val))
650                 } else {
651                     Some((y, y_val))
652                 }
653             }
654         }).map(|(x, _)| x)
655     }
656 }
657
658 #[unstable = "trait is unstable"]
659 impl<A, I> IteratorExt<A> for I where I: Iterator<A> {}
660
661 /// A range iterator able to yield elements from both ends
662 ///
663 /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust
664 /// elements from the *same* range, and do not work independently of each other.
665 #[unstable = "recently split into two traits"]
666 pub trait DoubleEndedIterator<A>: Iterator<A> {
667     /// Yield an element from the end of the range, returning `None` if the range is empty.
668     fn next_back(&mut self) -> Option<A>;
669 }
670
671 /// Extension methods for double-ended iterators.
672 #[unstable = "new extension trait convention"]
673 pub trait DoubleEndedIteratorExt<A>: DoubleEndedIterator<A> {
674     /// Change the direction of the iterator
675     ///
676     /// The flipped iterator swaps the ends on an iterator that can already
677     /// be iterated from the front and from the back.
678     ///
679     ///
680     /// If the iterator also implements RandomAccessIterator, the flipped
681     /// iterator is also random access, with the indices starting at the back
682     /// of the original iterator.
683     ///
684     /// Note: Random access with flipped indices still only applies to the first
685     /// `uint::MAX` elements of the original iterator.
686     #[inline]
687     #[stable]
688     fn rev(self) -> Rev<Self> {
689         Rev{iter: self}
690     }
691 }
692
693 #[unstable = "trait is unstable"]
694 impl<A, I> DoubleEndedIteratorExt<A> for I where I: DoubleEndedIterator<A> {}
695
696 /// A double-ended iterator yielding mutable references
697 #[experimental = "not widely used"]
698 pub trait MutableDoubleEndedIterator {
699     // FIXME: #5898: should be called `reverse`
700     /// Use an iterator to reverse a container in-place
701     fn reverse_(&mut self);
702 }
703
704 #[experimental = "trait is experimental"]
705 impl<'a, A:'a, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T {
706     // FIXME: #5898: should be called `reverse`
707     /// Use an iterator to reverse a container in-place
708     fn reverse_(&mut self) {
709         loop {
710             match (self.next(), self.next_back()) {
711                 (Some(x), Some(y)) => mem::swap(x, y),
712                 _ => break
713             }
714         }
715     }
716 }
717
718
719 /// An object implementing random access indexing by `uint`
720 ///
721 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
722 /// Calling `next()` or `next_back()` on a `RandomAccessIterator`
723 /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)`
724 /// after `it.next()` is called.
725 #[experimental = "not widely used, may be better decomposed into Index and ExactSizeIterator"]
726 pub trait RandomAccessIterator<A>: Iterator<A> {
727     /// Return the number of indexable elements. At most `std::uint::MAX`
728     /// elements are indexable, even if the iterator represents a longer range.
729     fn indexable(&self) -> uint;
730
731     /// Return an element at an index, or `None` if the index is out of bounds
732     fn idx(&mut self, index: uint) -> Option<A>;
733 }
734
735 /// An iterator that knows its exact length
736 ///
737 /// This trait is a helper for iterators like the vector iterator, so that
738 /// it can support double-ended enumeration.
739 ///
740 /// `Iterator::size_hint` *must* return the exact size of the iterator.
741 /// Note that the size must fit in `uint`.
742 #[unstable = "could move DoubleEndedIterator bound onto rposition with method-level where clauses"]
743 pub trait ExactSizeIterator<A> : DoubleEndedIterator<A> {
744     /// Return the index of the last element satisfying the specified predicate
745     ///
746     /// If no element matches, None is returned.
747     #[inline]
748     fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> {
749         let len = self.len();
750         for i in range(0, len).rev() {
751             if predicate(self.next_back().expect("rposition: incorrect ExactSizeIterator")) {
752                 return Some(i);
753             }
754         }
755         None
756     }
757
758     #[inline]
759     /// Return the exact length of the iterator.
760     fn len(&self) -> uint {
761         let (lower, upper) = self.size_hint();
762         // Note: This assertion is overly defensive, but it checks the invariant
763         // guaranteed by the trait. If this trait were rust-internal,
764         // we could use debug_assert!; assert_eq! will check all Rust user
765         // implementations too.
766         assert_eq!(upper, Some(lower));
767         lower
768     }
769 }
770
771 // All adaptors that preserve the size of the wrapped iterator are fine
772 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
773 #[unstable = "trait is unstable"]
774 impl<A, T: ExactSizeIterator<A>> ExactSizeIterator<(uint, A)> for Enumerate<T> {}
775 #[unstable = "trait is unstable"]
776 impl<'a, A, T: ExactSizeIterator<A>> ExactSizeIterator<A> for Inspect<'a, A, T> {}
777 #[unstable = "trait is unstable"]
778 impl<A, T: ExactSizeIterator<A>> ExactSizeIterator<A> for Rev<T> {}
779 #[unstable = "trait is unstable"]
780 impl<'a, A, B, T: ExactSizeIterator<A>> ExactSizeIterator<B> for Map<'a, A, B, T> {}
781 #[unstable = "trait is unstable"]
782 impl<A, B, T, U> ExactSizeIterator<(A, B)> for Zip<T, U>
783     where T: ExactSizeIterator<A>, U: ExactSizeIterator<B> {}
784
785 /// An double-ended iterator with the direction inverted
786 #[deriving(Clone)]
787 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
788 #[stable]
789 pub struct Rev<T> {
790     iter: T
791 }
792
793 #[unstable = "trait is unstable"]
794 impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> {
795     #[inline]
796     fn next(&mut self) -> Option<A> { self.iter.next_back() }
797     #[inline]
798     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
799 }
800
801 #[unstable = "trait is unstable"]
802 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> {
803     #[inline]
804     fn next_back(&mut self) -> Option<A> { self.iter.next() }
805 }
806
807 #[experimental = "trait is experimental"]
808 impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
809     for Rev<T> {
810     #[inline]
811     fn indexable(&self) -> uint { self.iter.indexable() }
812     #[inline]
813     fn idx(&mut self, index: uint) -> Option<A> {
814         let amt = self.indexable();
815         self.iter.idx(amt - index - 1)
816     }
817 }
818
819 /// A mutable reference to an iterator
820 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
821 #[stable]
822 pub struct ByRef<'a, T:'a> {
823     iter: &'a mut T
824 }
825
826 #[unstable = "trait is unstable"]
827 impl<'a, A, T: Iterator<A>+'a> Iterator<A> for ByRef<'a, T> {
828     #[inline]
829     fn next(&mut self) -> Option<A> { self.iter.next() }
830     #[inline]
831     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
832 }
833
834 #[unstable = "trait is unstable"]
835 impl<'a, A, T: DoubleEndedIterator<A>+'a> DoubleEndedIterator<A> for ByRef<'a, T> {
836     #[inline]
837     fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
838 }
839
840 /// A trait for iterators over elements which can be added together
841 #[experimental = "needs to be re-evaluated as part of numerics reform"]
842 pub trait AdditiveIterator<A> {
843     /// Iterates over the entire iterator, summing up all the elements
844     ///
845     /// # Example
846     ///
847     /// ```rust
848     /// use std::iter::AdditiveIterator;
849     ///
850     /// let a = [1i, 2, 3, 4, 5];
851     /// let mut it = a.iter().map(|&x| x);
852     /// assert!(it.sum() == 15);
853     /// ```
854     fn sum(self) -> A;
855 }
856
857 macro_rules! impl_additive {
858     ($A:ty, $init:expr) => {
859         #[experimental = "trait is experimental"]
860         impl<T: Iterator<$A>> AdditiveIterator<$A> for T {
861             #[inline]
862             fn sum(self) -> $A {
863                 self.fold($init, |acc, x| acc + x)
864             }
865         }
866     };
867 }
868 impl_additive!(i8,   0)
869 impl_additive!(i16,  0)
870 impl_additive!(i32,  0)
871 impl_additive!(i64,  0)
872 impl_additive!(int,  0)
873 impl_additive!(u8,   0)
874 impl_additive!(u16,  0)
875 impl_additive!(u32,  0)
876 impl_additive!(u64,  0)
877 impl_additive!(uint, 0)
878 impl_additive!(f32,  0.0)
879 impl_additive!(f64,  0.0)
880
881 /// A trait for iterators over elements which can be multiplied together.
882 #[experimental = "needs to be re-evaluated as part of numerics reform"]
883 pub trait MultiplicativeIterator<A> {
884     /// Iterates over the entire iterator, multiplying all the elements
885     ///
886     /// # Example
887     ///
888     /// ```rust
889     /// use std::iter::{count, MultiplicativeIterator};
890     ///
891     /// fn factorial(n: uint) -> uint {
892     ///     count(1u, 1).take_while(|&i| i <= n).product()
893     /// }
894     /// assert!(factorial(0) == 1);
895     /// assert!(factorial(1) == 1);
896     /// assert!(factorial(5) == 120);
897     /// ```
898     fn product(self) -> A;
899 }
900
901 macro_rules! impl_multiplicative {
902     ($A:ty, $init:expr) => {
903         #[experimental = "trait is experimental"]
904         impl<T: Iterator<$A>> MultiplicativeIterator<$A> for T {
905             #[inline]
906             fn product(self) -> $A {
907                 self.fold($init, |acc, x| acc * x)
908             }
909         }
910     };
911 }
912 impl_multiplicative!(i8,   1)
913 impl_multiplicative!(i16,  1)
914 impl_multiplicative!(i32,  1)
915 impl_multiplicative!(i64,  1)
916 impl_multiplicative!(int,  1)
917 impl_multiplicative!(u8,   1)
918 impl_multiplicative!(u16,  1)
919 impl_multiplicative!(u32,  1)
920 impl_multiplicative!(u64,  1)
921 impl_multiplicative!(uint, 1)
922 impl_multiplicative!(f32,  1.0)
923 impl_multiplicative!(f64,  1.0)
924
925 /// A trait for iterators over elements which can be compared to one another.
926 #[unstable = "recently renamed for new extension trait conventions"]
927 pub trait IteratorOrdExt<A> {
928     /// Consumes the entire iterator to return the maximum element.
929     ///
930     /// # Example
931     ///
932     /// ```rust
933     /// let a = [1i, 2, 3, 4, 5];
934     /// assert!(a.iter().max().unwrap() == &5);
935     /// ```
936     fn max(self) -> Option<A>;
937
938     /// Consumes the entire iterator to return the minimum element.
939     ///
940     /// # Example
941     ///
942     /// ```rust
943     /// let a = [1i, 2, 3, 4, 5];
944     /// assert!(a.iter().min().unwrap() == &1);
945     /// ```
946     fn min(self) -> Option<A>;
947
948     /// `min_max` finds the minimum and maximum elements in the iterator.
949     ///
950     /// The return type `MinMaxResult` is an enum of three variants:
951     ///
952     /// - `NoElements` if the iterator is empty.
953     /// - `OneElement(x)` if the iterator has exactly one element.
954     /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
955     ///    values are equal if and only if there is more than one
956     ///    element in the iterator and all elements are equal.
957     ///
958     /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
959     /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons.
960     ///
961     /// # Example
962     ///
963     /// ```rust
964     /// use std::iter::{NoElements, OneElement, MinMax};
965     ///
966     /// let v: [int, ..0] = [];
967     /// assert_eq!(v.iter().min_max(), NoElements);
968     ///
969     /// let v = [1i];
970     /// assert!(v.iter().min_max() == OneElement(&1));
971     ///
972     /// let v = [1i, 2, 3, 4, 5];
973     /// assert!(v.iter().min_max() == MinMax(&1, &5));
974     ///
975     /// let v = [1i, 2, 3, 4, 5, 6];
976     /// assert!(v.iter().min_max() == MinMax(&1, &6));
977     ///
978     /// let v = [1i, 1, 1, 1];
979     /// assert!(v.iter().min_max() == MinMax(&1, &1));
980     /// ```
981     fn min_max(self) -> MinMaxResult<A>;
982 }
983
984 #[unstable = "trait is unstable"]
985 impl<A: Ord, T: Iterator<A>> IteratorOrdExt<A> for T {
986     #[inline]
987     fn max(self) -> Option<A> {
988         self.fold(None, |max, x| {
989             match max {
990                 None    => Some(x),
991                 Some(y) => Some(cmp::max(x, y))
992             }
993         })
994     }
995
996     #[inline]
997     fn min(self) -> Option<A> {
998         self.fold(None, |min, x| {
999             match min {
1000                 None    => Some(x),
1001                 Some(y) => Some(cmp::min(x, y))
1002             }
1003         })
1004     }
1005
1006     fn min_max(mut self) -> MinMaxResult<A> {
1007         let (mut min, mut max) = match self.next() {
1008             None => return NoElements,
1009             Some(x) => {
1010                 match self.next() {
1011                     None => return OneElement(x),
1012                     Some(y) => if x < y {(x, y)} else {(y,x)}
1013                 }
1014             }
1015         };
1016
1017         loop {
1018             // `first` and `second` are the two next elements we want to look at.
1019             // We first compare `first` and `second` (#1). The smaller one is then compared to
1020             // current minimum (#2). The larger one is compared to current maximum (#3). This
1021             // way we do 3 comparisons for 2 elements.
1022             let first = match self.next() {
1023                 None => break,
1024                 Some(x) => x
1025             };
1026             let second = match self.next() {
1027                 None => {
1028                     if first < min {
1029                         min = first;
1030                     } else if first > max {
1031                         max = first;
1032                     }
1033                     break;
1034                 }
1035                 Some(x) => x
1036             };
1037             if first < second {
1038                 if first < min {min = first;}
1039                 if max < second {max = second;}
1040             } else {
1041                 if second < min {min = second;}
1042                 if max < first {max = first;}
1043             }
1044         }
1045
1046         MinMax(min, max)
1047     }
1048 }
1049
1050 /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
1051 #[deriving(Clone, PartialEq, Show)]
1052 #[unstable = "waiting on namespaced enum conventions"]
1053 pub enum MinMaxResult<T> {
1054     /// Empty iterator
1055     NoElements,
1056
1057     /// Iterator with one element, so the minimum and maximum are the same
1058     OneElement(T),
1059
1060     /// More than one element in the iterator, the first element is not larger than the second
1061     MinMax(T, T)
1062 }
1063
1064 #[stable]
1065 impl<T: Clone> MinMaxResult<T> {
1066     /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1067     /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1068     /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1069     /// performing this operation will make one clone of `x`.
1070     ///
1071     /// # Example
1072     ///
1073     /// ```rust
1074     /// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
1075     ///
1076     /// let r: MinMaxResult<int> = NoElements;
1077     /// assert_eq!(r.into_option(), None)
1078     ///
1079     /// let r = OneElement(1i);
1080     /// assert_eq!(r.into_option(), Some((1,1)));
1081     ///
1082     /// let r = MinMax(1i,2i);
1083     /// assert_eq!(r.into_option(), Some((1,2)));
1084     /// ```
1085     pub fn into_option(self) -> Option<(T,T)> {
1086         match self {
1087             NoElements => None,
1088             OneElement(x) => Some((x.clone(), x)),
1089             MinMax(x, y) => Some((x, y))
1090         }
1091     }
1092 }
1093
1094 /// A trait for iterators that contain cloneable elements
1095 #[unstable = "recently renamed for extension trait conventions"]
1096 pub trait IteratorCloneExt<A> {
1097     /// Creates an iterator that clones the elements it yields. Useful for converting an
1098     /// Iterator<&T> to an Iterator<T>.
1099     fn cloned(self) -> Cloned<Self>;
1100 }
1101
1102 #[unstable = "trait is unstable"]
1103 impl<A: Clone, D: Deref<A>, I: Iterator<D>> IteratorCloneExt<A> for I {
1104     fn cloned(self) -> Cloned<I> {
1105         Cloned { it: self }
1106     }
1107 }
1108
1109 /// An iterator that clones the elements of an underlying iterator
1110 pub struct Cloned<I> {
1111     it: I,
1112 }
1113
1114 impl<A: Clone, D: Deref<A>, I: Iterator<D>> Iterator<A> for Cloned<I> {
1115     fn next(&mut self) -> Option<A> {
1116         self.it.next().cloned()
1117     }
1118
1119     fn size_hint(&self) -> (uint, Option<uint>) {
1120         self.it.size_hint()
1121     }
1122 }
1123
1124 impl<A: Clone, D: Deref<A>, I: DoubleEndedIterator<D>>
1125         DoubleEndedIterator<A> for Cloned<I> {
1126     fn next_back(&mut self) -> Option<A> {
1127         self.it.next_back().cloned()
1128     }
1129 }
1130
1131 #[unstable = "trait is unstable"]
1132 impl<A: Clone, D: Deref<A>, I: ExactSizeIterator<D>> ExactSizeIterator<A> for Cloned<I> {}
1133
1134 #[unstable = "recently renamed for extension trait conventions"]
1135 /// An extension trait for cloneable iterators.
1136 pub trait CloneIteratorExt {
1137     /// Repeats an iterator endlessly
1138     ///
1139     /// # Example
1140     ///
1141     /// ```rust
1142     /// use std::iter::{CloneIteratorExt, count};
1143     ///
1144     /// let a = count(1i,1i).take(1);
1145     /// let mut cy = a.cycle();
1146     /// assert_eq!(cy.next(), Some(1));
1147     /// assert_eq!(cy.next(), Some(1));
1148     /// ```
1149     #[stable]
1150     fn cycle(self) -> Cycle<Self>;
1151 }
1152
1153 impl<A, I> CloneIteratorExt for I where I: Iterator<A> + Clone {
1154     #[inline]
1155     fn cycle(self) -> Cycle<I> {
1156         Cycle{orig: self.clone(), iter: self}
1157     }
1158 }
1159
1160 /// An iterator that repeats endlessly
1161 #[deriving(Clone)]
1162 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1163 #[stable]
1164 pub struct Cycle<T> {
1165     orig: T,
1166     iter: T,
1167 }
1168
1169 #[unstable = "trait is unstable"]
1170 impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
1171     #[inline]
1172     fn next(&mut self) -> Option<A> {
1173         match self.iter.next() {
1174             None => { self.iter = self.orig.clone(); self.iter.next() }
1175             y => y
1176         }
1177     }
1178
1179     #[inline]
1180     fn size_hint(&self) -> (uint, Option<uint>) {
1181         // the cycle iterator is either empty or infinite
1182         match self.orig.size_hint() {
1183             sz @ (0, Some(0)) => sz,
1184             (0, _) => (0, None),
1185             _ => (uint::MAX, None)
1186         }
1187     }
1188 }
1189
1190 #[experimental = "trait is experimental"]
1191 impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
1192     #[inline]
1193     fn indexable(&self) -> uint {
1194         if self.orig.indexable() > 0 {
1195             uint::MAX
1196         } else {
1197             0
1198         }
1199     }
1200
1201     #[inline]
1202     fn idx(&mut self, index: uint) -> Option<A> {
1203         let liter = self.iter.indexable();
1204         let lorig = self.orig.indexable();
1205         if lorig == 0 {
1206             None
1207         } else if index < liter {
1208             self.iter.idx(index)
1209         } else {
1210             self.orig.idx((index - liter) % lorig)
1211         }
1212     }
1213 }
1214
1215 /// An iterator which strings two iterators together
1216 #[deriving(Clone)]
1217 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1218 #[stable]
1219 pub struct Chain<T, U> {
1220     a: T,
1221     b: U,
1222     flag: bool,
1223 }
1224
1225 #[unstable = "trait is unstable"]
1226 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
1227     #[inline]
1228     fn next(&mut self) -> Option<A> {
1229         if self.flag {
1230             self.b.next()
1231         } else {
1232             match self.a.next() {
1233                 Some(x) => return Some(x),
1234                 _ => ()
1235             }
1236             self.flag = true;
1237             self.b.next()
1238         }
1239     }
1240
1241     #[inline]
1242     fn size_hint(&self) -> (uint, Option<uint>) {
1243         let (a_lower, a_upper) = self.a.size_hint();
1244         let (b_lower, b_upper) = self.b.size_hint();
1245
1246         let lower = a_lower.saturating_add(b_lower);
1247
1248         let upper = match (a_upper, b_upper) {
1249             (Some(x), Some(y)) => x.checked_add(y),
1250             _ => None
1251         };
1252
1253         (lower, upper)
1254     }
1255 }
1256
1257 #[unstable = "trait is unstable"]
1258 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1259 for Chain<T, U> {
1260     #[inline]
1261     fn next_back(&mut self) -> Option<A> {
1262         match self.b.next_back() {
1263             Some(x) => Some(x),
1264             None => self.a.next_back()
1265         }
1266     }
1267 }
1268
1269 #[experimental = "trait is experimental"]
1270 impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
1271 for Chain<T, U> {
1272     #[inline]
1273     fn indexable(&self) -> uint {
1274         let (a, b) = (self.a.indexable(), self.b.indexable());
1275         a.saturating_add(b)
1276     }
1277
1278     #[inline]
1279     fn idx(&mut self, index: uint) -> Option<A> {
1280         let len = self.a.indexable();
1281         if index < len {
1282             self.a.idx(index)
1283         } else {
1284             self.b.idx(index - len)
1285         }
1286     }
1287 }
1288
1289 /// An iterator which iterates two other iterators simultaneously
1290 #[deriving(Clone)]
1291 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1292 #[stable]
1293 pub struct Zip<T, U> {
1294     a: T,
1295     b: U
1296 }
1297
1298 #[unstable = "trait is unstable"]
1299 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
1300     #[inline]
1301     fn next(&mut self) -> Option<(A, B)> {
1302         match self.a.next() {
1303             None => None,
1304             Some(x) => match self.b.next() {
1305                 None => None,
1306                 Some(y) => Some((x, y))
1307             }
1308         }
1309     }
1310
1311     #[inline]
1312     fn size_hint(&self) -> (uint, Option<uint>) {
1313         let (a_lower, a_upper) = self.a.size_hint();
1314         let (b_lower, b_upper) = self.b.size_hint();
1315
1316         let lower = cmp::min(a_lower, b_lower);
1317
1318         let upper = match (a_upper, b_upper) {
1319             (Some(x), Some(y)) => Some(cmp::min(x,y)),
1320             (Some(x), None) => Some(x),
1321             (None, Some(y)) => Some(y),
1322             (None, None) => None
1323         };
1324
1325         (lower, upper)
1326     }
1327 }
1328
1329 #[unstable = "trait is unstable"]
1330 impl<A, B, T: ExactSizeIterator<A>, U: ExactSizeIterator<B>> DoubleEndedIterator<(A, B)>
1331 for Zip<T, U> {
1332     #[inline]
1333     fn next_back(&mut self) -> Option<(A, B)> {
1334         let a_sz = self.a.len();
1335         let b_sz = self.b.len();
1336         if a_sz != b_sz {
1337             // Adjust a, b to equal length
1338             if a_sz > b_sz {
1339                 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1340             } else {
1341                 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1342             }
1343         }
1344         match (self.a.next_back(), self.b.next_back()) {
1345             (Some(x), Some(y)) => Some((x, y)),
1346             (None, None) => None,
1347             _ => unreachable!(),
1348         }
1349     }
1350 }
1351
1352 #[experimental = "trait is experimental"]
1353 impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
1354 RandomAccessIterator<(A, B)> for Zip<T, U> {
1355     #[inline]
1356     fn indexable(&self) -> uint {
1357         cmp::min(self.a.indexable(), self.b.indexable())
1358     }
1359
1360     #[inline]
1361     fn idx(&mut self, index: uint) -> Option<(A, B)> {
1362         match self.a.idx(index) {
1363             None => None,
1364             Some(x) => match self.b.idx(index) {
1365                 None => None,
1366                 Some(y) => Some((x, y))
1367             }
1368         }
1369     }
1370 }
1371
1372 /// An iterator which maps the values of `iter` with `f`
1373 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1374 #[stable]
1375 pub struct Map<'a, A, B, T> {
1376     iter: T,
1377     f: |A|: 'a -> B
1378 }
1379
1380 impl<'a, A, B, T> Map<'a, A, B, T> {
1381     #[inline]
1382     fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1383         match elt {
1384             Some(a) => Some((self.f)(a)),
1385             _ => None
1386         }
1387     }
1388 }
1389
1390 #[unstable = "trait is unstable"]
1391 impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> {
1392     #[inline]
1393     fn next(&mut self) -> Option<B> {
1394         let next = self.iter.next();
1395         self.do_map(next)
1396     }
1397
1398     #[inline]
1399     fn size_hint(&self) -> (uint, Option<uint>) {
1400         self.iter.size_hint()
1401     }
1402 }
1403
1404 #[unstable = "trait is unstable"]
1405 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> {
1406     #[inline]
1407     fn next_back(&mut self) -> Option<B> {
1408         let next = self.iter.next_back();
1409         self.do_map(next)
1410     }
1411 }
1412
1413 #[experimental = "trait is experimental"]
1414 impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> {
1415     #[inline]
1416     fn indexable(&self) -> uint {
1417         self.iter.indexable()
1418     }
1419
1420     #[inline]
1421     fn idx(&mut self, index: uint) -> Option<B> {
1422         let elt = self.iter.idx(index);
1423         self.do_map(elt)
1424     }
1425 }
1426
1427 /// An iterator which filters the elements of `iter` with `predicate`
1428 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1429 #[stable]
1430 pub struct Filter<'a, A, T> {
1431     iter: T,
1432     predicate: |&A|: 'a -> bool
1433 }
1434
1435 #[unstable = "trait is unstable"]
1436 impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> {
1437     #[inline]
1438     fn next(&mut self) -> Option<A> {
1439         for x in self.iter {
1440             if (self.predicate)(&x) {
1441                 return Some(x);
1442             } else {
1443                 continue
1444             }
1445         }
1446         None
1447     }
1448
1449     #[inline]
1450     fn size_hint(&self) -> (uint, Option<uint>) {
1451         let (_, upper) = self.iter.size_hint();
1452         (0, upper) // can't know a lower bound, due to the predicate
1453     }
1454 }
1455
1456 #[unstable = "trait is unstable"]
1457 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> {
1458     #[inline]
1459     fn next_back(&mut self) -> Option<A> {
1460         for x in self.iter.by_ref().rev() {
1461             if (self.predicate)(&x) {
1462                 return Some(x);
1463             }
1464         }
1465         None
1466     }
1467 }
1468
1469 /// An iterator which uses `f` to both filter and map elements from `iter`
1470 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1471 #[stable]
1472 pub struct FilterMap<'a, A, B, T> {
1473     iter: T,
1474     f: |A|: 'a -> Option<B>
1475 }
1476
1477 #[unstable = "trait is unstable"]
1478 impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> {
1479     #[inline]
1480     fn next(&mut self) -> Option<B> {
1481         for x in self.iter {
1482             match (self.f)(x) {
1483                 Some(y) => return Some(y),
1484                 None => ()
1485             }
1486         }
1487         None
1488     }
1489
1490     #[inline]
1491     fn size_hint(&self) -> (uint, Option<uint>) {
1492         let (_, upper) = self.iter.size_hint();
1493         (0, upper) // can't know a lower bound, due to the predicate
1494     }
1495 }
1496
1497 #[unstable = "trait is unstable"]
1498 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1499 for FilterMap<'a, A, B, T> {
1500     #[inline]
1501     fn next_back(&mut self) -> Option<B> {
1502         for x in self.iter.by_ref().rev() {
1503             match (self.f)(x) {
1504                 Some(y) => return Some(y),
1505                 None => ()
1506             }
1507         }
1508         None
1509     }
1510 }
1511
1512 /// An iterator which yields the current count and the element during iteration
1513 #[deriving(Clone)]
1514 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1515 #[stable]
1516 pub struct Enumerate<T> {
1517     iter: T,
1518     count: uint
1519 }
1520
1521 #[unstable = "trait is unstable"]
1522 impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1523     #[inline]
1524     fn next(&mut self) -> Option<(uint, A)> {
1525         match self.iter.next() {
1526             Some(a) => {
1527                 let ret = Some((self.count, a));
1528                 self.count += 1;
1529                 ret
1530             }
1531             _ => None
1532         }
1533     }
1534
1535     #[inline]
1536     fn size_hint(&self) -> (uint, Option<uint>) {
1537         self.iter.size_hint()
1538     }
1539 }
1540
1541 #[unstable = "trait is unstable"]
1542 impl<A, T: ExactSizeIterator<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
1543     #[inline]
1544     fn next_back(&mut self) -> Option<(uint, A)> {
1545         match self.iter.next_back() {
1546             Some(a) => {
1547                 let len = self.iter.len();
1548                 Some((self.count + len, a))
1549             }
1550             _ => None
1551         }
1552     }
1553 }
1554
1555 #[experimental = "trait is experimental"]
1556 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
1557     #[inline]
1558     fn indexable(&self) -> uint {
1559         self.iter.indexable()
1560     }
1561
1562     #[inline]
1563     fn idx(&mut self, index: uint) -> Option<(uint, A)> {
1564         match self.iter.idx(index) {
1565             Some(a) => Some((self.count + index, a)),
1566             _ => None,
1567         }
1568     }
1569 }
1570
1571 /// An iterator with a `peek()` that returns an optional reference to the next element.
1572 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1573 #[stable]
1574 pub struct Peekable<A, T> {
1575     iter: T,
1576     peeked: Option<A>,
1577 }
1578
1579 #[unstable = "trait is unstable"]
1580 impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
1581     #[inline]
1582     fn next(&mut self) -> Option<A> {
1583         if self.peeked.is_some() { self.peeked.take() }
1584         else { self.iter.next() }
1585     }
1586
1587     #[inline]
1588     fn size_hint(&self) -> (uint, Option<uint>) {
1589         let (lo, hi) = self.iter.size_hint();
1590         if self.peeked.is_some() {
1591             let lo = lo.saturating_add(1);
1592             let hi = match hi {
1593                 Some(x) => x.checked_add(1),
1594                 None => None
1595             };
1596             (lo, hi)
1597         } else {
1598             (lo, hi)
1599         }
1600     }
1601 }
1602
1603 #[stable]
1604 impl<'a, A, T: Iterator<A>> Peekable<A, T> {
1605     /// Return a reference to the next element of the iterator with out advancing it,
1606     /// or None if the iterator is exhausted.
1607     #[inline]
1608     pub fn peek(&'a mut self) -> Option<&'a A> {
1609         if self.peeked.is_none() {
1610             self.peeked = self.iter.next();
1611         }
1612         match self.peeked {
1613             Some(ref value) => Some(value),
1614             None => None,
1615         }
1616     }
1617
1618     /// Check whether peekable iterator is empty or not.
1619     #[inline]
1620     pub fn is_empty(&mut self) -> bool {
1621         self.peek().is_none()
1622     }
1623 }
1624
1625 /// An iterator which rejects elements while `predicate` is true
1626 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1627 #[stable]
1628 pub struct SkipWhile<'a, A, T> {
1629     iter: T,
1630     flag: bool,
1631     predicate: |&A|: 'a -> bool
1632 }
1633
1634 #[unstable = "trait is unstable"]
1635 impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> {
1636     #[inline]
1637     fn next(&mut self) -> Option<A> {
1638         for x in self.iter {
1639             if self.flag || !(self.predicate)(&x) {
1640                 self.flag = true;
1641                 return Some(x);
1642             }
1643         }
1644         None
1645     }
1646
1647     #[inline]
1648     fn size_hint(&self) -> (uint, Option<uint>) {
1649         let (_, upper) = self.iter.size_hint();
1650         (0, upper) // can't know a lower bound, due to the predicate
1651     }
1652 }
1653
1654 /// An iterator which only accepts elements while `predicate` is true
1655 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1656 #[stable]
1657 pub struct TakeWhile<'a, A, T> {
1658     iter: T,
1659     flag: bool,
1660     predicate: |&A|: 'a -> bool
1661 }
1662
1663 #[unstable = "trait is unstable"]
1664 impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> {
1665     #[inline]
1666     fn next(&mut self) -> Option<A> {
1667         if self.flag {
1668             None
1669         } else {
1670             match self.iter.next() {
1671                 Some(x) => {
1672                     if (self.predicate)(&x) {
1673                         Some(x)
1674                     } else {
1675                         self.flag = true;
1676                         None
1677                     }
1678                 }
1679                 None => None
1680             }
1681         }
1682     }
1683
1684     #[inline]
1685     fn size_hint(&self) -> (uint, Option<uint>) {
1686         let (_, upper) = self.iter.size_hint();
1687         (0, upper) // can't know a lower bound, due to the predicate
1688     }
1689 }
1690
1691 /// An iterator which skips over `n` elements of `iter`.
1692 #[deriving(Clone)]
1693 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1694 #[stable]
1695 pub struct Skip<T> {
1696     iter: T,
1697     n: uint
1698 }
1699
1700 #[unstable = "trait is unstable"]
1701 impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
1702     #[inline]
1703     fn next(&mut self) -> Option<A> {
1704         let mut next = self.iter.next();
1705         if self.n == 0 {
1706             next
1707         } else {
1708             let mut n = self.n;
1709             while n > 0 {
1710                 n -= 1;
1711                 match next {
1712                     Some(_) => {
1713                         next = self.iter.next();
1714                         continue
1715                     }
1716                     None => {
1717                         self.n = 0;
1718                         return None
1719                     }
1720                 }
1721             }
1722             self.n = 0;
1723             next
1724         }
1725     }
1726
1727     #[inline]
1728     fn size_hint(&self) -> (uint, Option<uint>) {
1729         let (lower, upper) = self.iter.size_hint();
1730
1731         let lower = lower.saturating_sub(self.n);
1732
1733         let upper = match upper {
1734             Some(x) => Some(x.saturating_sub(self.n)),
1735             None => None
1736         };
1737
1738         (lower, upper)
1739     }
1740 }
1741
1742 #[experimental = "trait is experimental"]
1743 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
1744     #[inline]
1745     fn indexable(&self) -> uint {
1746         self.iter.indexable().saturating_sub(self.n)
1747     }
1748
1749     #[inline]
1750     fn idx(&mut self, index: uint) -> Option<A> {
1751         if index >= self.indexable() {
1752             None
1753         } else {
1754             self.iter.idx(index + self.n)
1755         }
1756     }
1757 }
1758
1759 /// An iterator which only iterates over the first `n` iterations of `iter`.
1760 #[deriving(Clone)]
1761 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1762 #[stable]
1763 pub struct Take<T> {
1764     iter: T,
1765     n: uint
1766 }
1767
1768 #[unstable = "trait is unstable"]
1769 impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
1770     #[inline]
1771     fn next(&mut self) -> Option<A> {
1772         if self.n != 0 {
1773             self.n -= 1;
1774             self.iter.next()
1775         } else {
1776             None
1777         }
1778     }
1779
1780     #[inline]
1781     fn size_hint(&self) -> (uint, Option<uint>) {
1782         let (lower, upper) = self.iter.size_hint();
1783
1784         let lower = cmp::min(lower, self.n);
1785
1786         let upper = match upper {
1787             Some(x) if x < self.n => Some(x),
1788             _ => Some(self.n)
1789         };
1790
1791         (lower, upper)
1792     }
1793 }
1794
1795 #[experimental = "trait is experimental"]
1796 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
1797     #[inline]
1798     fn indexable(&self) -> uint {
1799         cmp::min(self.iter.indexable(), self.n)
1800     }
1801
1802     #[inline]
1803     fn idx(&mut self, index: uint) -> Option<A> {
1804         if index >= self.n {
1805             None
1806         } else {
1807             self.iter.idx(index)
1808         }
1809     }
1810 }
1811
1812
1813 /// An iterator to maintain state while iterating another iterator
1814 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1815 #[unstable = "waiting for unboxed closures"]
1816 pub struct Scan<'a, A, B, T, St> {
1817     iter: T,
1818     f: |&mut St, A|: 'a -> Option<B>,
1819
1820     /// The current internal state to be passed to the closure next.
1821     pub state: St,
1822 }
1823
1824 #[unstable = "trait is unstable"]
1825 impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> {
1826     #[inline]
1827     fn next(&mut self) -> Option<B> {
1828         self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1829     }
1830
1831     #[inline]
1832     fn size_hint(&self) -> (uint, Option<uint>) {
1833         let (_, upper) = self.iter.size_hint();
1834         (0, upper) // can't know a lower bound, due to the scan function
1835     }
1836 }
1837
1838 /// An iterator that maps each element to an iterator,
1839 /// and yields the elements of the produced iterators
1840 ///
1841 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1842 #[unstable = "waiting for unboxed closures"]
1843 pub struct FlatMap<'a, A, T, U> {
1844     iter: T,
1845     f: |A|: 'a -> U,
1846     frontiter: Option<U>,
1847     backiter: Option<U>,
1848 }
1849
1850 #[unstable = "trait is unstable"]
1851 impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> {
1852     #[inline]
1853     fn next(&mut self) -> Option<B> {
1854         loop {
1855             for inner in self.frontiter.iter_mut() {
1856                 for x in *inner {
1857                     return Some(x)
1858                 }
1859             }
1860             match self.iter.next().map(|x| (self.f)(x)) {
1861                 None => return self.backiter.as_mut().and_then(|it| it.next()),
1862                 next => self.frontiter = next,
1863             }
1864         }
1865     }
1866
1867     #[inline]
1868     fn size_hint(&self) -> (uint, Option<uint>) {
1869         let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1870         let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1871         let lo = flo.saturating_add(blo);
1872         match (self.iter.size_hint(), fhi, bhi) {
1873             ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1874             _ => (lo, None)
1875         }
1876     }
1877 }
1878
1879 #[unstable = "trait is unstable"]
1880 impl<'a,
1881      A, T: DoubleEndedIterator<A>,
1882      B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
1883      for FlatMap<'a, A, T, U> {
1884     #[inline]
1885     fn next_back(&mut self) -> Option<B> {
1886         loop {
1887             for inner in self.backiter.iter_mut() {
1888                 match inner.next_back() {
1889                     None => (),
1890                     y => return y
1891                 }
1892             }
1893             match self.iter.next_back().map(|x| (self.f)(x)) {
1894                 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1895                 next => self.backiter = next,
1896             }
1897         }
1898     }
1899 }
1900
1901 /// An iterator that yields `None` forever after the underlying iterator
1902 /// yields `None` once.
1903 #[deriving(Clone)]
1904 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1905 #[stable]
1906 pub struct Fuse<T> {
1907     iter: T,
1908     done: bool
1909 }
1910
1911 #[unstable = "trait is unstable"]
1912 impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
1913     #[inline]
1914     fn next(&mut self) -> Option<A> {
1915         if self.done {
1916             None
1917         } else {
1918             match self.iter.next() {
1919                 None => {
1920                     self.done = true;
1921                     None
1922                 }
1923                 x => x
1924             }
1925         }
1926     }
1927
1928     #[inline]
1929     fn size_hint(&self) -> (uint, Option<uint>) {
1930         if self.done {
1931             (0, Some(0))
1932         } else {
1933             self.iter.size_hint()
1934         }
1935     }
1936 }
1937
1938 #[unstable = "trait is unstable"]
1939 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
1940     #[inline]
1941     fn next_back(&mut self) -> Option<A> {
1942         if self.done {
1943             None
1944         } else {
1945             match self.iter.next_back() {
1946                 None => {
1947                     self.done = true;
1948                     None
1949                 }
1950                 x => x
1951             }
1952         }
1953     }
1954 }
1955
1956 // Allow RandomAccessIterators to be fused without affecting random-access behavior
1957 #[experimental = "trait is experimental"]
1958 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
1959     #[inline]
1960     fn indexable(&self) -> uint {
1961         self.iter.indexable()
1962     }
1963
1964     #[inline]
1965     fn idx(&mut self, index: uint) -> Option<A> {
1966         self.iter.idx(index)
1967     }
1968 }
1969
1970 #[experimental = "seems marginal"]
1971 impl<T> Fuse<T> {
1972     /// Resets the fuse such that the next call to .next() or .next_back() will
1973     /// call the underlying iterator again even if it previously returned None.
1974     #[inline]
1975     pub fn reset_fuse(&mut self) {
1976         self.done = false
1977     }
1978 }
1979
1980 /// An iterator that calls a function with a reference to each
1981 /// element before yielding it.
1982 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1983 #[unstable = "waiting for unboxed closures"]
1984 pub struct Inspect<'a, A, T> {
1985     iter: T,
1986     f: |&A|: 'a
1987 }
1988
1989 impl<'a, A, T> Inspect<'a, A, T> {
1990     #[inline]
1991     fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
1992         match elt {
1993             Some(ref a) => (self.f)(a),
1994             None => ()
1995         }
1996
1997         elt
1998     }
1999 }
2000
2001 #[unstable = "trait is unstable"]
2002 impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> {
2003     #[inline]
2004     fn next(&mut self) -> Option<A> {
2005         let next = self.iter.next();
2006         self.do_inspect(next)
2007     }
2008
2009     #[inline]
2010     fn size_hint(&self) -> (uint, Option<uint>) {
2011         self.iter.size_hint()
2012     }
2013 }
2014
2015 #[unstable = "trait is unstable"]
2016 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
2017 for Inspect<'a, A, T> {
2018     #[inline]
2019     fn next_back(&mut self) -> Option<A> {
2020         let next = self.iter.next_back();
2021         self.do_inspect(next)
2022     }
2023 }
2024
2025 #[experimental = "trait is experimental"]
2026 impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
2027 for Inspect<'a, A, T> {
2028     #[inline]
2029     fn indexable(&self) -> uint {
2030         self.iter.indexable()
2031     }
2032
2033     #[inline]
2034     fn idx(&mut self, index: uint) -> Option<A> {
2035         let element = self.iter.idx(index);
2036         self.do_inspect(element)
2037     }
2038 }
2039
2040 /// An iterator which passes mutable state to a closure and yields the result.
2041 ///
2042 /// # Example: The Fibonacci Sequence
2043 ///
2044 /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2045 ///
2046 /// ```rust
2047 /// use std::iter::Unfold;
2048 /// use std::num::Int; // For `.checked_add()`
2049 ///
2050 /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2051 /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2052 /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&(ref mut x2, ref mut x1)| {
2053 ///     // Attempt to get the next Fibonacci number
2054 ///     // `x1` will be `None` if previously overflowed.
2055 ///     let next = match (*x2, *x1) {
2056 ///         (Some(x2), Some(x1)) => x2.checked_add(x1),
2057 ///         _ => None,
2058 ///     };
2059 ///
2060 ///     // Shift left: ret <- x2 <- x1 <- next
2061 ///     let ret = *x2;
2062 ///     *x2 = *x1;
2063 ///     *x1 = next;
2064 ///
2065 ///     ret
2066 /// });
2067 ///
2068 /// for i in fibonacci {
2069 ///     println!("{}", i);
2070 /// }
2071 /// ```
2072 #[experimental]
2073 pub struct Unfold<'a, A, St> {
2074     f: |&mut St|: 'a -> Option<A>,
2075     /// Internal state that will be passed to the closure on the next iteration
2076     pub state: St,
2077 }
2078
2079 #[experimental]
2080 impl<'a, A, St> Unfold<'a, A, St> {
2081     /// Creates a new iterator with the specified closure as the "iterator
2082     /// function" and an initial state to eventually pass to the closure
2083     #[inline]
2084     pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option<A>)
2085                -> Unfold<'a, A, St> {
2086         Unfold {
2087             f: f,
2088             state: initial_state
2089         }
2090     }
2091 }
2092
2093 #[experimental]
2094 impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> {
2095     #[inline]
2096     fn next(&mut self) -> Option<A> {
2097         (self.f)(&mut self.state)
2098     }
2099
2100     #[inline]
2101     fn size_hint(&self) -> (uint, Option<uint>) {
2102         // no possible known bounds at this point
2103         (0, None)
2104     }
2105 }
2106
2107 /// An infinite iterator starting at `start` and advancing by `step` with each
2108 /// iteration
2109 #[deriving(Clone)]
2110 #[unstable = "may be renamed"]
2111 pub struct Counter<A> {
2112     /// The current state the counter is at (next value to be yielded)
2113     state: A,
2114     /// The amount that this iterator is stepping by
2115     step: A,
2116 }
2117
2118 /// Creates a new counter with the specified start/step
2119 #[inline]
2120 #[unstable = "may be renamed"]
2121 pub fn count<A>(start: A, step: A) -> Counter<A> {
2122     Counter{state: start, step: step}
2123 }
2124
2125 #[unstable = "trait is unstable"]
2126 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
2127     #[inline]
2128     fn next(&mut self) -> Option<A> {
2129         let result = self.state.clone();
2130         self.state = self.state + self.step;
2131         Some(result)
2132     }
2133
2134     #[inline]
2135     fn size_hint(&self) -> (uint, Option<uint>) {
2136         (uint::MAX, None) // Too bad we can't specify an infinite lower bound
2137     }
2138 }
2139
2140 /// An iterator over the range [start, stop)
2141 #[deriving(Clone)]
2142 #[unstable = "may be refactored due to numerics reform or ops reform"]
2143 pub struct Range<A> {
2144     state: A,
2145     stop: A,
2146     one: A,
2147 }
2148
2149 /// Returns an iterator over the given range [start, stop) (that is, starting
2150 /// at start (inclusive), and ending at stop (exclusive)).
2151 ///
2152 /// # Example
2153 ///
2154 /// ```rust
2155 /// let array = [0, 1, 2, 3, 4];
2156 ///
2157 /// for i in range(0, 5u) {
2158 ///     println!("{}", i);
2159 ///     assert_eq!(i,  array[i]);
2160 /// }
2161 /// ```
2162 #[inline]
2163 pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
2164     Range {
2165         state: start,
2166         stop: stop,
2167         one: Int::one(),
2168     }
2169 }
2170
2171 // FIXME: #10414: Unfortunate type bound
2172 #[unstable = "trait is unstable"]
2173 impl<A: Int + ToPrimitive> Iterator<A> for Range<A> {
2174     #[inline]
2175     fn next(&mut self) -> Option<A> {
2176         if self.state < self.stop {
2177             let result = self.state.clone();
2178             self.state = self.state + self.one;
2179             Some(result)
2180         } else {
2181             None
2182         }
2183     }
2184
2185     #[inline]
2186     fn size_hint(&self) -> (uint, Option<uint>) {
2187         // This first checks if the elements are representable as i64. If they aren't, try u64 (to
2188         // handle cases like range(huge, huger)). We don't use uint/int because the difference of
2189         // the i64/u64 might lie within their range.
2190         let bound = match self.state.to_i64() {
2191             Some(a) => {
2192                 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
2193                 match sz {
2194                     Some(Some(bound)) => bound.to_uint(),
2195                     _ => None,
2196                 }
2197             },
2198             None => match self.state.to_u64() {
2199                 Some(a) => {
2200                     let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
2201                     match sz {
2202                         Some(Some(bound)) => bound.to_uint(),
2203                         _ => None
2204                     }
2205                 },
2206                 None => None
2207             }
2208         };
2209
2210         match bound {
2211             Some(b) => (b, Some(b)),
2212             // Standard fallback for unbounded/unrepresentable bounds
2213             None => (0, None)
2214         }
2215     }
2216 }
2217
2218 /// `Int` is required to ensure the range will be the same regardless of
2219 /// the direction it is consumed.
2220 #[unstable = "trait is unstable"]
2221 impl<A: Int + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
2222     #[inline]
2223     fn next_back(&mut self) -> Option<A> {
2224         if self.stop > self.state {
2225             self.stop = self.stop - self.one;
2226             Some(self.stop.clone())
2227         } else {
2228             None
2229         }
2230     }
2231 }
2232
2233 /// An iterator over the range [start, stop]
2234 #[deriving(Clone)]
2235 #[unstable = "may be refactored due to numerics reform or ops reform"]
2236 pub struct RangeInclusive<A> {
2237     range: Range<A>,
2238     done: bool,
2239 }
2240
2241 /// Return an iterator over the range [start, stop]
2242 #[inline]
2243 #[unstable = "may be refactored due to numerics reform or ops reform"]
2244 pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
2245     RangeInclusive {
2246         range: range(start, stop),
2247         done: false,
2248     }
2249 }
2250
2251 #[unstable = "trait is unstable"]
2252 impl<A: Int + ToPrimitive> Iterator<A> for RangeInclusive<A> {
2253     #[inline]
2254     fn next(&mut self) -> Option<A> {
2255         match self.range.next() {
2256             Some(x) => Some(x),
2257             None => {
2258                 if !self.done && self.range.state == self.range.stop {
2259                     self.done = true;
2260                     Some(self.range.stop.clone())
2261                 } else {
2262                     None
2263                 }
2264             }
2265         }
2266     }
2267
2268     #[inline]
2269     fn size_hint(&self) -> (uint, Option<uint>) {
2270         let (lo, hi) = self.range.size_hint();
2271         if self.done {
2272             (lo, hi)
2273         } else {
2274             let lo = lo.saturating_add(1);
2275             let hi = match hi {
2276                 Some(x) => x.checked_add(1),
2277                 None => None
2278             };
2279             (lo, hi)
2280         }
2281     }
2282 }
2283
2284 #[unstable = "trait is unstable"]
2285 impl<A: Int + ToPrimitive> DoubleEndedIterator<A> for RangeInclusive<A> {
2286     #[inline]
2287     fn next_back(&mut self) -> Option<A> {
2288         if self.range.stop > self.range.state {
2289             let result = self.range.stop.clone();
2290             self.range.stop = self.range.stop - self.range.one;
2291             Some(result)
2292         } else if !self.done && self.range.state == self.range.stop {
2293             self.done = true;
2294             Some(self.range.stop.clone())
2295         } else {
2296             None
2297         }
2298     }
2299 }
2300
2301 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2302 #[deriving(Clone)]
2303 #[unstable = "may be refactored due to numerics reform or ops reform"]
2304 pub struct RangeStep<A> {
2305     state: A,
2306     stop: A,
2307     step: A,
2308     rev: bool,
2309 }
2310
2311 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2312 #[inline]
2313 #[unstable = "may be refactored due to numerics reform or ops reform"]
2314 pub fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
2315     let rev = step < Int::zero();
2316     RangeStep{state: start, stop: stop, step: step, rev: rev}
2317 }
2318
2319 #[unstable = "trait is unstable"]
2320 impl<A: Int> Iterator<A> for RangeStep<A> {
2321     #[inline]
2322     fn next(&mut self) -> Option<A> {
2323         if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2324             let result = self.state;
2325             match self.state.checked_add(self.step) {
2326                 Some(x) => self.state = x,
2327                 None => self.state = self.stop.clone()
2328             }
2329             Some(result)
2330         } else {
2331             None
2332         }
2333     }
2334 }
2335
2336 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2337 #[deriving(Clone)]
2338 #[unstable = "may be refactored due to numerics reform or ops reform"]
2339 pub struct RangeStepInclusive<A> {
2340     state: A,
2341     stop: A,
2342     step: A,
2343     rev: bool,
2344     done: bool,
2345 }
2346
2347 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2348 #[inline]
2349 #[unstable = "may be refactored due to numerics reform or ops reform"]
2350 pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
2351     let rev = step < Int::zero();
2352     RangeStepInclusive {
2353         state: start,
2354         stop: stop,
2355         step: step,
2356         rev: rev,
2357         done: false,
2358     }
2359 }
2360
2361 #[unstable = "trait is unstable"]
2362 impl<A: Int> Iterator<A> for RangeStepInclusive<A> {
2363     #[inline]
2364     fn next(&mut self) -> Option<A> {
2365         if !self.done && ((self.rev && self.state >= self.stop) ||
2366                           (!self.rev && self.state <= self.stop)) {
2367             let result = self.state;
2368             match self.state.checked_add(self.step) {
2369                 Some(x) => self.state = x,
2370                 None => self.done = true
2371             }
2372             Some(result)
2373         } else {
2374             None
2375         }
2376     }
2377 }
2378
2379 /// An iterator that repeats an element endlessly
2380 #[deriving(Clone)]
2381 #[stable]
2382 pub struct Repeat<A> {
2383     element: A
2384 }
2385
2386 impl<A: Clone> Repeat<A> {
2387     /// Create a new `Repeat` that endlessly repeats the element `elt`.
2388     #[inline]
2389     #[deprecated = "use iter::repeat instead"]
2390     pub fn new(elt: A) -> Repeat<A> {
2391         Repeat{element: elt}
2392     }
2393 }
2394
2395 #[unstable = "trait is unstable"]
2396 impl<A: Clone> Iterator<A> for Repeat<A> {
2397     #[inline]
2398     fn next(&mut self) -> Option<A> { self.idx(0) }
2399     #[inline]
2400     fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2401 }
2402
2403 #[unstable = "trait is unstable"]
2404 impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
2405     #[inline]
2406     fn next_back(&mut self) -> Option<A> { self.idx(0) }
2407 }
2408
2409 #[experimental = "trait is experimental"]
2410 impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
2411     #[inline]
2412     fn indexable(&self) -> uint { uint::MAX }
2413     #[inline]
2414     fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
2415 }
2416
2417 type IterateState<'a, T> = (|T|: 'a -> T, Option<T>, bool);
2418
2419 /// An iterator that repeatedly applies a given function, starting
2420 /// from a given seed value.
2421 #[experimental]
2422 pub type Iterate<'a, T> = Unfold<'a, T, IterateState<'a, T>>;
2423
2424 /// Create a new iterator that produces an infinite sequence of
2425 /// repeated applications of the given function `f`.
2426 #[experimental]
2427 pub fn iterate<'a, T: Clone>(seed: T, f: |T|: 'a -> T) -> Iterate<'a, T> {
2428     Unfold::new((f, Some(seed), true), |st| {
2429         let &(ref mut f, ref mut val, ref mut first) = st;
2430         if *first {
2431             *first = false;
2432         } else {
2433             match val.take() {
2434                 Some(x) => {
2435                     *val = Some((*f)(x))
2436                 }
2437                 None => {}
2438             }
2439         }
2440         val.clone()
2441     })
2442 }
2443
2444 /// Create a new iterator that endlessly repeats the element `elt`.
2445 #[inline]
2446 #[stable]
2447 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
2448     Repeat{element: elt}
2449 }
2450
2451 /// Functions for lexicographical ordering of sequences.
2452 ///
2453 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2454 /// that the elements implement both `PartialEq` and `PartialOrd`.
2455 ///
2456 /// If two sequences are equal up until the point where one ends,
2457 /// the shorter sequence compares less.
2458 #[experimental = "likely to be removed after cmp reform"]
2459 pub mod order {
2460     use cmp;
2461     use cmp::{Eq, Ord, PartialOrd, PartialEq};
2462     use cmp::Ordering::{Equal, Less, Greater};
2463     use option::Option;
2464     use option::Option::{Some, None};
2465     use super::Iterator;
2466
2467     /// Compare `a` and `b` for equality using `Eq`
2468     pub fn equals<A: Eq, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2469         loop {
2470             match (a.next(), b.next()) {
2471                 (None, None) => return true,
2472                 (None, _) | (_, None) => return false,
2473                 (Some(x), Some(y)) => if x != y { return false },
2474             }
2475         }
2476     }
2477
2478     /// Order `a` and `b` lexicographically using `Ord`
2479     pub fn cmp<A: Ord, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> cmp::Ordering {
2480         loop {
2481             match (a.next(), b.next()) {
2482                 (None, None) => return Equal,
2483                 (None, _   ) => return Less,
2484                 (_   , None) => return Greater,
2485                 (Some(x), Some(y)) => match x.cmp(&y) {
2486                     Equal => (),
2487                     non_eq => return non_eq,
2488                 },
2489             }
2490         }
2491     }
2492
2493     /// Order `a` and `b` lexicographically using `PartialOrd`
2494     pub fn partial_cmp<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S)
2495             -> Option<cmp::Ordering> {
2496         loop {
2497             match (a.next(), b.next()) {
2498                 (None, None) => return Some(Equal),
2499                 (None, _   ) => return Some(Less),
2500                 (_   , None) => return Some(Greater),
2501                 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2502                     Some(Equal) => (),
2503                     non_eq => return non_eq,
2504                 },
2505             }
2506         }
2507     }
2508
2509     /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
2510     pub fn eq<A, B, L, R>(mut a: L, mut b: R) -> bool where
2511         A: PartialEq<B>,
2512         L: Iterator<A>,
2513         R: Iterator<B>,
2514     {
2515         loop {
2516             match (a.next(), b.next()) {
2517                 (None, None) => return true,
2518                 (None, _) | (_, None) => return false,
2519                 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2520             }
2521         }
2522     }
2523
2524     /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`)
2525     pub fn ne<A, B, L, R>(mut a: L, mut b: R) -> bool where
2526         A: PartialEq<B>,
2527         L: Iterator<A>,
2528         R: Iterator<B>,
2529     {
2530         loop {
2531             match (a.next(), b.next()) {
2532                 (None, None) => return false,
2533                 (None, _) | (_, None) => return true,
2534                 (Some(x), Some(y)) => if x.ne(&y) { return true },
2535             }
2536         }
2537     }
2538
2539     /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`)
2540     pub fn lt<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2541         loop {
2542             match (a.next(), b.next()) {
2543                 (None, None) => return false,
2544                 (None, _   ) => return true,
2545                 (_   , None) => return false,
2546                 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2547             }
2548         }
2549     }
2550
2551     /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
2552     pub fn le<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2553         loop {
2554             match (a.next(), b.next()) {
2555                 (None, None) => return true,
2556                 (None, _   ) => return true,
2557                 (_   , None) => return false,
2558                 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2559             }
2560         }
2561     }
2562
2563     /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`)
2564     pub fn gt<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2565         loop {
2566             match (a.next(), b.next()) {
2567                 (None, None) => return false,
2568                 (None, _   ) => return false,
2569                 (_   , None) => return true,
2570                 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2571             }
2572         }
2573     }
2574
2575     /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
2576     pub fn ge<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2577         loop {
2578             match (a.next(), b.next()) {
2579                 (None, None) => return true,
2580                 (None, _   ) => return false,
2581                 (_   , None) => return true,
2582                 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },
2583             }
2584         }
2585     }
2586 }