ft: initial impl
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/target
|
||||
7
Cargo.lock
generated
Normal file
7
Cargo.lock
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "brainfuck-rs"
|
||||
version = "0.1.0"
|
||||
6
Cargo.toml
Normal file
6
Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "brainfuck-rs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
69
src/main.rs
Normal file
69
src/main.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use std::io::{self, Read};
|
||||
|
||||
fn interpret(code: &str) {
|
||||
let mut memory = [0 as u8; 10_000];
|
||||
let mut head = 0 as usize;
|
||||
let mut pc = 0 as usize;
|
||||
let mut loop_stack = Vec::new();
|
||||
|
||||
let code_bytes = code.as_bytes();
|
||||
while pc < code.len() {
|
||||
match code_bytes[pc] as char {
|
||||
'>' => head += 1,
|
||||
'<' => head -= 1,
|
||||
'+' => memory[head] += 1,
|
||||
'-' => memory[head] -= 1,
|
||||
'.' => println!("{}", memory[head]),
|
||||
',' => {
|
||||
let mut input_buf = [0u8; 1];
|
||||
if io::stdin().read_exact(&mut input_buf).is_ok() {
|
||||
memory[head] = input_buf[0];
|
||||
}
|
||||
}
|
||||
'[' => {
|
||||
// loop start
|
||||
if memory[pc] == 0 {
|
||||
let mut count_brackets = 1;
|
||||
|
||||
// find nested brackets
|
||||
while count_brackets > 0 {
|
||||
pc += 1;
|
||||
if pc >= code_bytes.len() {
|
||||
panic!("Missing closing loop!");
|
||||
}
|
||||
match code_bytes[pc] as char {
|
||||
// closing current loop
|
||||
']' => count_brackets -= 1,
|
||||
// nested bracket
|
||||
'[' => count_brackets += 1,
|
||||
// ignore rest
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// save pc to jump back to
|
||||
loop_stack.push(pc);
|
||||
}
|
||||
}
|
||||
']' => {
|
||||
// loop terminator
|
||||
if memory[pc] != 0 {
|
||||
if let Some(start_pc) = loop_stack.last() {
|
||||
pc = *start_pc;
|
||||
}
|
||||
} else {
|
||||
// loop done, continue normally
|
||||
loop_stack.pop();
|
||||
}
|
||||
}
|
||||
_ => panic!("Invalid instruction"),
|
||||
}
|
||||
pc += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let code = "+++++++++[>++++++++<-]>.";
|
||||
let hello_world = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
|
||||
interpret(hello_world);
|
||||
}
|
||||
Reference in New Issue
Block a user