0

Is it possible to read and write to an active input stream in Rust?

assuming this code:

print!("[{}]>> ", line);
io::stdout().flush();
line += 1;

let mut input = String::new();
io::stdin().read_line(&mut input)?;

I would like to read individual characters as they are being inputted. My use-case would be for a REPL application where the user is asked for an input:

[0]>>

and in the case ( is inputted:

[0]>> (

I would like to auto-match the closing parenthesis and place the cursor in between the parentheses:

[0]>> ( )

For this functionality, I would need to be able to both read the individual characters and be able to mutate the stream structure while receiving input, and I am currently unaware of how to do so.

Any help appreciated

Its Me
  • 174
  • 1
  • 8
  • You can't write to an input stream, but you could read user input without echoing back to the terminal, and print your modified version of their input. A curses-like library could probably handle some of that. – Jeremy Meadows Jul 22 '22 at 12:24
  • The biggest problem here is that the user input doesn't even reach the program until the input pipe gets flushed externally. You might have to switch the console to raw mode, with all of the problems that come with it. [`crossterm`](https://docs.rs/crossterm/latest/crossterm/index.html) might help you with some of that; otherwise your code will become heavily OS-dependent. – Finomnis Jul 22 '22 at 14:40

0 Answers0