smol/examples/timer-timeout.rs

31 lines
758 B
Rust
Raw Normal View History

2020-04-21 15:51:07 +00:00
// TODO: document
use std::io;
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;
2020-04-21 15:51:07 +00:00
async fn timeout<T>(dur: Duration, f: impl Future<Output = io::Result<T>>) -> io::Result<T> {
futures::select! {
out = f.fuse() => out,
_ = Timer::after(dur).fuse() => {
Err(io::Error::from(io::ErrorKind::TimedOut))
}
2020-03-29 15:59:28 +00:00
}
}
fn main() -> Result<()> {
smol::run(async {
let mut line = String::new();
2020-04-21 15:51:07 +00:00
let mut stdin = BufReader::new(smol::reader(std::io::stdin()));
2020-03-29 15:59:28 +00:00
2020-04-21 15:51:07 +00:00
timeout(Duration::from_secs(5), stdin.read_line(&mut line)).await?;
2020-03-29 15:59:28 +00:00
println!("Line: {}", line);
2020-04-21 15:51:07 +00:00
2020-03-29 15:59:28 +00:00
Ok(())
})
}