Mercurial > templog
diff rust/src/main.rs @ 589:f2508125adf1 rust
Try using traits for periodic stream
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Wed, 21 Dec 2016 08:16:13 +0800 |
parents | 038734052b20 |
children | dccd8504aa38 |
line wrap: on
line diff
--- a/rust/src/main.rs Fri Dec 16 01:10:57 2016 +0800 +++ b/rust/src/main.rs Wed Dec 21 08:16:13 2016 +0800 @@ -4,13 +4,12 @@ use std::time::Duration; use std::cell::RefCell; +use std::io::{self, Read, Write}; use tokio_core::reactor::Interval; use tokio_core::reactor::Core; use tokio_core::reactor::Handle; -use futures::Stream; -use futures::Future; -use futures::IntoFuture; +use futures::{Future, failed, Poll, Async, Stream}; pub struct Reading { name: String, @@ -23,6 +22,30 @@ current: f32, } +struct Periodic<T> { + interval: Interval, +} + +trait Ticker { + type TickItem; + fn tick(&self) -> Self::TickItem; +} + +impl<T: Ticker> Stream for Periodic<T> { + type Item = T::TickItem; + type Error = io::Error; + + fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> { + self.interval.poll().map(|a| { + if let Async::Ready(t) = a { + Async::Ready(self.tick()) + } else { + a + } + }) + } +} + impl Sensor { fn step(&mut self) -> Readings { @@ -36,7 +59,7 @@ Sensor { current: 22.0 } } - pub fn run(handle: &Handle) -> impl Stream<Item=Readings> { + pub fn run(handle: &Handle) -> Box<Stream<Item=Readings, Error=io::Error>> { let mut s = Sensor::new(); let dur = Duration::from_millis(400);