iter.rs 80.7 KB
Newer Older
D
Daniel Micay 已提交
1 2 3 4 5 6 7 8 9 10
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11
/*!
12

13
Composable external iterators
14

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
# The `Iterator` trait

This module defines Rust's core iteration trait. The `Iterator` trait has one
un-implemented method, `next`. All other methods are derived through default
methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.

The goal of this module is to unify iteration across all containers in Rust.
An iterator can be considered as a state machine which is used to track which
element will be yielded next.

There are various extensions also defined in this module to assist with various
types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
the `FromIterator` trait for creating a container from an iterator, and much
more.

## Rust's `for` loop

The special syntax used by rust's `for` loop is based around the `Iterator`
trait defined in this module. For loops can be viewed as a syntactical expansion
into a `loop`, for example, the `for` loop in this example is essentially
translated to the `loop` below.

37
```rust
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
let values = ~[1, 2, 3];

// "Syntactical sugar" taking advantage of an iterator
for &x in values.iter() {
    println!("{}", x);
}

// Rough translation of the iteration without a `for` iterator.
let mut it = values.iter();
loop {
    match it.next() {
        Some(&x) => {
            println!("{}", x);
        }
        None => { break }
    }
}
55
 ```
56 57 58 59 60 61 62 63

This `for` loop syntax can be applied to any iterator over any type.

## Iteration protocol and more

More detailed information about iterators can be found in the [container
tutorial](http://static.rust-lang.org/doc/master/tutorial-container.html) with
the rest of the rust manuals.
64 65

*/
D
Daniel Micay 已提交
66

67
use cmp;
68
use num::{Zero, One, Integer, CheckedAdd, CheckedSub, Saturating};
M
Fixups  
Marvin Löbel 已提交
69
use option::{Option, Some, None};
70
use ops::{Add, Mul, Sub};
71
use cmp::{Eq, Ord};
M
Fixups  
Marvin Löbel 已提交
72
use clone::Clone;
73
use uint;
74
use util;
D
Daniel Micay 已提交
75

76
/// Conversion from an `Iterator`
77
pub trait FromIterator<A> {
78
    /// Build a container with elements from an external iterator.
79
    fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> Self;
80 81
}

D
Daniel Micay 已提交
82
/// A type growable from an `Iterator` implementation
83
pub trait Extendable<A>: FromIterator<A> {
D
Daniel Micay 已提交
84
    /// Extend a container with the elements yielded by an iterator
85
    fn extend<T: Iterator<A>>(&mut self, iterator: &mut T);
D
Daniel Micay 已提交
86 87
}

88 89 90
/// An interface for dealing with "external iterators". These types of iterators
/// can be resumed at any time as all state is stored internally as opposed to
/// being located on the call stack.
91 92 93 94 95 96 97
///
/// The Iterator protocol states that an iterator yields a (potentially-empty,
/// potentially-infinite) sequence of values, and returns `None` to signal that
/// it's finished. The Iterator protocol does not define behavior after `None`
/// is returned. A concrete Iterator implementation may choose to behave however
/// it wishes, either by returning `None` infinitely, or by doing something
/// else.
98
pub trait Iterator<A> {
D
Daniel Micay 已提交
99
    /// Advance the iterator and return the next value. Return `None` when the end is reached.
100
    fn next(&mut self) -> Option<A>;
101 102 103 104

    /// Return a lower bound and upper bound on the remaining length of the iterator.
    ///
    /// The common use case for the estimate is pre-allocating space to store the results.
105
    #[inline]
106
    fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
107

R
Ron Dahlgren 已提交
108
    /// Chain this iterator with another, returning a new iterator which will
109 110 111 112 113
    /// finish iterating over the current iterator, and then it will iterate
    /// over the other specified iterator.
    ///
    /// # Example
    ///
114
    /// ```rust
115 116
    /// let a = [0];
    /// let b = [1];
E
Erick Tryzelaar 已提交
117
    /// let mut it = a.iter().chain(b.iter());
118 119 120
    /// assert_eq!(it.next().get(), &0);
    /// assert_eq!(it.next().get(), &1);
    /// assert!(it.next().is_none());
121
    /// ```
122
    #[inline]
E
Erick Tryzelaar 已提交
123
    fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
124 125
        Chain{a: self, b: other, flag: false}
    }
126 127 128 129 130 131 132 133

    /// Creates an iterator which iterates over both this and the specified
    /// iterators simultaneously, yielding the two elements as pairs. When
    /// either iterator returns None, all further invocations of next() will
    /// return None.
    ///
    /// # Example
    ///
134
    /// ```rust
135 136 137 138 139
    /// let a = [0];
    /// let b = [1];
    /// let mut it = a.iter().zip(b.iter());
    /// assert_eq!(it.next().get(), (&0, &1));
    /// assert!(it.next().is_none());
140
    /// ```
141 142 143 144
    #[inline]
    fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
        Zip{a: self, b: other}
    }
145 146

    /// Creates a new iterator which will apply the specified function to each
147
    /// element returned by the first, yielding the mapped element instead.
148 149 150
    ///
    /// # Example
    ///
151
    /// ```rust
152
    /// let a = [1, 2];
153
    /// let mut it = a.iter().map(|&x| 2 * x);
154 155 156
    /// assert_eq!(it.next().get(), 2);
    /// assert_eq!(it.next().get(), 4);
    /// assert!(it.next().is_none());
157
    /// ```
158
    #[inline]
159
    fn map<'r, B>(self, f: &'r fn(A) -> B) -> Map<'r, A, B, Self> {
160 161
        Map{iter: self, f: f}
    }
162 163 164 165 166 167 168

    /// Creates an iterator which applies the predicate to each element returned
    /// by this iterator. Only elements which have the predicate evaluate to
    /// `true` will be yielded.
    ///
    /// # Example
    ///
169
    /// ```rust
170 171 172 173
    /// let a = [1, 2];
    /// let mut it = a.iter().filter(|&x| *x > 1);
    /// assert_eq!(it.next().get(), &2);
    /// assert!(it.next().is_none());
174
    /// ```
175 176 177 178
    #[inline]
    fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> Filter<'r, A, Self> {
        Filter{iter: self, predicate: predicate}
    }
179

R
Ron Dahlgren 已提交
180
    /// Creates an iterator which both filters and maps elements.
181 182 183 184 185
    /// If the specified function returns None, the element is skipped.
    /// Otherwise the option is unwrapped and the new value is yielded.
    ///
    /// # Example
    ///
186
    /// ```rust
187 188 189 190
    /// let a = [1, 2];
    /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
    /// assert_eq!(it.next().get(), 4);
    /// assert!(it.next().is_none());
191
    /// ```
192 193 194 195
    #[inline]
    fn filter_map<'r, B>(self, f: &'r fn(A) -> Option<B>) -> FilterMap<'r, A, B, Self> {
        FilterMap { iter: self, f: f }
    }
196 197 198 199 200 201

    /// Creates an iterator which yields a pair of the value returned by this
    /// iterator plus the current index of iteration.
    ///
    /// # Example
    ///
202
    /// ```rust
203 204 205 206 207
    /// let a = [100, 200];
    /// let mut it = a.iter().enumerate();
    /// assert_eq!(it.next().get(), (0, &100));
    /// assert_eq!(it.next().get(), (1, &200));
    /// assert!(it.next().is_none());
208
    /// ```
209 210 211 212
    #[inline]
    fn enumerate(self) -> Enumerate<Self> {
        Enumerate{iter: self, count: 0}
    }
213

214 215 216 217 218 219

    /// Creates an iterator that has a `.peek()` method
    /// that returns a optional reference to the next element.
    ///
    /// # Example
    ///
220
    /// ```rust
221 222 223 224 225 226 227 228 229 230
    /// let a = [100, 200, 300];
    /// let mut it = xs.iter().map(|&x|x).peekable();
    /// assert_eq!(it.peek().unwrap(), &100);
    /// assert_eq!(it.next().unwrap(), 100);
    /// assert_eq!(it.next().unwrap(), 200);
    /// assert_eq!(it.peek().unwrap(), &300);
    /// assert_eq!(it.peek().unwrap(), &300);
    /// assert_eq!(it.next().unwrap(), 300);
    /// assert!(it.peek().is_none());
    /// assert!(it.next().is_none());
231
    /// ```
D
Daniel Micay 已提交
232
    #[inline]
233 234 235 236
    fn peekable(self) -> Peekable<A, Self> {
        Peekable{iter: self, peeked: None}
    }

237
    /// Creates an iterator which invokes the predicate on elements until it
R
Ron Dahlgren 已提交
238
    /// returns false. Once the predicate returns false, all further elements are
239 240 241 242
    /// yielded.
    ///
    /// # Example
    ///
243
    /// ```rust
244 245 246 247 248 249
    /// let a = [1, 2, 3, 2, 1];
    /// let mut it = a.iter().skip_while(|&a| *a < 3);
    /// assert_eq!(it.next().get(), &3);
    /// assert_eq!(it.next().get(), &2);
    /// assert_eq!(it.next().get(), &1);
    /// assert!(it.next().is_none());
250
    /// ```
251 252 253 254
    #[inline]
    fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhile<'r, A, Self> {
        SkipWhile{iter: self, flag: false, predicate: predicate}
    }
255 256 257 258 259 260 261

    /// Creates an iterator which yields elements so long as the predicate
    /// returns true. After the predicate returns false for the first time, no
    /// further elements will be yielded.
    ///
    /// # Example
    ///
262
    /// ```rust
263 264 265 266 267
    /// let a = [1, 2, 3, 2, 1];
    /// let mut it = a.iter().take_while(|&a| *a < 3);
    /// assert_eq!(it.next().get(), &1);
    /// assert_eq!(it.next().get(), &2);
    /// assert!(it.next().is_none());
268
    /// ```
269 270 271 272
    #[inline]
    fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) -> TakeWhile<'r, A, Self> {
        TakeWhile{iter: self, flag: false, predicate: predicate}
    }
273 274 275 276 277 278

    /// Creates an iterator which skips the first `n` elements of this iterator,
    /// and then it yields all further items.
    ///
    /// # Example
    ///
279
    /// ```rust
280 281 282 283 284
    /// let a = [1, 2, 3, 4, 5];
    /// let mut it = a.iter().skip(3);
    /// assert_eq!(it.next().get(), &4);
    /// assert_eq!(it.next().get(), &5);
    /// assert!(it.next().is_none());
285
    /// ```
286 287 288 289
    #[inline]
    fn skip(self, n: uint) -> Skip<Self> {
        Skip{iter: self, n: n}
    }
290 291 292 293 294 295

    /// Creates an iterator which yields the first `n` elements of this
    /// iterator, and then it will always return None.
    ///
    /// # Example
    ///
296
    /// ```rust
297
    /// let a = [1, 2, 3, 4, 5];
E
Erick Tryzelaar 已提交
298
    /// let mut it = a.iter().take(3);
299 300 301 302
    /// assert_eq!(it.next().get(), &1);
    /// assert_eq!(it.next().get(), &2);
    /// assert_eq!(it.next().get(), &3);
    /// assert!(it.next().is_none());
303
    /// ```
304
    #[inline]
E
Erick Tryzelaar 已提交
305
    fn take(self, n: uint) -> Take<Self> {
306 307
        Take{iter: self, n: n}
    }
308 309 310 311

    /// Creates a new iterator which behaves in a similar fashion to foldl.
    /// There is a state which is passed between each iteration and can be
    /// mutated as necessary. The yielded values from the closure are yielded
312
    /// from the Scan instance when not None.
313 314 315
    ///
    /// # Example
    ///
316
    /// ```rust
317 318 319 320 321 322 323 324 325 326 327
    /// let a = [1, 2, 3, 4, 5];
    /// let mut it = a.iter().scan(1, |fac, &x| {
    ///   *fac = *fac * x;
    ///   Some(*fac)
    /// });
    /// assert_eq!(it.next().get(), 1);
    /// assert_eq!(it.next().get(), 2);
    /// assert_eq!(it.next().get(), 6);
    /// assert_eq!(it.next().get(), 24);
    /// assert_eq!(it.next().get(), 120);
    /// assert!(it.next().is_none());
328
    /// ```
329
    #[inline]
330
    fn scan<'r, St, B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>)
331 332 333
        -> Scan<'r, A, B, Self, St> {
        Scan{iter: self, f: f, state: initial_state}
    }
334

335 336 337 338 339
    /// Creates an iterator that maps each element to an iterator,
    /// and yields the elements of the produced iterators
    ///
    /// # Example
    ///
340
    /// ```rust
341 342
    /// let xs = [2u, 3];
    /// let ys = [0u, 1, 0, 1, 2];
343
    /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
344 345
    /// // Check that `it` has the same elements as `ys`
    /// let mut i = 0;
D
Daniel Micay 已提交
346
    /// for x: uint in it {
347 348 349
    ///     assert_eq!(x, ys[i]);
    ///     i += 1;
    /// }
350
    /// ```
351
    #[inline]
352
    fn flat_map<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U)
353 354 355
        -> FlatMap<'r, A, Self, U> {
        FlatMap{iter: self, f: f, frontiter: None, backiter: None }
    }
356

357 358 359 360 361 362
    /// Creates an iterator that yields `None` forever after the underlying
    /// iterator yields `None`. Random-access iterator behavior is not
    /// affected, only single and double-ended iterator behavior.
    ///
    /// # Example
    ///
363
    /// ```rust
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    /// fn process<U: Iterator<int>>(it: U) -> int {
    ///     let mut it = it.fuse();
    ///     let mut sum = 0;
    ///     for x in it {
    ///         if x > 5 {
    ///             break;
    ///         }
    ///         sum += x;
    ///     }
    ///     // did we exhaust the iterator?
    ///     if it.next().is_none() {
    ///         sum += 1000;
    ///     }
    ///     sum
    /// }
    /// let x = ~[1,2,3,7,8,9];
    /// assert_eq!(process(x.move_iter()), 1006);
381
    /// ```
382 383 384 385 386
    #[inline]
    fn fuse(self) -> Fuse<Self> {
        Fuse{iter: self, done: false}
    }

387 388 389 390 391 392
    /// Creates an iterator that calls a function with a reference to each
    /// element before yielding it. This is often useful for debugging an
    /// iterator pipeline.
    ///
    /// # Example
    ///
393
    /// ```rust
394 395
    ///let xs = [1u, 4, 2, 3, 8, 9, 6];
    ///let sum = xs.iter()
396
    ///            .map(|&x| x)
397
    ///            .inspect(|&x| debug!("filtering %u", x))
398
    ///            .filter(|&x| x % 2 == 0)
399
    ///            .inspect(|&x| debug!("%u made it through", x))
400 401
    ///            .sum();
    ///println(sum.to_str());
402
    /// ```
403
    #[inline]
404 405
    fn inspect<'r>(self, f: &'r fn(&A)) -> Inspect<'r, A, Self> {
        Inspect{iter: self, f: f}
406
    }
407

408 409 410 411
    /// An adaptation of an external iterator to the for-loop protocol of rust.
    ///
    /// # Example
    ///
412
    /// ```rust
413
    /// use std::iter::count;
D
Daniel Micay 已提交
414
    ///
415
    /// for i in count(0, 10) {
416
    ///     println!("{}", i);
417
    /// }
418
    /// ```
419 420 421 422 423 424 425 426 427 428 429
    #[inline]
    fn advance(&mut self, f: &fn(A) -> bool) -> bool {
        loop {
            match self.next() {
                Some(x) => {
                    if !f(x) { return false; }
                }
                None => { return true; }
            }
        }
    }
430

M
Marvin Löbel 已提交
431
    /// Loops through the entire iterator, collecting all of the elements into
432
    /// a container implementing `FromIterator`.
M
Marvin Löbel 已提交
433 434 435
    ///
    /// # Example
    ///
436
    /// ```rust
M
Marvin Löbel 已提交
437
    /// let a = [1, 2, 3, 4, 5];
438
    /// let b: ~[int] = a.iter().map(|&x| x).collect();
M
Marvin Löbel 已提交
439
    /// assert!(a == b);
440
    /// ```
441
    #[inline]
442
    fn collect<B: FromIterator<A>>(&mut self) -> B {
443 444
        FromIterator::from_iterator(self)
    }
M
Marvin Löbel 已提交
445

446 447 448 449 450
    /// Loops through the entire iterator, collecting all of the elements into
    /// a unique vector. This is simply collect() specialized for vectors.
    ///
    /// # Example
    ///
451
    /// ```rust
452
    /// let a = [1, 2, 3, 4, 5];
453
    /// let b: ~[int] = a.iter().map(|&x| x).to_owned_vec();
454
    /// assert!(a == b);
455
    /// ```
456 457 458 459
    #[inline]
    fn to_owned_vec(&mut self) -> ~[A] {
        self.collect()
    }
460

461 462 463 464 465
    /// Loops through `n` iterations, returning the `n`th element of the
    /// iterator.
    ///
    /// # Example
    ///
466
    /// ```rust
467 468 469 470
    /// let a = [1, 2, 3, 4, 5];
    /// let mut it = a.iter();
    /// assert!(it.nth(2).get() == &3);
    /// assert!(it.nth(2) == None);
471
    /// ```
472 473 474 475 476 477 478 479 480 481
    #[inline]
    fn nth(&mut self, mut n: uint) -> Option<A> {
        loop {
            match self.next() {
                Some(x) => if n == 0 { return Some(x) },
                None => return None
            }
            n -= 1;
        }
    }
482 483 484 485 486 487

    /// Loops through the entire iterator, returning the last element of the
    /// iterator.
    ///
    /// # Example
    ///
488
    /// ```rust
489 490
    /// let a = [1, 2, 3, 4, 5];
    /// assert!(a.iter().last().get() == &5);
491
    /// ```
492
    #[inline]
E
Erick Tryzelaar 已提交
493
    fn last(&mut self) -> Option<A> {
494 495 496 497
        let mut last = None;
        for x in *self { last = Some(x); }
        last
    }
498 499 500 501 502 503

    /// Performs a fold operation over the entire iterator, returning the
    /// eventual state at the end of the iteration.
    ///
    /// # Example
    ///
504
    /// ```rust
505 506
    /// let a = [1, 2, 3, 4, 5];
    /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
507
    /// ```
508 509 510 511 512 513 514 515 516 517 518
    #[inline]
    fn fold<B>(&mut self, init: B, f: &fn(B, A) -> B) -> B {
        let mut accum = init;
        loop {
            match self.next() {
                Some(x) => { accum = f(accum, x); }
                None    => { break; }
            }
        }
        accum
    }
519 520 521 522 523

    /// Counts the number of elements in this iterator.
    ///
    /// # Example
    ///
524
    /// ```rust
525 526
    /// let a = [1, 2, 3, 4, 5];
    /// let mut it = a.iter();
E
Erick Tryzelaar 已提交
527 528
    /// assert!(it.len() == 5);
    /// assert!(it.len() == 0);
529
    /// ```
530
    #[inline]
E
Erick Tryzelaar 已提交
531
    fn len(&mut self) -> uint {
532 533
        self.fold(0, |cnt, _x| cnt + 1)
    }
534 535 536 537 538

    /// Tests whether the predicate holds true for all elements in the iterator.
    ///
    /// # Example
    ///
539
    /// ```rust
540 541 542
    /// let a = [1, 2, 3, 4, 5];
    /// assert!(a.iter().all(|&x| *x > 0));
    /// assert!(!a.iter().all(|&x| *x > 2));
543
    /// ```
544 545 546 547 548
    #[inline]
    fn all(&mut self, f: &fn(A) -> bool) -> bool {
        for x in *self { if !f(x) { return false; } }
        true
    }
549 550 551 552 553 554

    /// Tests whether any element of an iterator satisfies the specified
    /// predicate.
    ///
    /// # Example
    ///
555
    /// ```rust
556 557
    /// let a = [1, 2, 3, 4, 5];
    /// let mut it = a.iter();
558 559
    /// assert!(it.any(|&x| *x == 3));
    /// assert!(!it.any(|&x| *x == 3));
560
    /// ```
561
    #[inline]
562
    fn any(&mut self, f: &fn(A) -> bool) -> bool {
D
Daniel Micay 已提交
563
        for x in *self { if f(x) { return true; } }
D
Daniel Micay 已提交
564 565 566 567
        false
    }

    /// Return the first element satisfying the specified predicate
568
    #[inline]
E
Erick Tryzelaar 已提交
569
    fn find(&mut self, predicate: &fn(&A) -> bool) -> Option<A> {
D
Daniel Micay 已提交
570
        for x in *self {
D
Daniel Micay 已提交
571 572 573
            if predicate(&x) { return Some(x) }
        }
        None
574
    }
575 576 577

    /// Return the index of the first element satisfying the specified predicate
    #[inline]
578
    fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
579
        let mut i = 0;
D
Daniel Micay 已提交
580
        for x in *self {
581 582 583 584 585 586 587
            if predicate(x) {
                return Some(i);
            }
            i += 1;
        }
        None
    }
588

589
    /// Count the number of elements satisfying the specified predicate
590 591 592
    #[inline]
    fn count(&mut self, predicate: &fn(A) -> bool) -> uint {
        let mut i = 0;
D
Daniel Micay 已提交
593
        for x in *self {
594 595 596 597
            if predicate(x) { i += 1 }
        }
        i
    }
598

H
Huon Wilson 已提交
599 600
    /// Return the element that gives the maximum value from the
    /// specified function.
601 602 603
    ///
    /// # Example
    ///
604
    /// ```rust
605 606
    /// let xs = [-3, 0, 1, 5, -10];
    /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
607
    /// ```
608 609 610 611 612 613 614 615 616 617 618 619
    #[inline]
    fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A> {
        self.fold(None, |max: Option<(A, B)>, x| {
            let x_val = f(&x);
            match max {
                None             => Some((x, x_val)),
                Some((y, y_val)) => if x_val > y_val {
                    Some((x, x_val))
                } else {
                    Some((y, y_val))
                }
            }
620
        }).map_move(|(x, _)| x)
621 622
    }

H
Huon Wilson 已提交
623 624
    /// Return the element that gives the minimum value from the
    /// specified function.
625 626 627
    ///
    /// # Example
    ///
628
    /// ```rust
629 630
    /// let xs = [-3, 0, 1, 5, -10];
    /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
631
    /// ```
632 633 634 635 636 637 638 639 640 641 642 643
    #[inline]
    fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A> {
        self.fold(None, |min: Option<(A, B)>, x| {
            let x_val = f(&x);
            match min {
                None             => Some((x, x_val)),
                Some((y, y_val)) => if x_val < y_val {
                    Some((x, x_val))
                } else {
                    Some((y, y_val))
                }
            }
644
        }).map_move(|(x, _)| x)
645
    }
D
Daniel Micay 已提交
646 647
}

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
/// A range iterator able to yield elements from both ends
pub trait DoubleEndedIterator<A>: Iterator<A> {
    /// Yield an element from the end of the range, returning `None` if the range is empty.
    fn next_back(&mut self) -> Option<A>;

    /// Flip the direction of the iterator
    ///
    /// The inverted iterator flips the ends on an iterator that can already
    /// be iterated from the front and from the back.
    ///
    ///
    /// If the iterator also implements RandomAccessIterator, the inverted
    /// iterator is also random access, with the indices starting at the back
    /// of the original iterator.
    ///
    /// Note: Random access with inverted indices still only applies to the first
    /// `uint::max_value` elements of the original iterator.
    #[inline]
    fn invert(self) -> Invert<Self> {
        Invert{iter: self}
    }
}

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
/// A double-ended iterator yielding mutable references
pub trait MutableDoubleEndedIterator {
    // FIXME: #5898: should be called `reverse`
    /// Use an iterator to reverse a container in-place
    fn reverse_(&mut self);
}

impl<'self, A, T: DoubleEndedIterator<&'self mut A>> MutableDoubleEndedIterator for T {
    // FIXME: #5898: should be called `reverse`
    /// Use an iterator to reverse a container in-place
    fn reverse_(&mut self) {
        loop {
            match (self.next(), self.next_back()) {
                (Some(x), Some(y)) => util::swap(x, y),
                _ => break
            }
        }
    }
}

691

692 693 694 695 696 697 698 699 700 701 702 703
/// An object implementing random access indexing by `uint`
///
/// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
pub trait RandomAccessIterator<A>: Iterator<A> {
    /// Return the number of indexable elements. At most `std::uint::max_value`
    /// elements are indexable, even if the iterator represents a longer range.
    fn indexable(&self) -> uint;

    /// Return an element at an index
    fn idx(&self, index: uint) -> Option<A>;
}

704 705 706 707 708 709 710 711
/// An iterator that knows its exact length
///
/// This trait is a helper for iterators like the vector iterator, so that
/// it can support double-ended enumeration.
///
/// `Iterator::size_hint` *must* return the exact size of the iterator.
/// Note that the size must fit in `uint`.
pub trait ExactSize<A> : DoubleEndedIterator<A> {
712 713 714 715 716
    /// Return the index of the last element satisfying the specified predicate
    ///
    /// If no element matches, None is returned.
    #[inline]
    fn rposition(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
717 718 719
        let (lower, upper) = self.size_hint();
        assert!(upper == Some(lower));
        let mut i = lower;
720 721 722 723 724 725
        loop {
            match self.next_back() {
                None => break,
                Some(x) => {
                    i = match i.checked_sub(&1) {
                        Some(x) => x,
726
                        None => fail!("rposition: incorrect ExactSize")
727 728 729 730 731 732 733 734 735 736 737
                    };
                    if predicate(x) {
                        return Some(i)
                    }
                }
            }
        }
        None
    }
}

738 739
// All adaptors that preserve the size of the wrapped iterator are fine
// Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
740 741 742 743 744
impl<A, T: ExactSize<A>> ExactSize<(uint, A)> for Enumerate<T> {}
impl<'self, A, T: ExactSize<A>> ExactSize<A> for Inspect<'self, A, T> {}
impl<A, T: ExactSize<A>> ExactSize<A> for Invert<T> {}
impl<'self, A, B, T: ExactSize<A>> ExactSize<B> for Map<'self, A, B, T> {}
impl<A, B, T: ExactSize<A>, U: ExactSize<B>> ExactSize<(A, B)> for Zip<T, U> {}
745

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
/// An double-ended iterator with the direction inverted
#[deriving(Clone)]
pub struct Invert<T> {
    priv iter: T
}

impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Invert<T> {
    #[inline]
    fn next(&mut self) -> Option<A> { self.iter.next_back() }
    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}

impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Invert<T> {
    #[inline]
    fn next_back(&mut self) -> Option<A> { self.iter.next() }
}

impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
    for Invert<T> {
    #[inline]
    fn indexable(&self) -> uint { self.iter.indexable() }
    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
        self.iter.idx(self.indexable() - index - 1)
    }
}

774
/// A trait for iterators over elements which can be added together
775
pub trait AdditiveIterator<A> {
776 777 778 779
    /// Iterates over the entire iterator, summing up all the elements
    ///
    /// # Example
    ///
780
    /// ```rust
781
    /// let a = [1, 2, 3, 4, 5];
782
    /// let mut it = a.iter().map(|&x| x);
783
    /// assert!(it.sum() == 15);
784
    /// ```
785 786 787 788
    fn sum(&mut self) -> A;
}

impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
789
    #[inline]
790 791 792 793
    fn sum(&mut self) -> A {
        let zero: A = Zero::zero();
        self.fold(zero, |s, x| s + x)
    }
794 795
}

796 797
/// A trait for iterators over elements whose elements can be multiplied
/// together.
798
pub trait MultiplicativeIterator<A> {
799 800 801 802
    /// Iterates over the entire iterator, multiplying all the elements
    ///
    /// # Example
    ///
803
    /// ```rust
804
    /// use std::iter::count;
805 806
    ///
    /// fn factorial(n: uint) -> uint {
807
    ///     count(1u, 1).take_while(|&i| i <= n).product()
808 809 810 811
    /// }
    /// assert!(factorial(0) == 1);
    /// assert!(factorial(1) == 1);
    /// assert!(factorial(5) == 120);
812
    /// ```
813 814 815 816
    fn product(&mut self) -> A;
}

impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
817
    #[inline]
818 819 820 821
    fn product(&mut self) -> A {
        let one: A = One::one();
        self.fold(one, |p, x| p * x)
    }
822 823
}

824 825
/// A trait for iterators over elements which can be compared to one another.
/// The type of each element must ascribe to the `Ord` trait.
826
pub trait OrdIterator<A> {
827 828 829 830
    /// Consumes the entire iterator to return the maximum element.
    ///
    /// # Example
    ///
831
    /// ```rust
832 833
    /// let a = [1, 2, 3, 4, 5];
    /// assert!(a.iter().max().get() == &5);
834
    /// ```
835
    fn max(&mut self) -> Option<A>;
836 837 838 839 840

    /// Consumes the entire iterator to return the minimum element.
    ///
    /// # Example
    ///
841
    /// ```rust
842 843
    /// let a = [1, 2, 3, 4, 5];
    /// assert!(a.iter().min().get() == &1);
844
    /// ```
845 846 847 848
    fn min(&mut self) -> Option<A>;
}

impl<A: Ord, T: Iterator<A>> OrdIterator<A> for T {
849
    #[inline]
850 851 852 853 854 855 856 857 858
    fn max(&mut self) -> Option<A> {
        self.fold(None, |max, x| {
            match max {
                None    => Some(x),
                Some(y) => Some(cmp::max(x, y))
            }
        })
    }

859
    #[inline]
860 861 862 863 864 865 866 867 868 869
    fn min(&mut self) -> Option<A> {
        self.fold(None, |min, x| {
            match min {
                None    => Some(x),
                Some(y) => Some(cmp::min(x, y))
            }
        })
    }
}

870
/// A trait for iterators that are clonable.
871
pub trait ClonableIterator {
872 873 874 875
    /// Repeats an iterator endlessly
    ///
    /// # Example
    ///
876
    /// ```rust
E
Erick Tryzelaar 已提交
877
    /// let a = count(1,1).take(1);
878 879 880
    /// let mut cy = a.cycle();
    /// assert_eq!(cy.next(), Some(1));
    /// assert_eq!(cy.next(), Some(1));
881
    /// ```
882
    fn cycle(self) -> Cycle<Self>;
883 884
}

885
impl<A, T: Clone + Iterator<A>> ClonableIterator for T {
886
    #[inline]
887 888
    fn cycle(self) -> Cycle<T> {
        Cycle{orig: self.clone(), iter: self}
889 890 891 892
    }
}

/// An iterator that repeats endlessly
893
#[deriving(Clone)]
894
pub struct Cycle<T> {
895 896 897 898
    priv orig: T,
    priv iter: T,
}

899
impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
    #[inline]
    fn next(&mut self) -> Option<A> {
        match self.iter.next() {
            None => { self.iter = self.orig.clone(); self.iter.next() }
            y => y
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        // the cycle iterator is either empty or infinite
        match self.orig.size_hint() {
            sz @ (0, Some(0)) => sz,
            (0, _) => (0, None),
            _ => (uint::max_value, None)
        }
    }
}

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
    #[inline]
    fn indexable(&self) -> uint {
        if self.orig.indexable() > 0 {
            uint::max_value
        } else {
            0
        }
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
        let liter = self.iter.indexable();
        let lorig = self.orig.indexable();
        if lorig == 0 {
            None
        } else if index < liter {
            self.iter.idx(index)
        } else {
            self.orig.idx((index - liter) % lorig)
        }
    }
}

943
/// An iterator which strings two iterators together
944
#[deriving(Clone)]
945
pub struct Chain<T, U> {
D
Daniel Micay 已提交
946
    priv a: T,
947
    priv b: U,
D
Daniel Micay 已提交
948 949 950
    priv flag: bool
}

951
impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
D
Daniel Micay 已提交
952 953 954 955 956 957 958 959 960 961 962 963 964
    #[inline]
    fn next(&mut self) -> Option<A> {
        if self.flag {
            self.b.next()
        } else {
            match self.a.next() {
                Some(x) => return Some(x),
                _ => ()
            }
            self.flag = true;
            self.b.next()
        }
    }
965 966

    #[inline]
967
    fn size_hint(&self) -> (uint, Option<uint>) {
968 969 970
        let (a_lower, a_upper) = self.a.size_hint();
        let (b_lower, b_upper) = self.b.size_hint();

971
        let lower = a_lower.saturating_add(b_lower);
972 973

        let upper = match (a_upper, b_upper) {
974
            (Some(x), Some(y)) => x.checked_add(&y),
975 976 977 978 979
            _ => None
        };

        (lower, upper)
    }
D
Daniel Micay 已提交
980 981
}

982
impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
983
for Chain<T, U> {
984 985 986 987 988 989 990 991 992
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        match self.b.next_back() {
            Some(x) => Some(x),
            None => self.a.next_back()
        }
    }
}

D
Daniel Micay 已提交
993
impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
994
for Chain<T, U> {
D
Daniel Micay 已提交
995 996 997
    #[inline]
    fn indexable(&self) -> uint {
        let (a, b) = (self.a.indexable(), self.b.indexable());
998
        a.saturating_add(b)
D
Daniel Micay 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
        let len = self.a.indexable();
        if index < len {
            self.a.idx(index)
        } else {
            self.b.idx(index - len)
        }
    }
}

