diff options
| author | Daniel Micay <danielmicay@gmail.com> | 2013-06-24 01:21:32 -0400 |
|---|---|---|
| committer | Daniel Micay <danielmicay@gmail.com> | 2013-06-24 01:35:15 -0400 |
| commit | 3ab5ec4b7c854290ad1bc5192c70cbc0856a5fa7 (patch) | |
| tree | bd554d39b65fb6deda79a06a17ad258b189c91b1 /src/libstd | |
| parent | 8779be39e1a6e064d75cc32ad3610fad9a4fa9a6 (diff) | |
| download | rust-3ab5ec4b7c854290ad1bc5192c70cbc0856a5fa7.tar.gz rust-3ab5ec4b7c854290ad1bc5192c70cbc0856a5fa7.zip | |
iterator: implement `collect` with FromIterator
This makes it take advantage of the size hint for pre-allocation.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/iterator.rs | 10 | ||||
| -rw-r--r-- | src/libstd/vec.rs | 11 |
2 files changed, 16 insertions, 5 deletions
diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index 46e05935594..d96191f296d 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -20,7 +20,7 @@ implementing the `Iterator` trait. #[allow(default_methods)]; // solid enough for the use case here use cmp; -use iter::{FromIter, Times}; +use iter::Times; use num::{Zero, One}; use option::{Option, Some, None}; use ops::{Add, Mul}; @@ -240,7 +240,7 @@ pub trait IteratorUtil<A> { fn advance(&mut self, f: &fn(A) -> bool) -> bool; /// Loops through the entire iterator, collecting all of the elements into - /// a container implementing `FromIter`. + /// a container implementing `FromIterator`. /// /// # Example /// @@ -249,7 +249,7 @@ pub trait IteratorUtil<A> { /// let b: ~[int] = a.iter().transform(|&x| x).collect(); /// assert!(a == b); /// ~~~ - fn collect<B: FromIter<A>>(&mut self) -> B; + fn collect<B: FromIterator<A, Self>>(&mut self) -> B; /// Loops through `n` iterations, returning the `n`th element of the /// iterator. @@ -411,8 +411,8 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T { } #[inline] - fn collect<B: FromIter<A>>(&mut self) -> B { - FromIter::from_iter::<A, B>(|f| self.advance(f)) + fn collect<B: FromIterator<A, T>>(&mut self) -> B { + FromIterator::from_iterator(self) } /// Return the `n`th item yielded by an iterator. diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index aeb5b000747..dd3c23d1084 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -2500,6 +2500,17 @@ impl<T> FromIter<T> for ~[T]{ } } +#[cfg(stage0)] +impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] { + pub fn from_iterator(iterator: &mut T) -> ~[A] { + let mut xs = ~[]; + for iterator.advance |x| { + xs.push(x); + } + xs + } +} + #[cfg(not(stage0))] impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] { pub fn from_iterator(iterator: &mut T) -> ~[A] { |
