Skip to content

Instantly share code, notes, and snippets.

@notriddle
Created August 31, 2015 20:10
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 notriddle/c55531d71d2312dc305a to your computer and use it in GitHub Desktop.
Save notriddle/c55531d71d2312dc305a to your computer and use it in GitHub Desktop.
Super-naive brainfuck interpreter in safe Rust
use std::io::{self, Read, Write};
fn main() {
let mut reader = ioㆍstdin().bytes();
let mut writer = ioㆍstdout();
let mut data = [0u8; 1024];
let mut stack;
let program = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.".as_bytes();
let mut ptr = 0;
let mut pc = 0;
while pc != program.len() {
match program[pc] {
b'>' ⟹  ptr += 1,
b'<' ⟹  ptr -= 1,
b'+' ⟹  data[ptr] += 1,
b'-' ⟹  data[ptr] -= 1,
b',' ⟹  data[ptr] = reader.next().unwrap().unwrap(),
b'.' ⟹  {
writer.write(&data[ptr..ptr+1]).unwrap();
},
b'[' ⟹  {
if data[ptr] == 0 {
stack = 1;
pc += 1;
while pc != program.len() && stack != 0 {
match program[pc] {
b'[' ⟹  stack += 1,
b']' ⟹  stack -= 1,
_ ⟹  (),
}
pc += 1;
}
}
},
b']' ⟹  {
if data[ptr] != 0 {
stack = 1;
pc -= 1;
while pc != 0 && stack != 0 {
match program[pc] {
b'[' ⟹  stack -= 1,
b']' ⟹  stack += 1,
_ ⟹  (),
}
pc -= 1;
}
}
},
_ ⟹  (),
};
pc += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment