Skip to content
This repository was archived by the owner on Nov 25, 2019. It is now read-only.

Commit 4793c9d

Browse files
committed
More Rustiness
1 parent aa3d636 commit 4793c9d

File tree

2 files changed

+33
-18
lines changed

2 files changed

+33
-18
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
# Binaries
2-
bin/qqq
2+
bin/

rust/main.rs

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::io::{stdin, stdout, Read, Write};
1+
use std::io::{Read, Write};
22

33
fn parse_instructions(code: String) -> Vec<char> {
44
let mut instructions = Vec::new();
@@ -52,11 +52,11 @@ fn evaluate(instructions: Vec<char>) {
5252
tape[mem_ptr] -= 0x01;
5353
},
5454
'?' => {
55-
let input: Option<u8> = io::stdin().bytes()
56-
.next()
57-
.map(|b| b as u8)
58-
.expect("No input received");
59-
tape[mem_ptr] = input.unwrap();
55+
let input: Option<u8> = std::io::stdin().bytes()
56+
.next()
57+
.and_then(|r| r.ok())
58+
.map(|b| b as u8);
59+
tape[mem_ptr] = input.unwrap_or(0x00);
6060
},
6161
'!' => {
6262
// print as char if printable ASCII, otherwise print raw
@@ -65,32 +65,47 @@ fn evaluate(instructions: Vec<char>) {
6565
} else {
6666
print!("{}", tape[mem_ptr])
6767
}
68-
io::stdout().flush().unwrap();
68+
std::io::stdout().flush().unwrap();
6969
},
7070
'[' => {
7171
if tape[mem_ptr] == 0x00 {
72-
// advance to matching close bracket
73-
while instructions[ins_ptr] != ']' {
74-
ins_ptr += 1
72+
let mut balance = 1;
73+
// find the corresponding closing bracket, move the ip to it
74+
loop {
75+
ins_ptr += 1;
76+
if instructions[ins_ptr] == '[' {
77+
balance += 1
78+
} else if instructions[ins_ptr] == ']' {
79+
balance -= 1
80+
}
81+
if balance == 0 { break }
7582
}
7683
}
77-
continue
7884
},
7985
']' => {
8086
if tape[mem_ptr] == 0x00 {
81-
// move back to just before the matching open bracket
82-
while instructions[ins_ptr] != '[' {
83-
ins_ptr -= 1
87+
let mut balance = 1;
88+
// find the corresponding opening bracket, move the ip just before it
89+
loop {
90+
if instructions[ins_ptr] == '[' {
91+
balance += 1
92+
} else if instructions[ins_ptr] == ']' {
93+
balance -= 1
94+
}
95+
ins_ptr -= 1;
96+
if balance == 0 { break }
8497
}
85-
ins_ptr -= 1
8698
}
87-
continue
8899
}
100+
_ => unreachable!(),
89101
}
90102
ins_ptr += 1
91103
}
92104
}
93105

94106
fn main() {
95-
// TODO
107+
// Just a test, doesn't seem to be working just yet
108+
let code = "\"?'\"........'\",;;....\";.;.;.;..;...\"-'\";,\";;;.;.;.'\"-'\"--\";;;;.;....;!;,,,!.......!!'\",;.;.--'\";...!---!--!;;;;....'\",-....;'\"-,!;;!...!;!,,,,,,,,!-----!".to_string();
109+
let instr = parse_instructions(code);
110+
evaluate(instr);
96111
}

0 commit comments

Comments
 (0)