Created
April 23, 2015 23:41
-
-
Save anonymous/1430c9313608719ba7ba to your computer and use it in GitHub Desktop.
This file contains 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>; | |
fn map<B, F>(self, f: F) -> Map<Self, F> | |
where Self: Sized, F: FnMut(Self::Item) -> B { | |
Map { iter: self, f: f } | |
} | |
} | |
struct Map<I, F> { | |
iter: I, | |
f: F, | |
} | |
impl<'a, B, I, F> StreamingIterator<'a> for Map<I, F> | |
where F: for <'b> FnMut(<I as StreamingIterator<'b>>::Item) -> B, | |
I: for <'b> StreamingIterator<'b> { | |
type Item = B; | |
#[inline] | |
fn next(&'a mut self) -> Option<B> { | |
match self.iter.next() { | |
None => None, | |
Some(a) => Some((self.f)(a)), | |
} | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::StreamingIterator; | |
struct Buffer<T> { | |
data: Vec<T>, | |
pos: usize | |
} | |
impl<'a, T> 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 | |
} | |
} | |
#[test] | |
fn buffer2() { | |
let b = Buffer { data: vec![1, 2, 3], pos: 0 }; | |
let mut it = b.map(|&x| 2 * x); | |
while let Some(x) = it.next() { | |
println!("{}", x); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment