comparison 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
comparison
equal deleted inserted replaced
588:038734052b20 589:f2508125adf1
2 extern crate tokio_core; 2 extern crate tokio_core;
3 extern crate futures; 3 extern crate futures;
4 4
5 use std::time::Duration; 5 use std::time::Duration;
6 use std::cell::RefCell; 6 use std::cell::RefCell;
7 use std::io::{self, Read, Write};
7 8
8 use tokio_core::reactor::Interval; 9 use tokio_core::reactor::Interval;
9 use tokio_core::reactor::Core; 10 use tokio_core::reactor::Core;
10 use tokio_core::reactor::Handle; 11 use tokio_core::reactor::Handle;
11 use futures::Stream; 12 use futures::{Future, failed, Poll, Async, Stream};
12 use futures::Future;
13 use futures::IntoFuture;
14 13
15 pub struct Reading { 14 pub struct Reading {
16 name: String, 15 name: String,
17 value: Option<f32>, 16 value: Option<f32>,
18 } 17 }
19 18
20 pub type Readings = Vec<Reading>; 19 pub type Readings = Vec<Reading>;
21 20
22 pub struct Sensor { 21 pub struct Sensor {
23 current: f32, 22 current: f32,
23 }
24
25 struct Periodic<T> {
26 interval: Interval,
27 }
28
29 trait Ticker {
30 type TickItem;
31 fn tick(&self) -> Self::TickItem;
32 }
33
34 impl<T: Ticker> Stream for Periodic<T> {
35 type Item = T::TickItem;
36 type Error = io::Error;
37
38 fn poll(&mut self) -> Poll<Option<Self::Item>, io::Error> {
39 self.interval.poll().map(|a| {
40 if let Async::Ready(t) = a {
41 Async::Ready(self.tick())
42 } else {
43 a
44 }
45 })
46 }
24 } 47 }
25 48
26 impl Sensor { 49 impl Sensor {
27 50
28 fn step(&mut self) -> Readings { 51 fn step(&mut self) -> Readings {
34 57
35 pub fn new() -> Sensor { 58 pub fn new() -> Sensor {
36 Sensor { current: 22.0 } 59 Sensor { current: 22.0 }
37 } 60 }
38 61
39 pub fn run(handle: &Handle) -> impl Stream<Item=Readings> { 62 pub fn run(handle: &Handle) -> Box<Stream<Item=Readings, Error=io::Error>> {
40 let mut s = Sensor::new(); 63 let mut s = Sensor::new();
41 64
42 let dur = Duration::from_millis(400); 65 let dur = Duration::from_millis(400);
43 Interval::new(dur, handle).unwrap().map(move |()| { 66 Interval::new(dur, handle).unwrap().map(move |()| {
44 println!("each one"); 67 println!("each one");