diff options
author | Ben Bridle <bridle.benjamin@gmail.com> | 2024-01-29 18:31:45 +1300 |
---|---|---|
committer | Ben Bridle <bridle.benjamin@gmail.com> | 2024-01-31 07:37:54 +1300 |
commit | e4cdcf4f5082f90abd9e259ccc215ecbb1973ab5 (patch) | |
tree | 4e640ec225e65001c441fdefbce88d8328d835ee | |
parent | 521e525763723cbc5d65b37ff47f34af48f50a2f (diff) | |
download | bedrock-pc-e4cdcf4f5082f90abd9e259ccc215ecbb1973ab5.zip |
Change stream device to use buffered streams
Wrapping stdin and stdout with BufReader and BufWriter makes reads and
writes more efficient by bundling multiple characters into a single
read or write operation. In practice, this hasn't made a difference to
running the numbers demo, but that demo spends the majority of processor
time converting values to decimal strings.
-rw-r--r-- | src/devices/stream.rs | 31 |
1 files changed, 17 insertions, 14 deletions
diff --git a/src/devices/stream.rs b/src/devices/stream.rs index 3d376b6..7f69a7a 100644 --- a/src/devices/stream.rs +++ b/src/devices/stream.rs @@ -1,14 +1,15 @@ -use std::io::{Read, Write, Stdin, Stdout}; +use std::io::{Read, Write}; +use std::io::{BufReader, BufWriter}; +use std::io::{Stdin, Stdout}; pub struct StreamDevice { pub wake_flag: bool, pub input_control: bool, pub output_control: bool, - pub read_queue: Vec<u8>, - pub stdin: Stdin, - pub stdout: Stdout, + pub stdin: BufReader<Stdin>, + pub stdout: BufWriter<Stdout>, } impl StreamDevice { @@ -18,24 +19,20 @@ impl StreamDevice { input_control: true, output_control: true, - read_queue: Vec::with_capacity(256), - stdin: std::io::stdin(), - stdout: std::io::stdout(), + stdin: BufReader::new(std::io::stdin()), + stdout: BufWriter::new(std::io::stdout()), } } - // pub fn fetch_stdin(&mut self) { - // match self.stdin.read(&mut self.read_queue) { - // Ok() => (), - // Err() => (), - // } - // } + pub fn read_queue_len(&self) -> usize { + self.stdin.buffer().len() + } pub fn read_stdin(&mut self) -> u8 { let mut buffer = [0; 1]; match self.stdin.read_exact(&mut buffer) { - Ok(()) => buffer[0], + Ok(_) => buffer[0], Err(_) => 0, } } @@ -44,3 +41,9 @@ impl StreamDevice { self.stdout.write_all(&[val]).unwrap(); } } + +impl Drop for StreamDevice { + fn drop(&mut self) { + self.stdout.flush().unwrap(); + } +} |