Created
April 7, 2017 05:18
-
-
Save zekesonxx/9ba0b2ece344733b957db8a8f987916c to your computer and use it in GitHub Desktop.
Simple Brainfuck implementation in 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 program: Vec<char> = include_str!("../program.bf").chars().collect(); | |
let mut tape: Vec<u8> = vec![0]; //init with a zero because we only check cells on moves | |
let mut tape_pointer = 0usize; | |
let mut instruction_pointer = 0usize; | |
let mut loop_stack: Vec<usize> = vec![]; | |
//let mut counter = 0usize; | |
loop { | |
match program[instruction_pointer] { | |
'<' => if tape_pointer != 0 { tape_pointer -= 1; }, | |
'>' => { | |
tape_pointer += 1; | |
if tape.get(tape_pointer).is_none() { | |
tape.push(0); | |
} | |
}, | |
// We just eat integer overflows or underflows | |
//'+' => tape[tape_pointer] = tape[tape_pointer].wrapping_add(1), | |
//'-' => tape[tape_pointer] = tape[tape_pointer].wrapping_sub(1), | |
'+' => if tape[tape_pointer] < u8::max_value() { tape[tape_pointer] += 1; }, | |
'-' => if tape[tape_pointer] > 0 { tape[tape_pointer] -= 1; }, | |
'.' => { | |
print!("{}", (tape[tape_pointer] as u8) as char); | |
}, | |
',' => { | |
println!("tried to input data, scrub."); | |
break; | |
}, | |
'[' => { | |
loop_stack.push(instruction_pointer); | |
}, | |
']' => { | |
if loop_stack.is_empty() { | |
println!("tried to ] when not in a loop."); | |
break; | |
} else if tape[tape_pointer] != 0 { | |
instruction_pointer = *loop_stack.last().unwrap(); | |
} else { | |
loop_stack.pop(); | |
} | |
}, | |
_ => {} | |
} | |
//println!("instruction {} at pos {} tapelen {} tapeptr {}", program[instruction_pointer], instruction_pointer, tape.len(), tape_pointer); | |
//println!("{:?}", loop_stack); | |
instruction_pointer += 1; | |
if instruction_pointer >= program.len() { | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment