use std::io::{self, Read};
use std::sync::mpsc;
use std::thread;
pub fn async_stdin() -> AsyncReader {
let (send, recv) = mpsc::channel();
thread::spawn(move || {
let stdin = io::stdin();
for i in stdin.lock().bytes() {
if send.send(i).is_err() {
return;
}
}
});
AsyncReader {
recv: recv,
}
}
pub struct AsyncReader {
recv: mpsc::Receiver<io::Result<u8>>,
}
impl Read for AsyncReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut total = 0;
loop {
match self.recv.try_recv() {
Ok(Ok(b)) => {
buf[total] = b;
total += 1;
if total == buf.len() {
break;
}
},
Ok(Err(e)) => return Err(e),
Err(_) => break,
}
}
Ok(total)
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Read;
#[test]
fn test_async_stdin() {
let stdin = async_stdin();
stdin.bytes().next();
}
}