From c9342663df3e705f6fe380f3d4f46c4a7be8035e Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Fri, 21 Jun 2013 07:57:22 -0400 Subject: [PATCH] iterator: add a FromIterator trait This is able to take advantage of the lower bound from the size hint. --- src/libstd/iterator.rs | 8 +++++++- src/libstd/vec.rs | 14 +++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index fa27f4560c1..46e05935594 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -27,6 +27,12 @@ use ops::{Add, Mul}; use cmp::Ord; use clone::Clone; +/// Conversion from an `Iterator` +pub trait FromIterator> { + /// 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. @@ -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::(|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]); } diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index b03b6efcaaf..62b42eebfbb 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -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; @@ -2511,6 +2511,18 @@ impl FromIter for ~[T]{ } } +#[cfg(not(stage0))] +impl> FromIterator 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};