1012
/// An iterator which iterates two other iterators simultaneously
1013
#[deriving(Clone)]
1014
pub struct Zip<T, U> {
D
Daniel Micay 已提交
1015 1016 1017 1018
    priv a: T,
    priv b: U
}

1019
impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
D
Daniel Micay 已提交
1020 1021
    #[inline]
    fn next(&mut self) -> Option<(A, B)> {
K
Kevin Ballard 已提交
1022 1023 1024 1025 1026 1027
        match self.a.next() {
            None => None,
            Some(x) => match self.b.next() {
                None => None,
                Some(y) => Some((x, y))
            }
D
Daniel Micay 已提交
1028 1029
        }
    }
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (a_lower, a_upper) = self.a.size_hint();
        let (b_lower, b_upper) = self.b.size_hint();

        let lower = cmp::min(a_lower, b_lower);

        let upper = match (a_upper, b_upper) {
            (Some(x), Some(y)) => Some(cmp::min(x,y)),
            (Some(x), None) => Some(x),
            (None, Some(y)) => Some(y),
            (None, None) => None
        };

        (lower, upper)
    }
D
Daniel Micay 已提交
1047 1048
}

1049
impl<A, B, T: ExactSize<A>, U: ExactSize<B>> DoubleEndedIterator<(A, B)>
1050 1051 1052
for Zip<T, U> {
    #[inline]
    fn next_back(&mut self) -> Option<(A, B)> {
1053 1054 1055 1056
        let (a_sz, a_upper) = self.a.size_hint();
        let (b_sz, b_upper) = self.b.size_hint();
        assert!(a_upper == Some(a_sz));
        assert!(b_upper == Some(b_sz));
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        if a_sz < b_sz {
            for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
        } else if a_sz > b_sz {
            for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
        }
        let (a_sz, _) = self.a.size_hint();
        let (b_sz, _) = self.b.size_hint();
        assert!(a_sz == b_sz);
        match (self.a.next_back(), self.b.next_back()) {
            (Some(x), Some(y)) => Some((x, y)),
            _ => None
        }
    }
}

1072 1073 1074 1075 1076 1077 1078 1079 1080
impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
RandomAccessIterator<(A, B)> for Zip<T, U> {
    #[inline]
    fn indexable(&self) -> uint {
        cmp::min(self.a.indexable(), self.b.indexable())
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<(A, B)> {
K
Kevin Ballard 已提交
1081 1082 1083 1084 1085 1086
        match self.a.idx(index) {
            None => None,
            Some(x) => match self.b.idx(index) {
                None => None,
                Some(y) => Some((x, y))
            }
1087 1088 1089 1090
        }
    }
}

1091
/// An iterator which maps the values of `iter` with `f`
1092
pub struct Map<'self, A, B, T> {
1093 1094 1095 1096
    priv iter: T,
    priv f: &'self fn(A) -> B
}

1097
impl<'self, A, B, T> Map<'self, A, B, T> {
1098
    #[inline]
1099 1100
    fn do_map(&self, elt: Option<A>) -> Option<B> {
        match elt {
1101 1102 1103 1104
            Some(a) => Some((self.f)(a)),
            _ => None
        }
    }
1105 1106 1107 1108 1109 1110 1111 1112
}

impl<'self, A, B, T: Iterator<A>> Iterator<B> for Map<'self, A, B, T> {
    #[inline]
    fn next(&mut self) -> Option<B> {
        let next = self.iter.next();
        self.do_map(next)
    }
1113 1114

    #[inline]
1115
    fn size_hint(&self) -> (uint, Option<uint>) {
1116 1117
        self.iter.size_hint()
    }
1118 1119
}

D
Daniel Micay 已提交
1120
impl<'self, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'self, A, B, T> {
1121 1122
    #[inline]
    fn next_back(&mut self) -> Option<B> {
1123 1124 1125 1126 1127
        let next = self.iter.next_back();
        self.do_map(next)
    }
}

D
Daniel Micay 已提交
1128
impl<'self, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'self, A, B, T> {
1129 1130 1131 1132 1133 1134 1135 1136
    #[inline]
    fn indexable(&self) -> uint {
        self.iter.indexable()
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<B> {
        self.do_map(self.iter.idx(index))
1137 1138 1139
    }
}

1140
/// An iterator which filters the elements of `iter` with `predicate`
1141
pub struct Filter<'self, A, T> {
D
Daniel Micay 已提交
1142 1143 1144 1145
    priv iter: T,
    priv predicate: &'self fn(&A) -> bool
}

1146
impl<'self, A, T: Iterator<A>> Iterator<A> for Filter<'self, A, T> {
D
Daniel Micay 已提交
1147 1148
    #[inline]
    fn next(&mut self) -> Option<A> {
D
Daniel Micay 已提交
1149
        for x in self.iter {
D
Daniel Micay 已提交
1150 1151 1152 1153 1154 1155 1156 1157
            if (self.predicate)(&x) {
                return Some(x);
            } else {
                loop
            }
        }
        None
    }
1158 1159

    #[inline]
1160
    fn size_hint(&self) -> (uint, Option<uint>) {
1161
        let (_, upper) = self.iter.size_hint();
1162
        (0, upper) // can't know a lower bound, due to the predicate
1163
    }
D
Daniel Micay 已提交
1164 1165
}

1166
impl<'self, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'self, A, T> {
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        loop {
            match self.iter.next_back() {
                None => return None,
                Some(x) => {
                    if (self.predicate)(&x) {
                        return Some(x);
                    } else {
                        loop
                    }
                }
            }
        }
    }
}

1184
/// An iterator which uses `f` to both filter and map elements from `iter`
1185
pub struct FilterMap<'self, A, B, T> {
1186 1187 1188 1189
    priv iter: T,
    priv f: &'self fn(A) -> Option<B>
}

1190
impl<'self, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'self, A, B, T> {
1191 1192
    #[inline]
    fn next(&mut self) -> Option<B> {
D
Daniel Micay 已提交
1193
        for x in self.iter {
1194 1195 1196
            match (self.f)(x) {
                Some(y) => return Some(y),
                None => ()
1197 1198
            }
        }
1199
        None
1200
    }
1201 1202

    #[inline]
1203
    fn size_hint(&self) -> (uint, Option<uint>) {
1204
        let (_, upper) = self.iter.size_hint();
1205
        (0, upper) // can't know a lower bound, due to the predicate
1206
    }
1207 1208
}

1209
impl<'self, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1210
for FilterMap<'self, A, B, T> {
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    #[inline]
    fn next_back(&mut self) -> Option<B> {
        loop {
            match self.iter.next_back() {
                None => return None,
                Some(x) => {
                    match (self.f)(x) {
                        Some(y) => return Some(y),
                        None => ()
                    }
                }
            }
        }
    }
}

1227
/// An iterator which yields the current count and the element during iteration
1228
#[deriving(Clone)]
1229
pub struct Enumerate<T> {
1230 1231 1232 1233
    priv iter: T,
    priv count: uint
}

1234
impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    #[inline]
    fn next(&mut self) -> Option<(uint, A)> {
        match self.iter.next() {
            Some(a) => {
                let ret = Some((self.count, a));
                self.count += 1;
                ret
            }
            _ => None
        }
    }
1246 1247 1248 1249 1250

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        self.iter.size_hint()
    }
1251
}
1252

1253
impl<A, T: ExactSize<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
1254 1255 1256 1257
    #[inline]
    fn next_back(&mut self) -> Option<(uint, A)> {
        match self.iter.next_back() {
            Some(a) => {
1258 1259 1260
                let (lower, upper) = self.iter.size_hint();
                assert!(upper == Some(lower));
                Some((self.count + lower, a))
1261 1262 1263 1264 1265 1266
            }
            _ => None
        }
    }
}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
    #[inline]
    fn indexable(&self) -> uint {
        self.iter.indexable()
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<(uint, A)> {
        match self.iter.idx(index) {
            Some(a) => Some((self.count + index, a)),
            _ => None,
        }
    }
}

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
/// An iterator with a `peek()` that returns an optional reference to the next element.
pub struct Peekable<A, T> {
    priv iter: T,
    priv peeked: Option<A>,
}

impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
    #[inline]
    fn next(&mut self) -> Option<A> {
        if self.peeked.is_some() { self.peeked.take() }
        else { self.iter.next() }
    }
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (lo, hi) = self.iter.size_hint();
        if self.peeked.is_some() {
            let lo = lo.saturating_add(1);
            let hi = match hi {
                Some(x) => x.checked_add(&1),
                None => None
            };
            (lo, hi)
        } else {
            (lo, hi)
        }
    }
1309 1310 1311 1312 1313 1314 1315
}

impl<'self, A, T: Iterator<A>> Peekable<A, T> {
    /// Return a reference to the next element of the iterator with out advancing it,
    /// or None if the iterator is exhausted.
    #[inline]
    pub fn peek(&'self mut self) -> Option<&'self A> {
1316 1317 1318
        if self.peeked.is_none() {
            self.peeked = self.iter.next();
        }
1319 1320
        match self.peeked {
            Some(ref value) => Some(value),
1321
            None => None,
1322 1323 1324 1325
        }
    }
}

1326
/// An iterator which rejects elements while `predicate` is true
1327
pub struct SkipWhile<'self, A, T> {
1328 1329 1330 1331 1332
    priv iter: T,
    priv flag: bool,
    priv predicate: &'self fn(&A) -> bool
}

1333
impl<'self, A, T: Iterator<A>> Iterator<A> for SkipWhile<'self, A, T> {
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    #[inline]
    fn next(&mut self) -> Option<A> {
        let mut next = self.iter.next();
        if self.flag {
            next
        } else {
            loop {
                match next {
                    Some(x) => {
                        if (self.predicate)(&x) {
                            next = self.iter.next();
                            loop
                        } else {
                            self.flag = true;
                            return Some(x)
                        }
                    }
                    None => return None
                }
            }
        }
    }
1356 1357 1358 1359 1360 1361

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (_, upper) = self.iter.size_hint();
        (0, upper) // can't know a lower bound, due to the predicate
    }
1362 1363
}

1364
/// An iterator which only accepts elements while `predicate` is true
1365
pub struct TakeWhile<'self, A, T> {
1366 1367 1368 1369 1370
    priv iter: T,
    priv flag: bool,
    priv predicate: &'self fn(&A) -> bool
}

1371
impl<'self, A, T: Iterator<A>> Iterator<A> for TakeWhile<'self, A, T> {
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
    #[inline]
    fn next(&mut self) -> Option<A> {
        if self.flag {
            None
        } else {
            match self.iter.next() {
                Some(x) => {
                    if (self.predicate)(&x) {
                        Some(x)
                    } else {
                        self.flag = true;
                        None
                    }
                }
                None => None
            }
        }
    }
1390 1391 1392 1393 1394 1395

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (_, upper) = self.iter.size_hint();
        (0, upper) // can't know a lower bound, due to the predicate
    }
1396
}
D
Daniel Micay 已提交
1397

1398
/// An iterator which skips over `n` elements of `iter`.
1399
#[deriving(Clone)]
1400
pub struct Skip<T> {
D
Daniel Micay 已提交
1401 1402 1403 1404
    priv iter: T,
    priv n: uint
}

