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
//! # bf-lib
//!
//! `bf-lib` is small library to run brainfuck programs non-interactively

use std::{collections::HashMap, num::Wrapping};
///Do a first pass on the program, adds every ['s position to a LIFO queue, pop from the vector and
///add to a hashmap every time a ] is found.
fn maploops(bytes: &[u8]) -> Result<HashMap<usize, usize>, String> {
    let mut map = HashMap::new();
    let mut open: Vec<usize> = Vec::new();
    let mut i: usize = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'[' => open.push(i),
            b']' => {
                let last = if let Some(last) = open.pop() {
                    last
                } else {
                    return Err(format!(
                        "Error. I didn't quite get that.\nUnmatched bracket at {}",
                        i
                    ));
                };
                map.insert(last, i);
                map.insert(i, last);
            }
            _ => (),
        }
        i += 1
    }
    if open.len() != 0 {
        return Err(format!(
            "Error. I didn't quite get that.\nUnmatched bracket at {}",
            open.pop().unwrap()
        ));
    }
    Ok(map)
}

fn exec(bytes: &[u8], map: HashMap<usize, usize>, input: Option<String>) -> Result<String, String> {
    let mut mem = [Wrapping(0u8); 30000];
    let (mut i, mut p, mut b) = (0usize, 0usize, 0usize);
    let mut output = String::new();
    let input = if let Some(a) = &input { a } else { "" };
    while p < bytes.len() {
        match bytes[p] {
            b'>' => {
                if i != 30000 {
                    i += 1
                } else {
                    return Err(String::from(
                        "Error, I didn't quite get that.\nOut of memory bounds",
                    ));
                }
            }
            b'<' => {
                if i != 0 {
                    i -= 1
                } else {
                    return Err(String::from(
                        "Error, I didn't quite get that.\nOut of memory bounds",
                    ));
                }
            }
            b'+' => mem[i] += Wrapping(1),
            b'-' => mem[i] -= Wrapping(1),
            b'.' => {
                output.push(mem[i].0 as char);
            }
            b',' => {
                mem[i] = {
                    b += 1;
                    if let Some(char) = input.as_bytes().get(b - 1) {
                        Wrapping(*char)
                    } else {
                        return Err(String::from(
                            "Error, I didn't quite get that.\nInput too short.",
                        ));
                    }
                }
            }
            b'[' => {
                if mem[i].0 == 0 {
                    p = map[&p]
                }
            }
            b']' => {
                if mem[i].0 != 0 {
                    p = map[&p]
                }
            }
            _ => (),
        }
        p += 1
    }
    Ok(output)
}

/// Runs a brainfuck program, returning the program's output or the reason it failed to execute.
/// # Examples
/// ```
/// let program = "++++++++++[>++++++++++>+++++++++++<<-]>++.>+..";
/// let output = bf_lib::run(program, None).unwrap();
///
/// assert_eq!(String::from("foo"), output);
/// ```
pub fn run(program: &str, input: Option<String>) -> Result<String, String> {
    let bytes = program.as_bytes();
    let loops = maploops(bytes)?;
    let output = exec(bytes, loops, input)?;
    Ok(output)
}

/// Checks if the program will try to read user input.
///
/// # Examples
///
/// ```
/// let reads = ",[>+>+<<-]>.>.";
/// let does_not_read = "foo. bar.";
///
/// assert_eq!(true, bf_lib::wants_input(reads));
/// assert_eq!(false, bf_lib::wants_input(does_not_read));
/// ```
pub fn wants_input(program: &str) -> bool {
    program.contains(",")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn in_out() {
        assert_eq!(
            run(",.", Some(String::from("a"))).unwrap(),
            String::from("a")
        );
    }

    #[test]
    fn loop_math() {
        assert_eq!(
            run("+++++[>++++++++++<-]>-.", None).unwrap(),
            String::from("1")
        );
    }

    #[test]
    #[should_panic]
    fn out_of_memory() {
        run("<", None).unwrap();
    }

    #[test]
    #[should_panic]
    fn out_of_input() {
        run(",", None).unwrap();
    }
    #[test]
    fn input_check() {
        assert_eq!(wants_input("foo , bar"), true);
        assert_eq!(wants_input("foo . bar"), false);
    }
}