From e4cdcf4f5082f90abd9e259ccc215ecbb1973ab5 Mon Sep 17 00:00:00 2001
From: Ben Bridle <bridle.benjamin@gmail.com>
Date: Mon, 29 Jan 2024 18:31:45 +1300
Subject: 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.
---
 src/devices/stream.rs | 31 +++++++++++++++++--------------
 1 file 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();
+    }
+}
-- 
cgit v1.2.3-70-g09d2