Skip to content

Commit 857d433

Browse files
committed
Added IteratorUtil::collect
1 parent af2086a commit 857d433

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libstd/iterator.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ implementing the `Iterator` trait.
1919

2020
use cmp;
2121
use iter;
22+
use iter::FromIter;
2223
use num::{Zero, One};
2324
use prelude::*;
2425

@@ -255,6 +256,20 @@ pub trait IteratorUtil<A> {
255256
/// ~~~
256257
fn to_vec(&mut self) -> ~[A];
257258

259+
/// Loops through the entire iterator, collecting all of the elements into
260+
/// a container implementing `FromIter`.
261+
///
262+
/// # Example
263+
///
264+
/// ~~~ {.rust}
265+
/// use std::iterator::*;
266+
///
267+
/// let a = [1, 2, 3, 4, 5];
268+
/// let b: ~[int] = a.iter().transform(|&x| x).collect();
269+
/// assert!(a == b);
270+
/// ~~~
271+
fn collect<B: FromIter<A>>(&mut self) -> B;
272+
258273
/// Loops through `n` iterations, returning the `n`th element of the
259274
/// iterator.
260275
///
@@ -419,6 +434,11 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
419434
iter::to_vec::<A>(|f| self.advance(f))
420435
}
421436

437+
#[inline(always)]
438+
fn collect<B: FromIter<A>>(&mut self) -> B {
439+
FromIter::from_iter::<A, B>(|f| self.advance(f))
440+
}
441+
422442
/// Return the `n`th item yielded by an iterator.
423443
#[inline(always)]
424444
fn nth(&mut self, mut n: uint) -> Option<A> {
@@ -1062,6 +1082,13 @@ mod tests {
10621082
assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None);
10631083
}
10641084

1085+
#[test]
1086+
fn test_collect() {
1087+
let a = [1, 2, 3, 4, 5];
1088+
let b: ~[int] = a.iter().transform(|&x| x).collect();
1089+
assert_eq!(a, b);
1090+
}
1091+
10651092
#[test]
10661093
fn test_all() {
10671094
let v = ~&[1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)