Skip to content

Commit c934266

Browse files
committed
iterator: add a FromIterator trait
This is able to take advantage of the lower bound from the size hint.
1 parent 468cbd9 commit c934266

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/libstd/iterator.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ use ops::{Add, Mul};
2727
use cmp::Ord;
2828
use clone::Clone;
2929

30+
/// Conversion from an `Iterator`
31+
pub trait FromIterator<A, T: Iterator<A>> {
32+
/// Build a container with elements from an external iterator.
33+
pub fn from_iterator(iterator: &mut T) -> Self;
34+
}
35+
3036
/// An interface for dealing with "external iterators". These types of iterators
3137
/// can be resumed at any time as all state is stored internally as opposed to
3238
/// being located on the call stack.
@@ -931,7 +937,7 @@ mod tests {
931937
#[test]
932938
fn test_counter_from_iter() {
933939
let mut it = Counter::new(0, 5).take_(10);
934-
let xs: ~[int] = iter::FromIter::from_iter::<int, ~[int]>(|f| it.advance(f));
940+
let xs: ~[int] = FromIterator::from_iterator(&mut it);
935941
assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
936942
}
937943

src/libstd/vec.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater};
1919
use clone::Clone;
2020
use old_iter::BaseIter;
2121
use old_iter;
22-
use iterator::{Iterator, IteratorUtil};
22+
use iterator::{FromIterator, Iterator, IteratorUtil};
2323
use iter::FromIter;
2424
use kinds::Copy;
2525
use libc;
@@ -2511,6 +2511,18 @@ impl<T> FromIter<T> for ~[T]{
25112511
}
25122512
}
25132513

2514+
#[cfg(not(stage0))]
2515+
impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
2516+
pub fn from_iterator(iterator: &mut T) -> ~[A] {
2517+
let (lower, _) = iterator.size_hint();
2518+
let mut xs = with_capacity(lower.get_or_zero());
2519+
for iterator.advance |x| {
2520+
xs.push(x);
2521+
}
2522+
xs
2523+
}
2524+
}
2525+
25142526
#[cfg(test)]
25152527
mod tests {
25162528
use option::{None, Option, Some};

0 commit comments

Comments
 (0)