4

I am trying to implement a command line editing library in Rust.

To handle the ESC key properly, I need to wait for the rest of an escape sequence that may never arrive.

Currently, I am using:

let stdin = io::stdin();
let mut chars = stdin.lock().chars();
let mut ch = try!(chars.next().unwrap());

but there seems to be no way to specify a timeout. Should I try to mix Rust IO with the poll function?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Gwenn
  • 55
  • 4
  • Possible duplicate of [How can I read one character from stdin without having to hit enter?](http://stackoverflow.com/questions/26321592/how-can-i-read-one-character-from-stdin-without-having-to-hit-enter) – oli_obk Nov 11 '15 at 09:12
  • No - this is language-specific, and the suggested duplicate does not address Rust. – Thomas Dickey Nov 11 '15 at 09:28
  • 2
    By itself, Rust has no features for this, but can call system-specific functions to do it -- but OP gave no clues regarding which systems are of interest. For UTF-8, there is the complication of whether it is acceptable to timeout in the middle of a multibyte input sequence, etc. – Thomas Dickey Nov 11 '15 at 11:41

1 Answers1

0

The async-std crate has out-of-the-box support for this:

use async_std::io;
use std::time::Duration;

#[async_std::main]
async fn main() -> std::io::Result<()> {
    let input = io::timeout(Duration::from_secs(5), async {
        let stdin = io::stdin();
        let mut line = String::new();
        stdin.read_line(&mut line).await?;
        Ok(line)
    })
    .await;

    println!("{:?}", input);

    Ok(())
}
schrieveslaach
  • 1,689
  • 1
  • 15
  • 32