smol/examples/timer-timeout.rs

29 lines
735 B
Rust
Raw Normal View History

2020-03-29 15:59:28 +00:00
use std::time::Duration;
2020-03-26 13:57:06 +00:00
2020-03-29 15:59:28 +00:00
use anyhow::{bail, Result};
2020-04-20 15:45:14 +00:00
use futures::future::{select, Either};
2020-03-29 15:59:28 +00:00
use futures::io::BufReader;
use futures::prelude::*;
use smol::Timer;
async fn timeout<T>(dur: Duration, f: impl Future<Output = T>) -> Result<T> {
2020-04-01 19:40:27 +00:00
futures::pin_mut!(f);
2020-04-20 15:45:14 +00:00
match select(f, Timer::after(dur)).await {
2020-04-01 19:40:27 +00:00
Either::Left((out, _)) => Ok(out),
Either::Right(_) => bail!("timed out"),
2020-03-29 15:59:28 +00:00
}
}
fn main() -> Result<()> {
smol::run(async {
2020-03-31 16:04:16 +00:00
let mut stdin = BufReader::new(smol::reader(std::io::stdin()));
2020-03-29 15:59:28 +00:00
let mut line = String::new();
let dur = Duration::from_secs(5);
timeout(dur, stdin.read_line(&mut line)).await??;
println!("Line: {}", line);
Ok(())
})
}