1use std::io::Read;
2
3const INS: &[u8] = &[
4 b'>', b'<', b'+', b'-', b'.', b',', b'[', b']', b' ', b'\t', b'\n',
5];
6
7fn readchar() -> u8 {
8 let mut stdin = std::io::stdin();
9 let mut buf = [0; 1];
10 stdin.read(&mut buf).unwrap();
11 buf[0]
12}
13
14fn check_instructions(ins: &String) -> bool {
15 for c in ins.as_bytes() {
16 if !INS.contains(&c) {
17 return false;
18 }
19 }
20 true
21}
22pub fn process(ins: String) -> Vec<u8> {
23 let mut ins_ptr: usize = 0;
24 let mut mem_ptr: usize = 0;
25 let mut mem: Vec<u8> = vec![0; 30000];
26 let mut result: Vec<u8> = vec![];
27
28 assert_eq!(check_instructions(&ins), true);
29
30 while ins_ptr < ins.len() {
31 let c = ins.as_bytes()[ins_ptr];
32 match c {
33 b'+' => mem[mem_ptr] += 1,
34 b'-' => mem[mem_ptr] -= 1,
35 b'<' => mem_ptr -= 1,
36 b'>' => mem_ptr += 1,
37 b'.' => result.push(mem[mem_ptr]),
38 b',' => mem[mem_ptr] = readchar(),
39 b'[' => {
40 if mem[mem_ptr] == 0 {
41 let mut depth = 1;
42 ins_ptr += 1;
43 while depth > 0 {
44 match ins.as_bytes()[ins_ptr] {
45 b'[' => depth += 1,
46 b']' => depth -= 1,
47 _ => (),
48 }
49 ins_ptr += 1;
50 }
51 }
52 }
53 b']' => {
54 if mem[mem_ptr] != 0 {
55 let mut depth = 1;
56 ins_ptr -= 1;
57 while depth > 0 {
58 match ins.as_bytes()[ins_ptr] {
59 b'[' => depth -= 1,
60 b']' => depth += 1,
61 _ => (),
62 }
63 ins_ptr -= 1;
64 }
65 }
66 }
67 _ => (),
68 }
69 ins_ptr += 1;
70 }
71
72 result
73}