tapir_bf/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#![warn(
    clippy::all,
    clippy::restriction,
    clippy::pedantic,
    clippy::nursery,
    clippy::cargo
)]

use std::io::{BufRead, Write};
use std::{io, process::exit};

fn match_right(index: usize, program: &[u8], lma: usize, lmv: usize) -> (usize, usize, usize) {
    if lma == index {
        return (lmv, lma, lmv);
    }

    let lma = index;
    let mut index = index;

    let mut depth = 0;
    while index < program.len() {
        if program[index] as char == '[' {
            depth += 1;
        } else if program[index] as char == ']' {
            depth -= 1;
        }
        if depth == 0 {
            break;
        }
        index += 1;
    }
    if depth != 0 {
        return (0, lma, lmv);
    }
    (index, lma, index)
}

fn match_left(
    index: usize,
    program: &[u8],
    lma: usize,
    lmv: usize,
) -> (Option<usize>, usize, usize) {
    if lma == index {
        return (Some(lmv), lma, lmv);
    }

    let lma = index;
    let origin = index;
    let mut index = index;
    let mut depth = 0;

    while index <= origin {
        if program[index] as char == '[' {
            depth += 1;
        } else if program[index] as char == ']' {
            depth -= 1;
        }
        if depth == 0 {
            break;
        }
        index -= 1;
    }
    if depth != 0 {
        return (None, lma, lmv);
    }

    (Some(index), lma, index)
}

fn parse_byte(s: &str) -> Result<u8, String> {
    let mut cs = s.chars();
    match cs.next() {
        None => Err("Expected input got got none".to_owned()),
        Some('\\') => match cs.collect::<String>().parse::<u8>() {
            Ok(val) => Ok(val),
            Err(e) => Err(e.to_string()),
        },
        Some(c) => Ok(c as u8),
    }
}

pub fn interpret(mem: &mut Vec<u8>, program: &[u8]) -> i32 {
    let mut mem_ptr: usize = 0;
    let mut ins_ptr: usize = 0;

    let mut last_match_left_arg = 0;
    let mut last_match_left_val = 0;
    let mut last_match_right_arg = usize::MAX;
    let mut last_match_right_val = 0;

    let mut input = io::stdin().lock().lines();

    if mem.is_empty() {
        mem.push(0);
    }

    while ins_ptr < program.len() {
        match program[ins_ptr] as char {
            '>' => {
                mem_ptr += 1;
                let mem_len = mem.len();
                if mem_ptr == mem_len {
                    mem.push(0);
                    continue;
                }
                assert!(mem_ptr < mem.len()); // if we somehow increment by > 1
            }
            '<' => {
                let new_mem_ptr = mem_ptr - 1;
                if new_mem_ptr > mem_ptr {
                    return 4;
                }
                mem_ptr = new_mem_ptr;
            }
            '+' => mem[mem_ptr] += 1,
            '-' => mem[mem_ptr] -= 1,
            '.' => {
                print!("{}", mem[mem_ptr] as char);
            }
            ',' => {
                println!();
                io::stdout().flush().expect("Failed to flush stdout (???)");
                mem[mem_ptr] = parse_byte(
                    &mut input
                        .next()
                        .expect("Failed to read stdin (???)")
                        .unwrap_or_else(|e| {
                            eprintln!("{e}");
                            exit(1)
                        }),
                )
                .unwrap_or_else(|e| {
                    eprintln!("{e}");
                    exit(1);
                });
            }
            '[' => {
                if mem[mem_ptr] == 0 {
                    match match_right(ins_ptr, program, last_match_right_arg, last_match_right_val)
                    {
                        (0, _, _) => return 4,
                        (n, lma, lmv) => {
                            ins_ptr = n;
                            last_match_right_arg = lma;
                            last_match_right_val = lmv;
                        }
                    }
                }
            }
            ']' => {
                if mem[mem_ptr] != 0 {
                    match match_left(ins_ptr, program, last_match_left_arg, last_match_left_val) {
                        (None, _, _) => return 4,
                        (Some(n), lma, lmv) => {
                            ins_ptr = n;
                            last_match_left_arg = lma;
                            last_match_left_val = lmv;
                        }
                    }
                }
            }
            _ => {}
        }
        ins_ptr += 1;
    }

    io::stdout().flush().expect("Failed to flush stdout (???)");

    0
}