Created
February 27, 2021 09:25
-
-
Save XuaTheGrate/5e4412569a196a8470f77bb08a1d4957 to your computer and use it in GitHub Desktop.
brainfuck interpreter 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
use std::env; | |
use std::fs; | |
use std::io::{self, Write, Read}; | |
use std::process::exit; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let contents: String = match fs::read_to_string(&args[1]) { | |
Ok(x) => x, | |
Err(e) => { | |
eprintln!("{:?}", e); | |
exit(1); | |
} | |
}; | |
let contents: &[u8] = contents.as_bytes(); | |
let mut tape: Vec<u8> = vec![0u8; 30000]; | |
let mut ptr: usize = 0; | |
let mut unmatched: i32 = 0; | |
let mut i: usize = 0; | |
loop { | |
let ch: char = match contents.get(i) { | |
Some(t) => *t as char, | |
None => exit(0) | |
}; | |
match ch { | |
'>' => { | |
ptr += 1; | |
} | |
'<' => { | |
ptr -= 1; | |
} | |
'+' => { | |
tape[ptr] = tape[ptr].wrapping_add(1); | |
} | |
'-' => { | |
tape[ptr] = tape[ptr].wrapping_sub(1); | |
} | |
'.' => { | |
io::stdout().write(&[tape[ptr]]).unwrap(); | |
} | |
',' => { | |
let mut buf: [u8; 1] = [0u8; 1]; | |
io::stdin().read(&mut buf) | |
.expect("h"); | |
tape[ptr] = buf[0]; | |
} | |
'[' => { | |
if tape[ptr] == 0u8 { | |
unmatched += 1; | |
while contents[i] as char != ']' || unmatched != 0 { | |
i += 1; | |
if contents[i] as char == '[' { | |
unmatched += 1; | |
} else if contents[i] as char == ']' { | |
unmatched -= 1; | |
} | |
} | |
} | |
} | |
']' => { | |
if tape[ptr] != 0u8 { | |
unmatched += 1; | |
while contents[i] as char != '[' || unmatched != 0 { | |
i -= 1; | |
if contents[i] as char == ']' { | |
unmatched += 1; | |
} else if contents[i] as char == '[' { | |
unmatched -= 1; | |
} | |
} | |
} | |
} | |
_ => {} | |
} | |
i += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment