Skip to content

Commit 3ab5ec4

Browse files
committed
iterator: implement collect with FromIterator
This makes it take advantage of the size hint for pre-allocation.
1 parent 8779be3 commit 3ab5ec4

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

src/libstd/iterator.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ implementing the `Iterator` trait.
2020
#[allow(default_methods)]; // solid enough for the use case here
2121

2222
use cmp;
23-
use iter::{FromIter, Times};
23+
use iter::Times;
2424
use num::{Zero, One};
2525
use option::{Option, Some, None};
2626
use ops::{Add, Mul};
@@ -240,7 +240,7 @@ pub trait IteratorUtil<A> {
240240
fn advance(&mut self, f: &fn(A) -> bool) -> bool;
241241

242242
/// Loops through the entire iterator, collecting all of the elements into
243-
/// a container implementing `FromIter`.
243+
/// a container implementing `FromIterator`.
244244
///
245245
/// # Example
246246
///
@@ -249,7 +249,7 @@ pub trait IteratorUtil<A> {
249249
/// let b: ~[int] = a.iter().transform(|&x| x).collect();
250250
/// assert!(a == b);
251251
/// ~~~
252-
fn collect<B: FromIter<A>>(&mut self) -> B;
252+
fn collect<B: FromIterator<A, Self>>(&mut self) -> B;
253253

254254
/// Loops through `n` iterations, returning the `n`th element of the
255255
/// iterator.
@@ -411,8 +411,8 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
411411
}
412412

413413
#[inline]
414-
fn collect<B: FromIter<A>>(&mut self) -> B {
415-
FromIter::from_iter::<A, B>(|f| self.advance(f))
414+
fn collect<B: FromIterator<A, T>>(&mut self) -> B {
415+
FromIterator::from_iterator(self)
416416
}
417417

418418
/// Return the `n`th item yielded by an iterator.

src/libstd/vec.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2500,6 +2500,17 @@ impl<T> FromIter<T> for ~[T]{
25002500
}
25012501
}
25022502

2503+
#[cfg(stage0)]
2504+
impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
2505+
pub fn from_iterator(iterator: &mut T) -> ~[A] {
2506+
let mut xs = ~[];
2507+
for iterator.advance |x| {
2508+
xs.push(x);
2509+
}
2510+
xs
2511+
}
2512+
}
2513+
25032514
#[cfg(not(stage0))]
25042515
impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
25052516
pub fn from_iterator(iterator: &mut T) -> ~[A] {

0 commit comments

Comments
 (0)