Skip to content

Instantly share code, notes, and snippets.

@euank
Last active December 29, 2017 04:07
Show Gist options
  • Save euank/028fbd684d9a9f6c09030236fec7d899 to your computer and use it in GitHub Desktop.
Save euank/028fbd684d9a9f6c09030236fec7d899 to your computer and use it in GitHub Desktop.
//! If you're on a Unix system, try something like:
//!
//! `yes | cargo run --example count_keys`
//!
//! (Originally from
//! https://github.com/paulkernfeld/tokio-stdin/blob/master/examples/count_keys.rs)
extern crate futures;
extern crate tokio_stdin;
extern crate tokio_timer;
use futures::stream::Stream;
use futures::stream;
use std::time::Duration;
use tokio_stdin::spawn_stdin_stream_unbounded;
use tokio_timer::{Timer, TimerError};
#[derive(Debug)]
enum Error {
Timer(TimerError),
Stdin(()),
}
#[derive(Debug)]
enum Event {
Byte,
Second,
}
fn main() {
let seconds_stream = Timer::default()
.interval(Duration::from_secs(1))
.map(|()| Some(Event::Second))
.map_err(Error::Timer);
let stdin_stream = spawn_stdin_stream_unbounded()
.map(|_| Some(Event::Byte))
.map_err(Error::Stdin)
.chain(stream::iter_result(vec![Ok(None)]));
let mut n_bytes = 0;
let mut n_seconds = 0;
let mut exit = false;
let rate = seconds_stream.select(stdin_stream);
for event in rate.wait() {
match event {
Ok(Some(Event::Byte)) => {
n_bytes += 1;
}
Ok(Some(Event::Second)) => {
n_seconds += 1;
println!("{} bytes in {} seconds", n_bytes, n_seconds);
if exit { return; }
}
Ok(None) => {
println!("stdin closed");
exit = true;
}
Err(e) => eprintln!("error {:?}", e),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment