Created
February 12, 2016 16:43
-
-
Save anonymous/1167dbdb413e9383c457 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait StreamingIterator<'a> { | |
type Item; | |
fn next(&'a mut self) -> Option<Self::Item>; | |
} | |
struct Buffer<T> { | |
data: Vec<T>, | |
pos: usize | |
} | |
impl<'a, T: 'a> StreamingIterator<'a> for Buffer<T> { | |
type Item = &'a T; | |
fn next(&'a mut self) -> Option<&'a T> { | |
let x = self.data.get(self.pos); | |
self.pos += 1; | |
x | |
} | |
} | |
impl<'a, I: Iterator> StreamingIterator<'a> for I { | |
type Item = I::Item; | |
fn next(&mut self) -> Option<I::Item> { | |
Iterator::next(self) | |
} | |
} | |
fn cloned_collect<T, I>(mut iter: I) -> Vec<T> | |
where I: for<'a> StreamingIterator<'a, Item=&'a T>, | |
T: Clone | |
{ | |
let mut v = vec![]; | |
while let Some(x) = iter.next() { | |
v.push(x.clone()); | |
} | |
v | |
} | |
fn old_collect<T, I>(mut iter: I) -> Vec<T> | |
where I: for<'a> StreamingIterator<'a, Item=T> | |
{ | |
let mut v = vec![]; | |
while let Some(x) = iter.next() { | |
v.push(x); | |
} | |
v | |
} | |
fn main() { | |
println!("{:?}", old_collect( | |
cloned_collect(Buffer { | |
data: vec![0u8, 2, 3, 5], | |
pos: 1 | |
}).iter() | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment