Last active
February 21, 2019 05:58
-
-
Save luben/c6ed8332f09dc9b78da888dc9b626c7b to your computer and use it in GitHub Desktop.
Naive streams
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
#[derive(Clone)] | |
struct Repeat { | |
current: u32, | |
end: u32, | |
} | |
impl Repeat { | |
fn new(current: u32, end: u32) -> Self { | |
Repeat {current, end} | |
} | |
} | |
impl Future for Repeat { | |
type Error = (); | |
type Item = Option<(u32, Self)>; | |
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { | |
if self.current < self.end { | |
Ok(Async::Ready(Some((self.current, Repeat::new(self.current + 1, self.end))))) | |
} else { | |
Ok(Async::Ready(None)) | |
} | |
} | |
} | |
fn main() { | |
let pool = CpuPool::new(1); | |
let f = loop_fn(Repeat::new(10, 20), |mut stream| match stream.poll() { | |
Ok(Async::Ready(Some((item, next)))) => { | |
println!("Item: {}", item); | |
Ok(Loop::Continue(next)) | |
} | |
Ok(Async::Ready(None)) => Ok(Loop::Break(stream)), | |
Ok(Async::NotReady) => Ok(Loop::Continue(stream)), | |
Err(err) => Err(err), | |
}); | |
pool.spawn(f).wait().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment