use std::sync::mpsc::{channel, Receiver}; use std::thread::spawn; use std::{ collections::VecDeque, io::{stdin, Read}, }; pub struct StdinPeekable { buffer: VecDeque, rx: Receiver, } impl StdinPeekable { pub fn new() -> Self { let (tx, rx) = channel::(); spawn(move || { for byte in stdin().bytes() { if let Ok(byte) = byte { tx.send(byte).unwrap(); } } }); Self { rx, buffer: Default::default(), } } pub fn next(&mut self) -> Option { self.buffer.extend(self.rx.try_iter()); self.buffer.pop_front() } pub fn peek(&mut self) -> Option { self.buffer.extend(self.rx.try_iter()); self.buffer.front().copied() } }