1405
impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
D
Daniel Micay 已提交
1406 1407 1408 1409 1410 1411
    #[inline]
    fn next(&mut self) -> Option<A> {
        let mut next = self.iter.next();
        if self.n == 0 {
            next
        } else {
1412 1413 1414
            let mut n = self.n;
            while n > 0 {
                n -= 1;
D
Daniel Micay 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
                match next {
                    Some(_) => {
                        next = self.iter.next();
                        loop
                    }
                    None => {
                        self.n = 0;
                        return None
                    }
                }
            }
            self.n = 0;
            next
        }
    }
1430 1431 1432 1433 1434

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (lower, upper) = self.iter.size_hint();

1435
        let lower = lower.saturating_sub(self.n);
1436 1437

        let upper = match upper {
1438
            Some(x) => Some(x.saturating_sub(self.n)),
1439 1440 1441 1442 1443
            None => None
        };

        (lower, upper)
    }
D
Daniel Micay 已提交
1444 1445
}

1446 1447 1448
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
    #[inline]
    fn indexable(&self) -> uint {
1449
        self.iter.indexable().saturating_sub(self.n)
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
        if index >= self.indexable() {
            None
        } else {
            self.iter.idx(index + self.n)
        }
    }
}

1462
/// An iterator which only iterates over the first `n` iterations of `iter`.
1463
#[deriving(Clone)]
1464
pub struct Take<T> {
D
Daniel Micay 已提交
1465 1466 1467 1468
    priv iter: T,
    priv n: uint
}

1469
impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
D
Daniel Micay 已提交
1470 1471 1472 1473
    #[inline]
    fn next(&mut self) -> Option<A> {
        if self.n != 0 {
            self.n -= 1;
1474
            self.iter.next()
D
Daniel Micay 已提交
1475 1476 1477 1478
        } else {
            None
        }
    }
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (lower, upper) = self.iter.size_hint();

        let lower = cmp::min(lower, self.n);

        let upper = match upper {
            Some(x) if x < self.n => Some(x),
            _ => Some(self.n)
        };

        (lower, upper)
    }
D
Daniel Micay 已提交
1493
}
1494

1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
    #[inline]
    fn indexable(&self) -> uint {
        cmp::min(self.iter.indexable(), self.n)
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
        if index >= self.n {
            None
        } else {
            self.iter.idx(index)
        }
    }
}


1512
/// An iterator to maintain state while iterating another iterator
1513
pub struct Scan<'self, A, B, T, St> {
D
Daniel Micay 已提交
1514 1515
    priv iter: T,
    priv f: &'self fn(&mut St, A) -> Option<B>,
1516 1517

    /// The current internal state to be passed to the closure next.
D
Daniel Micay 已提交
1518 1519 1520
    state: St
}

1521
impl<'self, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'self, A, B, T, St> {
D
Daniel Micay 已提交
1522 1523
    #[inline]
    fn next(&mut self) -> Option<B> {
1524
        self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
D
Daniel Micay 已提交
1525
    }
1526 1527 1528 1529 1530 1531

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (_, upper) = self.iter.size_hint();
        (0, upper) // can't know a lower bound, due to the scan function
    }
D
Daniel Micay 已提交
1532 1533
}

1534 1535 1536
/// An iterator that maps each element to an iterator,
/// and yields the elements of the produced iterators
///
1537
pub struct FlatMap<'self, A, T, U> {
1538 1539
    priv iter: T,
    priv f: &'self fn(A) -> U,
1540 1541
    priv frontiter: Option<U>,
    priv backiter: Option<U>,
1542 1543
}

1544
impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'self, A, T, U> {
1545 1546 1547
    #[inline]
    fn next(&mut self) -> Option<B> {
        loop {
D
Daniel Micay 已提交
1548 1549
            for inner in self.frontiter.mut_iter() {
                for x in *inner {
1550 1551 1552
                    return Some(x)
                }
            }
1553
            match self.iter.next().map_move(|x| (self.f)(x)) {
1554
                None => return self.backiter.and_then_mut_ref(|it| it.next()),
1555 1556 1557 1558
                next => self.frontiter = next,
            }
        }
    }
1559 1560 1561 1562 1563

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (flo, fhi) = self.frontiter.map_default((0, Some(0)), |it| it.size_hint());
        let (blo, bhi) = self.backiter.map_default((0, Some(0)), |it| it.size_hint());
1564
        let lo = flo.saturating_add(blo);
1565
        match (self.iter.size_hint(), fhi, bhi) {
1566
            ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(&b)),
1567
            _ => (lo, None)
1568 1569
        }
    }
1570 1571 1572 1573 1574 1575 1576 1577 1578
}

impl<'self,
     A, T: DoubleEndedIterator<A>,
     B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
     for FlatMap<'self, A, T, U> {
    #[inline]
    fn next_back(&mut self) -> Option<B> {
        loop {
D
Daniel Micay 已提交
1579
            for inner in self.backiter.mut_iter() {
1580 1581 1582 1583 1584
                match inner.next_back() {
                    None => (),
                    y => return y
                }
            }
1585
            match self.iter.next_back().map_move(|x| (self.f)(x)) {
1586
                None => return self.frontiter.and_then_mut_ref(|it| it.next_back()),
1587
                next => self.backiter = next,
1588 1589 1590 1591 1592
            }
        }
    }
}

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
/// An iterator that yields `None` forever after the underlying iterator
/// yields `None` once.
#[deriving(Clone, DeepClone)]
pub struct Fuse<T> {
    priv iter: T,
    priv done: bool
}

impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
    #[inline]
    fn next(&mut self) -> Option<A> {
        if self.done {
            None
        } else {
            match self.iter.next() {
                None => {
                    self.done = true;
                    None
                }
                x => x
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        if self.done {
            (0, Some(0))
        } else {
            self.iter.size_hint()
        }
    }
}

impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        if self.done {
            None
        } else {
            match self.iter.next_back() {
                None => {
                    self.done = true;
                    None
                }
                x => x
            }
        }
    }
}

// Allow RandomAccessIterators to be fused without affecting random-access behavior
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
    #[inline]
    fn indexable(&self) -> uint {
        self.iter.indexable()
    }

    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
        self.iter.idx(index)
    }
}

impl<T> Fuse<T> {
    /// Resets the fuse such that the next call to .next() or .next_back() will
    /// call the underlying iterator again even if it prevously returned None.
    #[inline]
    fn reset_fuse(&mut self) {
        self.done = false
    }
}

1666 1667
/// An iterator that calls a function with a reference to each
/// element before yielding it.
1668
pub struct Inspect<'self, A, T> {
1669 1670 1671 1672
    priv iter: T,
    priv f: &'self fn(&A)
}

1673
impl<'self, A, T> Inspect<'self, A, T> {
1674
    #[inline]
1675
    fn do_inspect(&self, elt: Option<A>) -> Option<A> {
1676
        match elt {
1677 1678 1679 1680
            Some(ref a) => (self.f)(a),
            None => ()
        }

1681 1682 1683 1684
        elt
    }
}

1685
impl<'self, A, T: Iterator<A>> Iterator<A> for Inspect<'self, A, T> {
1686 1687 1688
    #[inline]
    fn next(&mut self) -> Option<A> {
        let next = self.iter.next();
1689
        self.do_inspect(next)
1690 1691 1692 1693 1694 1695 1696 1697
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        self.iter.size_hint()
    }
}

1698 1699
impl<'self, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
for Inspect<'self, A, T> {
1700 1701 1702
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        let next = self.iter.next_back();
1703
        self.do_inspect(next)
1704 1705
    }
}
1706

1707 1708
impl<'self, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
for Inspect<'self, A, T> {
1709 1710 1711 1712
    #[inline]
    fn indexable(&self) -> uint {
        self.iter.indexable()
    }
1713

1714 1715
    #[inline]
    fn idx(&self, index: uint) -> Option<A> {
1716
        self.do_inspect(self.iter.idx(index))
1717 1718 1719
    }
}

1720
/// An iterator which just modifies the contained state throughout iteration.
H
Huon Wilson 已提交
1721
pub struct Unfold<'self, A, St> {
1722
    priv f: &'self fn(&mut St) -> Option<A>,
1723
    /// Internal state that will be yielded on the next iteration
1724
    state: St
1725 1726
}

H
Huon Wilson 已提交
1727
impl<'self, A, St> Unfold<'self, A, St> {
1728 1729
    /// Creates a new iterator with the specified closure as the "iterator
    /// function" and an initial state to eventually pass to the iterator
1730
    #[inline]
1731
    pub fn new<'a>(initial_state: St, f: &'a fn(&mut St) -> Option<A>)
H
Huon Wilson 已提交
1732 1733
        -> Unfold<'a, A, St> {
        Unfold {
1734 1735 1736 1737 1738 1739
            f: f,
            state: initial_state
        }
    }
}

H
Huon Wilson 已提交
1740
impl<'self, A, St> Iterator<A> for Unfold<'self, A, St> {
1741 1742 1743 1744
    #[inline]
    fn next(&mut self) -> Option<A> {
        (self.f)(&mut self.state)
    }
1745 1746 1747 1748 1749 1750

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        // no possible known bounds at this point
        (0, None)
    }
1751 1752
}

1753 1754
/// An infinite iterator starting at `start` and advancing by `step` with each
/// iteration
1755
#[deriving(Clone)]
D
Daniel Micay 已提交
1756
pub struct Counter<A> {
1757
    /// The current state the counter is at (next value to be yielded)
D
Daniel Micay 已提交
1758
    state: A,
1759
    /// The amount that this iterator is stepping by
D
Daniel Micay 已提交
1760
    step: A
1761 1762
}

1763 1764 1765 1766
/// Creates a new counter with the specified start/step
#[inline]
pub fn count<A>(start: A, step: A) -> Counter<A> {
    Counter{state: start, step: step}
D
Daniel Micay 已提交
1767 1768
}

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
    #[inline]
    fn next(&mut self) -> Option<A> {
        let result = self.state.clone();
        self.state = self.state + self.step;
        Some(result)
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        (uint::max_value, None) // Too bad we can't specify an infinite lower bound
    }
}

D
Daniel Micay 已提交
1783
/// An iterator over the range [start, stop)
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
#[deriving(Clone, DeepClone)]
pub struct Range<A> {
    priv state: A,
    priv stop: A,
    priv one: A
}

/// Return an iterator over the range [start, stop)
#[inline]
pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
    Range{state: start, stop: stop, one: One::one()}
}

1797
impl<A: Add<A, A> + Ord + Clone> Iterator<A> for Range<A> {
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
    #[inline]
    fn next(&mut self) -> Option<A> {
        if self.state < self.stop {
            let result = self.state.clone();
            self.state = self.state + self.one;
            Some(result)
        } else {
            None
        }
    }
1808 1809 1810

    // FIXME: #8606 Implement size_hint() on Range
    // Blocked on #8605 Need numeric trait for converting to `Option<uint>`
1811 1812
}

1813 1814 1815
/// `Integer` is required to ensure the range will be the same regardless of
/// the direction it is consumed.
impl<A: Integer + Ord + Clone> DoubleEndedIterator<A> for Range<A> {
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        if self.stop > self.state {
            self.stop = self.stop - self.one;
            Some(self.stop.clone())
        } else {
            None
        }
    }
}

