iterator: add an Extendable trait

This commit is contained in:
Daniel Micay 2013-07-27 17:41:30 -04:00
parent ffe549daf5
commit fe955e7b06
2 changed files with 18 additions and 1 deletions

View file

@ -32,6 +32,12 @@ pub trait FromIterator<A, T: Iterator<A>> {
fn from_iterator(iterator: &mut T) -> Self;
}
/// A type growable from an `Iterator` implementation
pub trait Extendable<A, T: Iterator<A>>: FromIterator<A, T> {
/// Extend a container with the elements yielded by an iterator
fn extend(&mut self, iterator: &mut T);
}
/// 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.

View file

@ -2224,7 +2224,7 @@ impl<T> Iterator<T> for VecConsumeRevIterator<T> {
}
impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
pub fn from_iterator(iterator: &mut T) -> ~[A] {
fn from_iterator(iterator: &mut T) -> ~[A] {
let (lower, _) = iterator.size_hint();
let mut xs = with_capacity(lower);
for iterator.advance |x| {
@ -2234,6 +2234,17 @@ impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
}
}
impl<A, T: Iterator<A>> Extendable<A, T> for ~[A] {
fn extend(&mut self, iterator: &mut T) {
let (lower, _) = iterator.size_hint();
let len = self.len();
self.reserve(len + lower);
for iterator.advance |x| {
self.push(x);
}
}
}
#[cfg(test)]
mod tests {
use option::{None, Option, Some};