Skip to content

Instantly share code, notes, and snippets.

@boxdot
Last active November 9, 2022 12:03
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boxdot/0e707be10d86a610296483ab78f6b121 to your computer and use it in GitHub Desktop.
Save boxdot/0e707be10d86a610296483ab78f6b121 to your computer and use it in GitHub Desktop.
Async stdin reading with thread and futures in Rust
extern crate futures;
use std::io::{self, BufRead};
use std::thread;
use futures::{Future, Sink, Stream};
use futures::stream::BoxStream;
use futures::sync::mpsc::channel;
fn stdin() -> impl Stream<String, io::Error> {
let (mut tx, rx) = channel(1);
thread::spawn(move || {
let input = io::stdin();
for line in input.lock().lines() {
match tx.send(line).wait() {
Ok(s) => tx = s,
Err(_) => break,
}
}
});
rx.then(|e| e.unwrap())
}
fn main() {
stdin()
.for_each(|string| {
println!("{}", string);
Ok(())
})
.wait()
.unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment