use std::{
fs::File,
path::Path,
io::{Read, Write},
ops::{Deref, DerefMut},
};
pub use error::{Error, Result};
pub mod error;
pub const DEFAULT_MAX_CELL_VALUE: u32 = 255;
pub enum Reader<'a> {
Value(Box<dyn Read>),
Ref(&'a mut dyn Read),
}
pub enum Writer<'a> {
Value(Box<dyn Write>),
Ref(&'a mut dyn Write),
}
impl<'a> Deref for Reader<'a> {
type Target = dyn Read + 'a;
fn deref(&self) -> &Self::Target {
match self {
Self::Value(v) => &**v,
Self::Ref(r) => &**r,
}
}
}
impl<'a> DerefMut for Reader<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Self::Value(v) => &mut **v,
Self::Ref(r) => &mut **r,
}
}
}
impl<'a> Deref for Writer<'a> {
type Target = dyn Write + 'a;
fn deref(&self) -> &Self::Target {
match self {
Self::Value(v) => &**v,
Self::Ref(r) => &**r,
}
}
}
impl<'a> DerefMut for Writer<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Self::Value(v) => &mut **v,
Self::Ref(r) => &mut **r,
}
}
}
pub struct Brainfuck<'a> {
pub code: String,
pub input: Option<Reader<'a>>,
pub output: Option<Writer<'a>>,
pub max_cell_value: u32,
pub memory_size: Option<usize>,
pub flush_output: bool,
pub prompt_stdin_once: bool,
pub instructions_limit: Option<usize>,
instructions_ctn: usize,
}
impl<'a> Default for Brainfuck<'a> {
fn default() -> Self {
Self::new(String::new())
}
}
impl<'a> Brainfuck<'a> {
#[must_use]
pub fn new<S: AsRef<str>>(code: S) -> Self {
Self {
code: code
.as_ref()
.to_string(),
input: None,
output: None,
max_cell_value: DEFAULT_MAX_CELL_VALUE,
memory_size: None,
flush_output: true,
prompt_stdin_once: false,
instructions_limit: None,
instructions_ctn: 0,
}
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let mut buf = String::new();
let mut file = File::open(path)
.map_err(Error::FileReadError)?;
file.read_to_string(&mut buf)
.map_err(Error::FileReadError)?;
Ok(Self::new(buf))
}
#[must_use]
pub fn with_code<S: AsRef<str>>(mut self, code: S) -> Self {
self.code = code
.as_ref()
.to_string();
self
}
#[must_use]
pub fn with_input<I>(mut self, input: I) -> Self
where
I: Read + 'static
{
self.input = Some(
Reader::Value(Box::new(input))
);
self
}
#[must_use]
pub fn with_output<O>(mut self, output: O) -> Self
where
O: Write + 'static
{
self.output = Some(
Writer::Value(Box::new(output))
);
self
}
#[must_use]
pub fn with_input_ref<I>(mut self, input: &'a mut I) -> Self
where
I: Read + 'static
{
self.input = Some(
Reader::Ref(input)
);
self
}
#[must_use]
pub fn with_output_ref<O>(mut self, output: &'a mut O) -> Self
where
O: Write + 'static
{
self.output = Some(
Writer::Ref(output)
);
self
}
#[must_use]
pub const fn with_max_value(mut self, cell_value: u32) -> Self {
self.max_cell_value = cell_value;
self
}
#[must_use]
pub const fn with_mem_size(mut self, mem_size: usize) -> Self {
self.memory_size = Some(mem_size);
self
}
#[must_use]
pub const fn with_flush(mut self, flush: bool) -> Self {
self.flush_output = flush;
self
}
#[must_use]
pub const fn prompt_stdin_once(mut self, once: bool) -> Self {
self.prompt_stdin_once = once;
self
}
#[must_use]
pub const fn with_instructions_limit(mut self, limit: usize) -> Self {
self.instructions_limit = Some(limit);
self
}
#[must_use]
pub const fn instructions_count(&self) -> usize {
self.instructions_ctn
}
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn into_input(self) -> Option<Reader<'a>> {
self.input
}
#[must_use]
#[allow(clippy::missing_const_for_fn)]
pub fn into_output(self) -> Option<Writer<'a>> {
self.output
}
#[must_use]
fn read_from_stdin_once() -> u32 {
let mut buffer = [0];
match std::io::stdin()
.read_exact(&mut buffer[0..1])
{
Ok(_) => u32::from(buffer[0]),
Err(_) => 0,
}
}
#[must_use]
fn read_from_stdin() -> u32 {
let mut buffer = String::new();
match std::io::stdin()
.read_line(&mut buffer)
{
Ok(_) => buffer
.chars()
.next()
.map_or(0, |c| c as u32),
Err(_) => 0,
}
}
#[allow(clippy::too_many_lines)]
pub fn execute(&mut self) -> Result<Vec<u32>> {
let (opening, closing) = (
self.code.chars()
.filter(|c| *c == '[')
.count(),
self.code.chars()
.filter(|c| *c == ']')
.count()
);
if opening != closing {
return Err(Error::MismatchedBrackets {
opening, closing
});
}
let mut cells =
self.memory_size
.map_or_else(
|| vec![0],
|mem_size| vec![0; mem_size],
);
self.instructions_ctn = 0;
let mut code_idx = 0usize;
let mut ptr = 0usize;
while code_idx < self.code
.chars()
.count()
{
match self.code
.chars()
.nth(code_idx)
{
Some('+') =>
if cells[ptr] >= self.max_cell_value {
cells[ptr] = 0;
} else {
cells[ptr] += 1;
},
Some('-') =>
if cells[ptr] == 0 {
cells[ptr] = self.max_cell_value;
} else {
cells[ptr] -= 1;
},
Some('<') =>
if ptr == 0 {
ptr = cells.len() - 1;
} else {
ptr -= 1;
},
Some('>') => {
ptr += 1;
if let Some(mem_size) = self.memory_size {
if ptr >= mem_size {
ptr = 0;
}
} else if ptr >= cells.len() {
cells.push(0);
}
},
Some('.') =>
if let Some(chr) =
std::char::from_u32(cells[ptr])
{
if let Some(ref mut writer) =
self.output
{
let mut buf = vec![0; chr.len_utf8()];
chr.encode_utf8(&mut buf);
writer.write_all(&buf)?;
if self.flush_output {
writer.flush()?;
}
} else {
print!("{chr}");
if self.flush_output {
std::io::stdout()
.flush()?;
}
}
},
#[allow(clippy::option_if_let_else)]
Some(',') =>
cells[ptr] = if let Some(ref mut reader) =
self.input
{
let mut buffer = [0];
match reader
.read_exact(&mut buffer[0..1])
{
Ok(_) => u32::from(buffer[0]),
Err(_) => 0,
}
} else if self.prompt_stdin_once {
Self::read_from_stdin_once()
} else {
Self::read_from_stdin()
},
Some('[') =>
if cells[ptr] == 0 {
let mut loop_ = 1;
while loop_ > 0 {
code_idx += 1;
match self.code
.chars()
.nth(code_idx)
{
Some('[') => loop_ += 1,
Some(']') => loop_ -= 1,
_ => (),
}
}
},
Some(']') => {
let mut loop_ = 1;
while loop_ > 0 {
code_idx -= 1;
match self.code
.chars()
.nth(code_idx)
{
Some('[') => loop_ -= 1,
Some(']') => loop_ += 1,
_ => (),
}
}
code_idx -= 1;
},
_ => (),
}
code_idx += 1;
self.instructions_ctn += 1;
if let Some(cap) = self.instructions_limit {
if self.instructions_ctn > cap {
return Err(Error::MaxInstructionsExceeded(cap));
}
}
}
Ok(cells)
}
}