Futures in Rust can be polled without blocking to check if the future is ready (and do some work in the process). With that in mind, is it possible to "check" if a future is ready, without consuming its output?
Possible scenario
stdin
would be polled if there is any data, and take action on the input (playground):
async fn read_input_if_available() {
use tokio::io::AsyncReadExt;
let mut stdin = tokio::io::stdin();
// if !stdin.ready() {
// return;
// }
let mut input = String::new();
let mut buffer = [0_u8; 1024];
while let Ok(bytes) = stdin.read(&mut buffer).await {
if let Ok(string) = std::str::from_utf8(&buffer[..bytes]) {
input.push_str(string);
}
}
// Take action on `input` here
}
When the code hits the await
, it will not proceed until there is something on stdin, even if just waiting for an EOF
.
I used tokio::io::Stdin
because it is simpler for a self-contained example, but the question is about Rust futures in general.