D
Daniel Micay 已提交
1827
/// An iterator over the range [start, stop]
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
#[deriving(Clone, DeepClone)]
pub struct RangeInclusive<A> {
    priv range: Range<A>,
    priv done: bool
}

/// Return an iterator over the range [start, stop]
#[inline]
pub fn range_inclusive<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> RangeInclusive<A> {
    RangeInclusive{range: range(start, stop), done: false}
}

1840
impl<A: Add<A, A> + Eq + Ord + Clone> Iterator<A> for RangeInclusive<A> {
1841 1842 1843 1844 1845
    #[inline]
    fn next(&mut self) -> Option<A> {
        match self.range.next() {
            Some(x) => Some(x),
            None => {
1846
                if !self.done && self.range.state == self.range.stop {
1847 1848
                    self.done = true;
                    Some(self.range.stop.clone())
1849 1850
                } else {
                    None
1851 1852 1853 1854
                }
            }
        }
    }
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        let (lo, hi) = self.range.size_hint();
        if self.done {
            (lo, hi)
        } else {
            let lo = lo.saturating_add(1);
            let hi = match hi {
                Some(x) => x.checked_add(&1),
                None => None
            };
            (lo, hi)
        }
    }
1870 1871 1872 1873 1874 1875 1876 1877 1878
}

impl<A: Sub<A, A> + Integer + Ord + Clone> DoubleEndedIterator<A> for RangeInclusive<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> {
        if self.range.stop > self.range.state {
            let result = self.range.stop.clone();
            self.range.stop = self.range.stop - self.range.one;
            Some(result)
1879
        } else if !self.done && self.range.state == self.range.stop {
1880 1881
            self.done = true;
            Some(self.range.stop.clone())
1882 1883
        } else {
            None
1884 1885 1886 1887
        }
    }
}

1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
/// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
#[deriving(Clone, DeepClone)]
pub struct RangeStep<A> {
    priv state: A,
    priv stop: A,
    priv step: A,
    priv rev: bool
}

/// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A, step: A) -> RangeStep<A> {
    let rev = step < Zero::zero();
    RangeStep{state: start, stop: stop, step: step, rev: rev}
}

impl<A: CheckedAdd + Ord + Clone> Iterator<A> for RangeStep<A> {
    #[inline]
    fn next(&mut self) -> Option<A> {
1907
        if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
            let result = self.state.clone();
            match self.state.checked_add(&self.step) {
                Some(x) => self.state = x,
                None => self.state = self.stop.clone()
            }
            Some(result)
        } else {
            None
        }
    }
}

/// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
#[deriving(Clone, DeepClone)]
pub struct RangeStepInclusive<A> {
    priv state: A,
    priv stop: A,
    priv step: A,
    priv rev: bool,
    priv done: bool
}

/// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step_inclusive<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A,
                                                                step: A) -> RangeStepInclusive<A> {
    let rev = step < Zero::zero();
    RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
}

impl<A: CheckedAdd + Ord + Clone + Eq> Iterator<A> for RangeStepInclusive<A> {
    #[inline]
    fn next(&mut self) -> Option<A> {
1941 1942 1943 1944 1945 1946
        if !self.done && ((self.rev && self.state >= self.stop) ||
                          (!self.rev && self.state <= self.stop)) {
            let result = self.state.clone();
            match self.state.checked_add(&self.step) {
                Some(x) => self.state = x,
                None => self.done = true
1947
            }
1948
            Some(result)
1949 1950 1951 1952 1953 1954
        } else {
            None
        }
    }
}

1955 1956 1957 1958 1959 1960 1961
/// An iterator that repeats an element endlessly
#[deriving(Clone, DeepClone)]
pub struct Repeat<A> {
    priv element: A
}

impl<A: Clone> Repeat<A> {
H
Huon Wilson 已提交
1962
    /// Create a new `Repeat` that endlessly repeats the element `elt`.
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
    #[inline]
    pub fn new(elt: A) -> Repeat<A> {
        Repeat{element: elt}
    }
}

impl<A: Clone> Iterator<A> for Repeat<A> {
    #[inline]
    fn next(&mut self) -> Option<A> { self.idx(0) }
    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) { (uint::max_value, None) }
}

impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
    #[inline]
    fn next_back(&mut self) -> Option<A> { self.idx(0) }
}

impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
    #[inline]
    fn indexable(&self) -> uint { uint::max_value }
    #[inline]
    fn idx(&self, _: uint) -> Option<A> { Some(self.element.clone()) }
}

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
/// Functions for lexicographical ordering of sequences.
///
/// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
/// that the elements implement both `Eq` and `Ord`.
///
/// If two sequences are equal up until the point where one ends,
/// the shorter sequence compares less.
pub mod order {
    use cmp;
    use cmp::{TotalEq, TotalOrd, Ord, Eq};
    use option::{Some, None};
    use super::Iterator;

    /// Compare `a` and `b` for equality using `TotalOrd`
    pub fn equals<A: TotalEq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return true,
                (None, _) | (_, None) => return false,
                (Some(x), Some(y)) => if !x.equals(&y) { return false },
            }
        }
    }

    /// Order `a` and `b` lexicographically using `TotalOrd`
    pub fn cmp<A: TotalOrd, T: Iterator<A>>(mut a: T, mut b: T) -> cmp::Ordering {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return cmp::Equal,
                (None, _   ) => return cmp::Less,
                (_   , None) => return cmp::Greater,
                (Some(x), Some(y)) => match x.cmp(&y) {
                    cmp::Equal => (),
                    non_eq => return non_eq,
                },
            }
        }
    }

    /// Compare `a` and `b` for equality (Using partial equality, `Eq`)
    pub fn eq<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return true,
                (None, _) | (_, None) => return false,
                (Some(x), Some(y)) => if !x.eq(&y) { return false },
            }
        }
    }

    /// Compare `a` and `b` for nonequality (Using partial equality, `Eq`)
    pub fn ne<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return false,
                (None, _) | (_, None) => return true,
                (Some(x), Some(y)) => if x.ne(&y) { return true },
            }
        }
    }

    /// Return `a` < `b` lexicographically (Using partial order, `Ord`)
    pub fn lt<A: Eq + Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return false,
                (None, _   ) => return true,
                (_   , None) => return false,
                (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
            }
        }
    }

    /// Return `a` <= `b` lexicographically (Using partial order, `Ord`)
    pub fn le<A: Eq + Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return true,
                (None, _   ) => return true,
                (_   , None) => return false,
                (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
            }
        }
    }

    /// Return `a` > `b` lexicographically (Using partial order, `Ord`)
    pub fn gt<A: Eq + Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return false,
                (None, _   ) => return false,
                (_   , None) => return true,
                (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
            }
        }
    }

    /// Return `a` >= `b` lexicographically (Using partial order, `Ord`)
    pub fn ge<A: Eq + Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
        loop {
            match (a.next(), b.next()) {
                (None, None) => return true,
                (None, _   ) => return false,
                (_   , None) => return true,
                (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },
            }
        }
    }
B
blake2-ppc 已提交
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142

    #[test]
    fn test_lt() {
        use vec::ImmutableVector;

        let empty: [int, ..0] = [];
        let xs = [1,2,3];
        let ys = [1,2,0];

        assert!(!lt(xs.iter(), ys.iter()));
        assert!(!le(xs.iter(), ys.iter()));
        assert!( gt(xs.iter(), ys.iter()));
        assert!( ge(xs.iter(), ys.iter()));

        assert!( lt(ys.iter(), xs.iter()));
        assert!( le(ys.iter(), xs.iter()));
        assert!(!gt(ys.iter(), xs.iter()));
        assert!(!ge(ys.iter(), xs.iter()));

        assert!( lt(empty.iter(), xs.iter()));
        assert!( le(empty.iter(), xs.iter()));
        assert!(!gt(empty.iter(), xs.iter()));
        assert!(!ge(empty.iter(), xs.iter()));

        // Sequence with NaN
        let u = [1.0, 2.0];
        let v = [0.0/0.0, 3.0];

        assert!(!lt(u.iter(), v.iter()));
        assert!(!le(u.iter(), v.iter()));
        assert!(!gt(u.iter(), v.iter()));
        assert!(!ge(u.iter(), v.iter()));

        let a = [0.0/0.0];
        let b = [1.0];
        let c = [2.0];

        assert!(lt(a.iter(), b.iter()) == (a[0] <  b[0]));
        assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
        assert!(gt(a.iter(), b.iter()) == (a[0] >  b[0]));
        assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0]));

        assert!(lt(c.iter(), b.iter()) == (c[0] <  b[0]));
        assert!(le(c.iter(), b.iter()) == (c[0] <= b[0]));
        assert!(gt(c.iter(), b.iter()) == (c[0] >  b[0]));
        assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0]));
    }
2143 2144
}

2145 2146 2147 2148 2149
#[cfg(test)]
mod tests {
    use super::*;
    use prelude::*;

2150
    use cmp;
2151 2152
    use uint;

D
Daniel Micay 已提交
2153
    #[test]
M
Fixups  
Marvin Löbel 已提交
2154
    fn test_counter_from_iter() {
E
Erick Tryzelaar 已提交
2155
        let mut it = count(0, 5).take(10);
2156
        let xs: ~[int] = FromIterator::from_iterator(&mut it);
D
Daniel Micay 已提交
2157 2158 2159
        assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
    }

D
Daniel Micay 已提交
2160 2161 2162
    #[test]
    fn test_iterator_chain() {
        let xs = [0u, 1, 2, 3, 4, 5];
2163
        let ys = [30u, 40, 50, 60];
D
Daniel Micay 已提交
2164
        let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
E
Erick Tryzelaar 已提交
2165
        let mut it = xs.iter().chain(ys.iter());
D
Daniel Micay 已提交
2166
        let mut i = 0;
D
Daniel Micay 已提交
2167
        for &x in it {
D
Daniel Micay 已提交
2168 2169 2170 2171
            assert_eq!(x, expected[i]);
            i += 1;
        }
        assert_eq!(i, expected.len());
2172

E
Erick Tryzelaar 已提交
2173
        let ys = count(30u, 10).take(4);
E
Erick Tryzelaar 已提交
2174
        let mut it = xs.iter().map(|&x| x).chain(ys);
2175
        let mut i = 0;
D
Daniel Micay 已提交
2176
        for x in it {
2177 2178 2179 2180
            assert_eq!(x, expected[i]);
            i += 1;
        }
        assert_eq!(i, expected.len());
D
Daniel Micay 已提交
2181 2182
    }

2183 2184
    #[test]
    fn test_filter_map() {
E
Erick Tryzelaar 已提交
2185
        let mut it = count(0u, 1u).take(10)
2186
            .filter_map(|x| if x.is_even() { Some(x*x) } else { None });
M
Fixups  
Marvin Löbel 已提交
2187
        assert_eq!(it.collect::<~[uint]>(), ~[0*0, 2*2, 4*4, 6*6, 8*8]);
2188 2189
    }

2190 2191 2192 2193
    #[test]
    fn test_iterator_enumerate() {
        let xs = [0u, 1, 2, 3, 4, 5];
        let mut it = xs.iter().enumerate();
D
Daniel Micay 已提交
2194
        for (i, &x) in it {
2195 2196 2197 2198
            assert_eq!(i, x);
        }
    }

2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
    #[test]
    fn test_iterator_peekable() {
        let xs = ~[0u, 1, 2, 3, 4, 5];
        let mut it = xs.iter().map(|&x|x).peekable();
        assert_eq!(it.peek().unwrap(), &0);
        assert_eq!(it.next().unwrap(), 0);
        assert_eq!(it.next().unwrap(), 1);
        assert_eq!(it.next().unwrap(), 2);
        assert_eq!(it.peek().unwrap(), &3);
        assert_eq!(it.peek().unwrap(), &3);
        assert_eq!(it.next().unwrap(), 3);
        assert_eq!(it.next().unwrap(), 4);
        assert_eq!(it.peek().unwrap(), &5);
        assert_eq!(it.next().unwrap(), 5);
        assert!(it.peek().is_none());
        assert!(it.next().is_none());
    }

2217 2218 2219 2220 2221 2222
    #[test]
    fn test_iterator_take_while() {
        let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
        let ys = [0u, 1, 2, 3, 5, 13];
        let mut it = xs.iter().take_while(|&x| *x < 15u);
        let mut i = 0;
D
Daniel Micay 已提交
2223
        for &x in it {
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
            assert_eq!(x, ys[i]);
            i += 1;
        }
        assert_eq!(i, ys.len());
    }

    #[test]
    fn test_iterator_skip_while() {
        let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
        let ys = [15, 16, 17, 19];
        let mut it = xs.iter().skip_while(|&x| *x < 15u);
        let mut i = 0;
D
Daniel Micay 已提交
2236
        for &x in it {
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
            assert_eq!(x, ys[i]);
            i += 1;
        }
        assert_eq!(i, ys.len());
    }

    #[test]
    fn test_iterator_skip() {
        let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
        let ys = [13, 15, 16, 17, 19, 20, 30];
        let mut it = xs.iter().skip(5);
        let mut i = 0;
D
Daniel Micay 已提交
2249
        for &x in it {
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
            assert_eq!(x, ys[i]);
            i += 1;
        }
        assert_eq!(i, ys.len());
    }

    #[test]
    fn test_iterator_take() {
        let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
        let ys = [0u, 1, 2, 3, 5];
E
Erick Tryzelaar 已提交
2260
        let mut it = xs.iter().take(5);
2261
        let mut i = 0;
D
Daniel Micay 已提交
2262
        for &x in it {
2263 2264 2265 2266 2267
            assert_eq!(x, ys[i]);
            i += 1;
        }
        assert_eq!(i, ys.len());
    }
2268

2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    #[test]
    fn test_iterator_scan() {
        // test the type inference
        fn add(old: &mut int, new: &uint) -> Option<float> {
            *old += *new as int;
            Some(*old as float)
        }
        let xs = [0u, 1, 2, 3, 4];
        let ys = [0f, 1f, 3f, 6f, 10f];

        let mut it = xs.iter().scan(0, add);
        let mut i = 0;
D
Daniel Micay 已提交
2281
        for x in it {
2282 2283 2284 2285 2286 2287
            assert_eq!(x, ys[i]);
            i += 1;
        }
        assert_eq!(i, ys.len());
    }

2288 2289 2290 2291
    #[test]
    fn test_iterator_flat_map() {
        let xs = [0u, 3, 6];
        let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
2292
        let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3));
2293
        let mut i = 0;
D
Daniel Micay 已提交
2294
        for x in it {
2295 2296 2297 2298 2299 2300
            assert_eq!(x, ys[i]);
            i += 1;
        }
        assert_eq!(i, ys.len());
    }

2301
    #[test]
2302
    fn test_inspect() {
2303 2304 2305 2306
        let xs = [1u, 2, 3, 4];
        let mut n = 0;

        let ys = xs.iter()
2307
                   .map(|&x| x)
2308
                   .inspect(|_| n += 1)
2309 2310 2311 2312 2313 2314
                   .collect::<~[uint]>();

        assert_eq!(n, xs.len());
        assert_eq!(xs, ys.as_slice());
    }

2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
    #[test]
    fn test_unfoldr() {
        fn count(st: &mut uint) -> Option<uint> {
            if *st < 10 {
                let ret = Some(*st);
                *st += 1;
                ret
            } else {
                None
            }
        }

H
Huon Wilson 已提交
2327
        let mut it = Unfold::new(0, count);
2328
        let mut i = 0;
D
Daniel Micay 已提交
2329
        for counted in it {
2330 2331 2332 2333 2334
            assert_eq!(counted, i);
            i += 1;
        }
        assert_eq!(i, 10);
    }
2335

B
blake2-ppc 已提交
2336 2337 2338
    #[test]
    fn test_cycle() {
        let cycle_len = 3;
E
Erick Tryzelaar 已提交
2339
        let it = count(0u, 1).take(cycle_len).cycle();
B
blake2-ppc 已提交
2340
        assert_eq!(it.size_hint(), (uint::max_value, None));
E
Erick Tryzelaar 已提交
2341
        for (i, x) in it.take(100).enumerate() {
B
blake2-ppc 已提交
2342 2343 2344
            assert_eq!(i % cycle_len, x);
        }

E
Erick Tryzelaar 已提交
2345
        let mut it = count(0u, 1).take(0).cycle();
B
blake2-ppc 已提交
2346 2347 2348 2349
        assert_eq!(it.size_hint(), (0, Some(0)));
        assert_eq!(it.next(), None);
    }

2350 2351 2352
    #[test]
    fn test_iterator_nth() {
        let v = &[0, 1, 2, 3, 4];
D
Daniel Micay 已提交
2353
        for i in range(0u, v.len()) {
2354
            assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
2355 2356 2357 2358 2359 2360
        }
    }

    #[test]
    fn test_iterator_last() {
        let v = &[0, 1, 2, 3, 4];
E
Erick Tryzelaar 已提交
2361 2362
        assert_eq!(v.iter().last().unwrap(), &4);
        assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
2363
    }
2364 2365

    #[test]
2366
    fn test_iterator_len() {
2367
        let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
E
Erick Tryzelaar 已提交
2368 2369 2370
        assert_eq!(v.slice(0, 4).iter().len(), 4);
        assert_eq!(v.slice(0, 10).iter().len(), 10);
        assert_eq!(v.slice(0, 0).iter().len(), 0);
2371
    }
2372 2373 2374 2375

    #[test]
    fn test_iterator_sum() {
        let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2376 2377 2378
        assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
        assert_eq!(v.iter().map(|&x| x).sum(), 55);
        assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
2379 2380 2381 2382 2383
    }

    #[test]
    fn test_iterator_product() {
        let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2384 2385 2386
        assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
        assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
        assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
2387 2388 2389 2390 2391
    }

    #[test]
    fn test_iterator_max() {
        let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2392 2393 2394
        assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
        assert_eq!(v.iter().map(|&x| x).max(), Some(10));
        assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
2395 2396 2397 2398 2399
    }

    #[test]
    fn test_iterator_min() {
        let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2400 2401 2402
        assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
        assert_eq!(v.iter().map(|&x| x).min(), Some(0));
        assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
2403 2404
    }

2405 2406
    #[test]
    fn test_iterator_size_hint() {
2407
        let c = count(0, 1);
2408 2409 2410 2411 2412 2413 2414
        let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        let v2 = &[10, 11, 12];
        let vi = v.iter();

        assert_eq!(c.size_hint(), (uint::max_value, None));
        assert_eq!(vi.size_hint(), (10, Some(10)));

E
Erick Tryzelaar 已提交
2415
        assert_eq!(c.take(5).size_hint(), (5, Some(5)));
2416 2417 2418 2419
        assert_eq!(c.skip(5).size_hint().second(), None);
        assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
        assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
        assert_eq!(c.enumerate().size_hint(), (uint::max_value, None));
E
Erick Tryzelaar 已提交
2420
        assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::max_value, None));
2421 2422 2423
        assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
        assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
        assert_eq!(c.filter(|_| false).size_hint(), (0, None));
2424
        assert_eq!(c.map(|_| 0).size_hint(), (uint::max_value, None));
2425 2426
        assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));

E
Erick Tryzelaar 已提交
2427 2428
        assert_eq!(vi.take(5).size_hint(), (5, Some(5)));
        assert_eq!(vi.take(12).size_hint(), (10, Some(10)));
2429 2430 2431 2432 2433
        assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
        assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
        assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
        assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
        assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
E
Erick Tryzelaar 已提交
2434
        assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13)));
2435 2436 2437
        assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
        assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
        assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
2438
        assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10)));
2439 2440 2441
        assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
    }

M
Marvin Löbel 已提交
2442 2443
    #[test]
    fn test_collect() {
M
Fixups  
Marvin Löbel 已提交
2444
        let a = ~[1, 2, 3, 4, 5];
2445
        let b: ~[int] = a.iter().map(|&x| x).collect();
M
Marvin Löbel 已提交
2446 2447 2448
        assert_eq!(a, b);
    }

2449 2450
    #[test]
    fn test_all() {
2451
        let v: ~&[int] = ~&[1, 2, 3, 4, 5];
2452
        assert!(v.iter().all(|&x| x < 10));
2453
        assert!(!v.iter().all(|&x| x.is_even()));
2454
        assert!(!v.iter().all(|&x| x > 100));
2455 2456 2457 2458 2459
        assert!(v.slice(0, 0).iter().all(|_| fail!()));
    }

    #[test]
    fn test_any() {
2460
        let v: ~&[int] = ~&[1, 2, 3, 4, 5];
2461 2462 2463 2464
        assert!(v.iter().any(|&x| x < 10));
        assert!(v.iter().any(|&x| x.is_even()));
        assert!(!v.iter().any(|&x| x > 100));
        assert!(!v.slice(0, 0).iter().any(|_| fail!()));
2465
    }
D
Daniel Micay 已提交
2466 2467 2468

    #[test]
    fn test_find() {
2469
        let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
E
Erick Tryzelaar 已提交
2470 2471 2472
        assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
        assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
        assert!(v.iter().find(|x| *x % 12 == 0).is_none());
D
Daniel Micay 已提交
2473
    }
2474 2475 2476 2477

    #[test]
    fn test_position() {
        let v = &[1, 3, 9, 27, 103, 14, 11];
2478 2479 2480
        assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
        assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
        assert!(v.iter().position(|x| *x % 12 == 0).is_none());
2481
    }
2482 2483 2484 2485 2486 2487 2488 2489

    #[test]
    fn test_count() {
        let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
        assert_eq!(xs.iter().count(|x| *x == 2), 3);
        assert_eq!(xs.iter().count(|x| *x == 5), 1);
        assert_eq!(xs.iter().count(|x| *x == 95), 0);
    }
2490 2491 2492

    #[test]
    fn test_max_by() {
2493
        let xs: &[int] = &[-3, 0, 1, 5, -10];
2494 2495 2496 2497 2498
        assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
    }

    #[test]
    fn test_min_by() {
2499
        let xs: &[int] = &[-3, 0, 1, 5, -10];
2500 2501
        assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
    }
2502 2503 2504 2505 2506 2507 2508

    #[test]
    fn test_invert() {
        let xs = [2, 4, 6, 8, 10, 12, 14, 16];
        let mut it = xs.iter();
        it.next();
        it.next();
2509
        assert_eq!(it.invert().map(|&x| x).collect::<~[int]>(), ~[16, 14, 12, 10, 8, 6]);
2510
    }
