Last active
February 6, 2018 15:20
-
-
Save permil/b3b6e04f4194e6b28c45ca17149ecc86 to your computer and use it in GitHub Desktop.
bf interpreter written in Rust (https://github.com/rust-lang/rust)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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