]> git.lizzy.rs Git - rust.git/commitdiff
iterator: add a FromIterator trait
authorDaniel Micay <danielmicay@gmail.com>
Fri, 21 Jun 2013 11:57:22 +0000 (07:57 -0400)
committerDaniel Micay <danielmicay@gmail.com>
Sat, 22 Jun 2013 19:59:59 +0000 (15:59 -0400)
This is able to take advantage of the lower bound from the size hint.

src/libstd/iterator.rs
src/libstd/vec.rs

index fa27f4560c146390b6ab88c69831cb2b1c205652..46e059355941f6156dc59a62b765f1325a320c83 100644 (file)
 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.
@@ -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]);
     }
 
index b03b6efcaaf3119c271f8986c1020db04dad57c4..62b42eebfbbd4683d60821609fb5e3686c7ae893 100644 (file)
@@ -19,7 +19,7 @@
 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 @@ pub fn from_iter(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[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};