Skip to content

Instantly share code, notes, and snippets.

@XuaTheGrate
Created February 27, 2021 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XuaTheGrate/5e4412569a196a8470f77bb08a1d4957 to your computer and use it in GitHub Desktop.
Save XuaTheGrate/5e4412569a196a8470f77bb08a1d4957 to your computer and use it in GitHub Desktop.
brainfuck interpreter in rust
use std::env;
use std::fs;
use std::io::{self, Write, Read};
use std::process::exit;
fn main() {
let args: Vec<String> = env::args().collect();
let contents: String = match fs::read_to_string(&args[1]) {
Ok(x) => x,
Err(e) => {
eprintln!("{:?}", e);
exit(1);
}
};
let contents: &[u8] = contents.as_bytes();
let mut tape: Vec<u8> = vec![0u8; 30000];
let mut ptr: usize = 0;
let mut unmatched: i32 = 0;
let mut i: usize = 0;
loop {
let ch: char = match contents.get(i) {
Some(t) => *t as char,
None => exit(0)
};
match ch {
'>' => {
ptr += 1;
}
'<' => {
ptr -= 1;
}
'+' => {
tape[ptr] = tape[ptr].wrapping_add(1);
}
'-' => {
tape[ptr] = tape[ptr].wrapping_sub(1);
}
'.' => {
io::stdout().write(&[tape[ptr]]).unwrap();
}
',' => {
let mut buf: [u8; 1] = [0u8; 1];
io::stdin().read(&mut buf)
.expect("h");
tape[ptr] = buf[0];
}
'[' => {
if tape[ptr] == 0u8 {
unmatched += 1;
while contents[i] as char != ']' || unmatched != 0 {
i += 1;
if contents[i] as char == '[' {
unmatched += 1;
} else if contents[i] as char == ']' {
unmatched -= 1;
}
}
}
}
']' => {
if tape[ptr] != 0u8 {
unmatched += 1;
while contents[i] as char != '[' || unmatched != 0 {
i -= 1;
if contents[i] as char == ']' {
unmatched += 1;
} else if contents[i] as char == '[' {
unmatched -= 1;
}
}
}
}
_ => {}
}
i += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment