Skip to content

Commit

Permalink
iterator: add a FromIterator trait
Browse files Browse the repository at this point in the history
This is able to take advantage of the lower bound from the size hint.
  • Loading branch information
thestinger committed Jun 22, 2013
1 parent 468cbd9 commit c934266
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/libstd/iterator.rs
Expand Up @@ -27,6 +27,12 @@ use ops::{Add, Mul};
use cmp::Ord;
use clone::Clone;

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

/// 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.
Expand Down Expand Up @@ -931,7 +937,7 @@ mod tests {
#[test]
fn test_counter_from_iter() {
let mut it = Counter::new(0, 5).take_(10);
let xs: ~[int] = iter::FromIter::from_iter::<int, ~[int]>(|f| it.advance(f));
let xs: ~[int] = FromIterator::from_iterator(&mut it);
assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
}

Expand Down
14 changes: 13 additions & 1 deletion src/libstd/vec.rs
Expand Up @@ -19,7 +19,7 @@ use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater};
use clone::Clone;
use old_iter::BaseIter;
use old_iter;
use iterator::{Iterator, IteratorUtil};
use iterator::{FromIterator, Iterator, IteratorUtil};
use iter::FromIter;
use kinds::Copy;
use libc;
Expand Down Expand Up @@ -2511,6 +2511,18 @@ impl<T> FromIter<T> for ~[T]{
}
}

#[cfg(not(stage0))]
impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
pub fn from_iterator(iterator: &mut T) -> ~[A] {
let (lower, _) = iterator.size_hint();
let mut xs = with_capacity(lower.get_or_zero());
for iterator.advance |x| {
xs.push(x);
}
xs
}
}

#[cfg(test)]
mod tests {
use option::{None, Option, Some};
Expand Down

0 comments on commit c934266

Please sign in to comment.