2511 2512 2513 2514

    #[test]
    fn test_double_ended_map() {
        let xs = [1, 2, 3, 4, 5, 6];
2515
        let mut it = xs.iter().map(|&x| x * -1);
2516 2517 2518 2519 2520 2521 2522 2523 2524
        assert_eq!(it.next(), Some(-1));
        assert_eq!(it.next(), Some(-2));
        assert_eq!(it.next_back(), Some(-6));
        assert_eq!(it.next_back(), Some(-5));
        assert_eq!(it.next(), Some(-3));
        assert_eq!(it.next_back(), Some(-4));
        assert_eq!(it.next(), None);
    }

2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
    #[test]
    fn test_double_ended_enumerate() {
        let xs = [1, 2, 3, 4, 5, 6];
        let mut it = xs.iter().map(|&x| x).enumerate();
        assert_eq!(it.next(), Some((0, 1)));
        assert_eq!(it.next(), Some((1, 2)));
        assert_eq!(it.next_back(), Some((5, 6)));
        assert_eq!(it.next_back(), Some((4, 5)));
        assert_eq!(it.next_back(), Some((3, 4)));
        assert_eq!(it.next_back(), Some((2, 3)));
        assert_eq!(it.next(), None);
    }

    #[test]
    fn test_double_ended_zip() {
        let xs = [1, 2, 3, 4, 5, 6];
        let ys = [1, 2, 3, 7];
        let a = xs.iter().map(|&x| x);
        let b = ys.iter().map(|&x| x);
        let mut it = a.zip(b);
        assert_eq!(it.next(), Some((1, 1)));
        assert_eq!(it.next(), Some((2, 2)));
        assert_eq!(it.next_back(), Some((4, 7)));
        assert_eq!(it.next_back(), Some((3, 3)));
        assert_eq!(it.next(), None);
    }

2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
    #[test]
    fn test_double_ended_filter() {
        let xs = [1, 2, 3, 4, 5, 6];
        let mut it = xs.iter().filter(|&x| *x & 1 == 0);
        assert_eq!(it.next_back().unwrap(), &6);
        assert_eq!(it.next_back().unwrap(), &4);
        assert_eq!(it.next().unwrap(), &2);
        assert_eq!(it.next_back(), None);
    }

    #[test]
    fn test_double_ended_filter_map() {
        let xs = [1, 2, 3, 4, 5, 6];
        let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
        assert_eq!(it.next_back().unwrap(), 12);
        assert_eq!(it.next_back().unwrap(), 8);
        assert_eq!(it.next().unwrap(), 4);
        assert_eq!(it.next_back(), None);
    }

    #[test]
    fn test_double_ended_chain() {
        let xs = [1, 2, 3, 4, 5];
        let ys = ~[7, 9, 11];
E
Erick Tryzelaar 已提交
2576
        let mut it = xs.iter().chain(ys.iter()).invert();
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
        assert_eq!(it.next().unwrap(), &11)
        assert_eq!(it.next().unwrap(), &9)
        assert_eq!(it.next_back().unwrap(), &1)
        assert_eq!(it.next_back().unwrap(), &2)
        assert_eq!(it.next_back().unwrap(), &3)
        assert_eq!(it.next_back().unwrap(), &4)
        assert_eq!(it.next_back().unwrap(), &5)
        assert_eq!(it.next_back().unwrap(), &7)
        assert_eq!(it.next_back(), None)
    }
D
Daniel Micay 已提交
2587

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
    #[test]
    fn test_rposition() {
        fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
        fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
        let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];

        assert_eq!(v.iter().rposition(f), Some(3u));
        assert!(v.iter().rposition(g).is_none());
    }

    #[test]
    #[should_fail]
    fn test_rposition_fail() {
        let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
        let mut i = 0;
        do v.iter().rposition |_elt| {
            if i == 2 {
                fail!()
            }
            i += 1;
            false
        };
    }


2613 2614 2615 2616 2617 2618
    #[cfg(test)]
    fn check_randacc_iter<A: Eq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint)
    {
        let mut b = a.clone();
        assert_eq!(len, b.indexable());
        let mut n = 0;
D
Daniel Micay 已提交
2619
        for (i, elt) in a.enumerate() {
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
            assert_eq!(Some(elt), b.idx(i));
            n += 1;
        }
        assert_eq!(n, len);
        assert_eq!(None, b.idx(n));
        // call recursively to check after picking off an element
        if len > 0 {
            b.next();
            check_randacc_iter(b, len-1);
        }
    }


2633 2634 2635 2636
    #[test]
    fn test_double_ended_flat_map() {
        let u = [0u,1];
        let v = [5,6,7,8];
2637
        let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
        assert_eq!(it.next_back().unwrap(), &8);
        assert_eq!(it.next().unwrap(),      &5);
        assert_eq!(it.next_back().unwrap(), &7);
        assert_eq!(it.next_back().unwrap(), &6);
        assert_eq!(it.next_back().unwrap(), &8);
        assert_eq!(it.next().unwrap(),      &6);
        assert_eq!(it.next_back().unwrap(), &7);
        assert_eq!(it.next_back(), None);
        assert_eq!(it.next(),      None);
        assert_eq!(it.next_back(), None);
    }

D
Daniel Micay 已提交
2650 2651 2652 2653
    #[test]
    fn test_random_access_chain() {
        let xs = [1, 2, 3, 4, 5];
        let ys = ~[7, 9, 11];
E
Erick Tryzelaar 已提交
2654
        let mut it = xs.iter().chain(ys.iter());
D
Daniel Micay 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
        assert_eq!(it.idx(0).unwrap(), &1);
        assert_eq!(it.idx(5).unwrap(), &7);
        assert_eq!(it.idx(7).unwrap(), &11);
        assert!(it.idx(8).is_none());

        it.next();
        it.next();
        it.next_back();

        assert_eq!(it.idx(0).unwrap(), &3);
        assert_eq!(it.idx(4).unwrap(), &9);
        assert!(it.idx(6).is_none());
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676

        check_randacc_iter(it, xs.len() + ys.len() - 3);
    }

    #[test]
    fn test_random_access_enumerate() {
        let xs = [1, 2, 3, 4, 5];
        check_randacc_iter(xs.iter().enumerate(), xs.len());
    }

2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
    #[test]
    fn test_random_access_invert() {
        let xs = [1, 2, 3, 4, 5];
        check_randacc_iter(xs.iter().invert(), xs.len());
        let mut it = xs.iter().invert();
        it.next();
        it.next_back();
        it.next();
        check_randacc_iter(it, xs.len() - 3);
    }

2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
    #[test]
    fn test_random_access_zip() {
        let xs = [1, 2, 3, 4, 5];
        let ys = [7, 9, 11];
        check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
    }

    #[test]
    fn test_random_access_take() {
        let xs = [1, 2, 3, 4, 5];
        let empty: &[int] = [];
E
Erick Tryzelaar 已提交
2699 2700 2701 2702
        check_randacc_iter(xs.iter().take(3), 3);
        check_randacc_iter(xs.iter().take(20), xs.len());
        check_randacc_iter(xs.iter().take(0), 0);
        check_randacc_iter(empty.iter().take(2), 0);
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
    }

    #[test]
    fn test_random_access_skip() {
        let xs = [1, 2, 3, 4, 5];
        let empty: &[int] = [];
        check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
        check_randacc_iter(empty.iter().skip(2), 0);
    }

    #[test]
2714
    fn test_random_access_inspect() {
2715 2716
        let xs = [1, 2, 3, 4, 5];

2717 2718
        // test .map and .inspect that don't implement Clone
        let it = xs.iter().inspect(|_| {});
2719
        assert_eq!(xs.len(), it.indexable());
D
Daniel Micay 已提交
2720
        for (i, elt) in xs.iter().enumerate() {
2721 2722 2723 2724 2725 2726
            assert_eq!(Some(elt), it.idx(i));
        }

    }

    #[test]
2727
    fn test_random_access_map() {
2728 2729
        let xs = [1, 2, 3, 4, 5];

2730
        let it = xs.iter().map(|x| *x);
2731
        assert_eq!(xs.len(), it.indexable());
D
Daniel Micay 已提交
2732
        for (i, elt) in xs.iter().enumerate() {
2733 2734 2735 2736 2737 2738 2739 2740
            assert_eq!(Some(*elt), it.idx(i));
        }
    }

    #[test]
    fn test_random_access_cycle() {
        let xs = [1, 2, 3, 4, 5];
        let empty: &[int] = [];
E
Erick Tryzelaar 已提交
2741
        check_randacc_iter(xs.iter().cycle().take(27), 27);
2742
        check_randacc_iter(empty.iter().cycle(), 0);
D
Daniel Micay 已提交
2743
    }
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756

    #[test]
    fn test_double_ended_range() {
        assert_eq!(range(11i, 14).invert().collect::<~[int]>(), ~[13i, 12, 11]);
        for _ in range(10i, 0).invert() {
            fail!("unreachable");
        }

        assert_eq!(range(11u, 14).invert().collect::<~[uint]>(), ~[13u, 12, 11]);
        for _ in range(10u, 0).invert() {
            fail!("unreachable");
        }
    }
2757

2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
    #[test]
    fn test_range() {
        assert_eq!(range(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4]);
        assert_eq!(range(0i, 5).invert().collect::<~[int]>(), ~[4, 3, 2, 1, 0]);
        assert_eq!(range(200, -5).collect::<~[int]>(), ~[]);
        assert_eq!(range(200, -5).invert().collect::<~[int]>(), ~[]);
        assert_eq!(range(200, 200).collect::<~[int]>(), ~[]);
        assert_eq!(range(200, 200).invert().collect::<~[int]>(), ~[]);
    }

2768 2769 2770 2771
    #[test]
    fn test_range_inclusive() {
        assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4, 5]);
        assert_eq!(range_inclusive(0i, 5).invert().collect::<~[int]>(), ~[5i, 4, 3, 2, 1, 0]);
2772
        assert_eq!(range_inclusive(200, -5).collect::<~[int]>(), ~[]);
2773
        assert_eq!(range_inclusive(200, -5).invert().collect::<~[int]>(), ~[]);
2774
        assert_eq!(range_inclusive(200, 200).collect::<~[int]>(), ~[200]);
2775
        assert_eq!(range_inclusive(200, 200).invert().collect::<~[int]>(), ~[200]);
2776
    }
2777

2778 2779 2780 2781
    #[test]
    fn test_range_step() {
        assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15]);
        assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5]);
2782
        assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
2783
        assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
2784 2785
        assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), ~[]);
        assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), ~[]);
2786 2787 2788 2789 2790 2791
    }

    #[test]
    fn test_range_step_inclusive() {
        assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15, 20]);
        assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5, 0]);
2792
        assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
2793
        assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
2794 2795
        assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), ~[]);
        assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), ~[200]);
2796 2797
    }

2798 2799 2800 2801 2802 2803
    #[test]
    fn test_reverse() {
        let mut ys = [1, 2, 3, 4, 5];
        ys.mut_iter().reverse_();
        assert_eq!(ys, [5, 4, 3, 2, 1]);
    }
2804
}