Created
August 31, 2015 20:10
-
-
Save notriddle/c55531d71d2312dc305a to your computer and use it in GitHub Desktop.
Super-naive brainfuck interpreter in safe Rust
This file contains 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
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