summary refs log tree commit diff
path: root/src/engine.rs
blob: 508178ad2234e58149d5bb4b263a6ba5ec3f1a98 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//! 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)?;

		let number = ((u16::from(input[0])) << 8i32) | u16::from(input[1]);

		Ok(number)
	}

	fn write_byte(byte: u16) -> Result<(), Error> {
		print!("{}", String::from_utf16_lossy(&[byte]));

		Ok(())
	}
}