Skip to content

Instantly share code, notes, and snippets.

@permil
Last active February 6, 2018 15:20
Show Gist options
  • Save permil/b3b6e04f4194e6b28c45ca17149ecc86 to your computer and use it in GitHub Desktop.
Save permil/b3b6e04f4194e6b28c45ca17149ecc86 to your computer and use it in GitHub Desktop.
bf interpreter written in Rust (https://github.com/rust-lang/rust)
fn main() {
let prog = ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++
++>-]<.>+++++++++++[<+++++>-]<.>++++++++[<+++>-]<.+++.------.--------.[-]>
++++++++[<++++>-]<+.[-]++++++++++.";
let mut inst = 0;
let mut tape = [0; 30000];
let mut ptr = 0;
while inst < prog.len() {
let command = prog.as_bytes()[inst];
match command as char {
'>' => ptr += 1,
'<' => ptr -= 1,
'+' => tape[ptr] += 1,
'-' => tape[ptr] -= 1,
'.' => print!("{}", tape[ptr] as u8 as char),
',' => {}, // TODO:
'[' => {
if tape[ptr] == 0 {
let mut cnt = 0;
inst += 1;
loop {
match prog.as_bytes()[inst] as char {
'[' => cnt += 1,
']' => match cnt {
0 => break,
_ => cnt -= 1,
},
_ => {},
}
inst += 1;
}
}
},
']' => {
let mut cnt = 0;
inst -= 1;
loop {
match prog.as_bytes()[inst] as char {
'[' => match cnt {
0 => break,
_ => cnt -= 1,
},
']' => cnt += 1,
_ => {},
}
inst -= 1;
}
continue;
},
_ => {},
}
inst = inst + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment