# HG changeset patch # User Matt Johnston # Date 1482279373 -28800 # Node ID f2508125adf15ec4091f6d31ead8fcb8bfbe9b78 # Parent 038734052b2021e46e1be80ec609bb4408ccf215 Try using traits for periodic stream diff -r 038734052b20 -r f2508125adf1 rust/src/main.rs --- 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 { + interval: Interval, +} + +trait Ticker { + type TickItem; + fn tick(&self) -> Self::TickItem; +} + +impl Stream for Periodic { + type Item = T::TickItem; + type Error = io::Error; + + fn poll(&mut self) -> Poll, 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 { + pub fn run(handle: &Handle) -> Box> { let mut s = Sensor::new(); let dur = Duration::from_millis(400);