Skip to content

Instantly share code, notes, and snippets.

@Trivaxy
Created June 30, 2020 22:07
Show Gist options
  • Save Trivaxy/a7ff813597b80b6e0f8ca7bedf24b840 to your computer and use it in GitHub Desktop.
Save Trivaxy/a7ff813597b80b6e0f8ca7bedf24b840 to your computer and use it in GitHub Desktop.
brain-screw
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::{self, BufRead};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("no file specified");
return;
}
let filepath = &args[1];
let code = match fs::read_to_string(filepath) {
Ok(c) => c,
Err(_) => {
println!("couldn't read file");
return;
}
};
run(&code);
}
fn run(code: &str) {
let mut cells: [u8; 30000] = [0; 30000];
let mut pointer = 0;
let code = code.as_bytes();
let mut bracket_pairs = HashMap::new();
for i in 0..code.len() {
let character = code[i] as char;
if character == '[' {
let mut skips = 0;
for j in (i + 1)..code.len() {
let inner_char = code[j] as char;
if inner_char == '[' {
skips += 1;
}
else if inner_char == ']' {
if skips == 0 {
bracket_pairs.insert(i, j);
bracket_pairs.insert(j, i);
break;
}
skips -= 1;
}
}
}
}
let mut i = 0;
while i < code.len() {
match code[i] as char {
'>' => {
if pointer + 1 >= cells.len() {
pointer = 0;
} else {
pointer += 1;
}
},
'<' => {
if (pointer as i32) - 1 < 0 {
pointer = cells.len() - 1;
} else {
pointer -= 1;
}
},
'+' => cells[pointer] += 1,
'-' => cells[pointer] -= 1,
'.' => print!("{}", cells[pointer] as char),
',' => {
let mut buf = String::new();
io::stdin().lock().read_line(&mut buf);
cells[pointer] = buf.as_bytes()[0];
},
'[' => {
if cells[pointer] == 0 {
i = bracket_pairs[&i] - 1;
}
},
']' => {
if cells[pointer] != 0 {
i = bracket_pairs[&i] - 1;
}
},
'*' => cells[pointer] *= 2,
'~' => cells[pointer] = ((SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.subsec_nanos() as f32)
.sin()
.abs() * 255f32) as u8,
_ => {}
}
i += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment