summary refs log tree commit diff
path: root/src/engine.rs
diff options
context:
space:
mode:
authorSophie Forrest <git@sophieforrest.com>2024-08-30 23:35:45 +1200
committerSophie Forrest <git@sophieforrest.com>2024-08-30 23:35:45 +1200
commitf752160c6ebcee747a61e6febc4789d0b04ccd12 (patch)
tree76e123279abbd1797ba281f35cbcba61136ef7bd /src/engine.rs
parent98d7946709032aae5e1d0d35cff78efc55550900 (diff)
feat: implement generic engine for executor
Diffstat (limited to '')
-rw-r--r--src/engine.rs61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/engine.rs b/src/engine.rs
new file mode 100644
index 0000000..d57d6a4
--- /dev/null
+++ b/src/engine.rs
@@ -0,0 +1,61 @@
+//! Executor engine implementation for Brainfuck interpreter.
+//!
+//! This predominantly allows implementation of a [`u16`] executor.
+
+use std::io::Read;
+
+use crate::executor::{Error, Executor};
+
+/// Generic engine implementation for the Brainfuck interpreter.
+pub trait Engine<T> {
+	/// Read one byte from stdin.
+	///
+	/// # Errors
+	///
+	/// This function will return an error if it is unable to read from stdin,
+	/// or if it indexes out of bounds.
+	fn read_byte() -> Result<T, Error>;
+
+	/// Write the provided byte to stdout.
+	///
+	/// # Errors
+	///
+	/// This function will return an error if it is unable to write a byte to
+	/// stdout.
+	fn write_byte(byte: T) -> Result<(), Error>;
+}
+
+impl Engine<u8> for Executor {
+	fn read_byte() -> Result<u8, Error> {
+		let mut input: [u8; 1] = [0; 1];
+
+		std::io::stdin().read_exact(&mut input)?;
+
+		Ok(input[0])
+	}
+
+	fn write_byte(byte: u8) -> Result<(), Error> {
+		print!("{}", char::from(byte));
+
+		Ok(())
+	}
+}
+
+impl Engine<u16> for Executor {
+	fn read_byte() -> Result<u16, Error> {
+		let mut input: [u8; 2] = [0; 2];
+
+		std::io::stdin().read_exact(&mut input)?;
+
+		#[expect(clippy::pedantic)]
+		let number = ((input[0] as u16) << 8i32) | input[1] as u16;
+
+		Ok(number)
+	}
+
+	fn write_byte(byte: u16) -> Result<(), Error> {
+		print!("{}", String::from_utf16_lossy(&[byte]));
+
+		Ok(())
+	}
+}