Last active
August 8, 2024 01:34
-
-
Save Nakanoin19/3feca9d297c756783a40c23fb2b084f4 to your computer and use it in GitHub Desktop.
Simple Brainfuck Interpreter
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 text_io::read; | |
use std::collections::VecDeque; | |
fn main() { | |
loop { | |
print!("BF) "); | |
let code: String = read!(); | |
if code.trim() == "!".to_string() { | |
println!("Exit"); | |
break; | |
} | |
let chars = &code.trim().chars().collect::<Vec<char>>(); | |
let mut m = [0u8; 256]; | |
let mut i = 0usize; | |
let mut mp = 0usize; | |
let mut lstart = VecDeque::<usize>::new(); | |
let mut buffer = Vec::<u8>::new(); | |
while i < chars.len() { | |
match chars[i] { | |
'+' => { | |
m[mp] = ((m[mp] as u16 + 1) % 256) as u8; | |
i += 1; | |
}, | |
'-' => { | |
m[mp] = ((256 + m[mp] as u16 - 1) % 256) as u8; | |
i += 1; | |
}, | |
'>' => { | |
mp = (mp + 1) % 256; | |
i += 1; | |
}, | |
'<' => { | |
mp = (256 + mp - 1) % 256; | |
i += 1; | |
}, | |
'[' => { | |
lstart.push_back(i + 1); | |
i += 1; | |
}, | |
']' => { | |
if m[mp] == 0 { | |
lstart.pop_back(); | |
i += 1; | |
} else { | |
i = (&lstart)[lstart.len() - 1]; | |
} | |
}, | |
',' => { | |
print!("char: "); | |
let s: String = read!(); | |
let c = s.chars().next().unwrap_or('\0'); | |
m[mp] = c as u8; | |
i += 1; | |
}, | |
'.' => { | |
buffer.push(m[mp]); | |
i += 1; | |
}, | |
_ => { | |
i += 1; | |
}, | |
} | |
} | |
println!("{}", String::from_utf8(buffer).unwrap()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment