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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
#[derive(Debug)]
pub enum Error {
    MismatchedBrackets,
    IOError(std::io::Error),
    EOF,
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::IOError(err)
    }
}

type CellContent = u8;

struct Tape {
    contents: [CellContent; 30000],
}

impl Tape {
    pub fn get_cell(&self, index: usize) -> CellContent {
        self.contents[index]
    }
    pub fn set_cell(&mut self, index: usize, value: CellContent) {
        self.contents[index] = value;
    }
    pub fn increment(&mut self, index: usize) {
        if self.contents[index] == 255 {
            self.contents[index] = 0;
        } else {
            self.contents[index] += 1;
        }
    }
    pub fn decrement(&mut self, index: usize) {
        if self.contents[index] == 0 {
            self.contents[index] = 255;
        } else {
            self.contents[index] -= 1;
        }
    }
    pub fn new() -> Tape {
        Tape {
            contents: [0; 30000],
        }
    }
}

struct State<'s, R: std::io::Read + 's, W: std::io::Write + 's> {
    tape: Tape,
    source: Vec<char>,
    instruction_index: usize,
    data_index: usize,
    input: &'s mut R,
    output: &'s mut W,
    small_buffer: [u8; 1],
}

impl<'s, R: std::io::Read, W: std::io::Write> State<'s, R, W> {
    fn run_single(&mut self) -> Result<bool, Error> {
        match self.source.get(self.instruction_index) {
            Some(chr) => {
                let result: Result<bool, Error> = match *chr {
                    '.' => {
                        self.output
                            .write_all(&[self.tape.get_cell(self.data_index)])?;
                        Ok(true)
                    }
                    ',' => {
                        let count = self.input.read(&mut self.small_buffer)?;
                        if count < 1 {
                            return Err(Error::EOF);
                        }
                        self.tape.set_cell(self.data_index, self.small_buffer[0]);
                        Ok(true)
                    }
                    '+' => {
                        self.tape.increment(self.data_index);
                        Ok(true)
                    }
                    '-' => {
                        self.tape.decrement(self.data_index);
                        Ok(true)
                    }
                    '<' => {
                        self.data_index -= 1;
                        Ok(true)
                    }
                    '>' => {
                        self.data_index += 1;
                        Ok(true)
                    }
                    '[' => {
                        if self.tape.get_cell(self.data_index) > 0 {
                            Ok(true)
                        } else {
                            let mut nested = 1;
                            loop {
                                self.instruction_index += 1;
                                let chr = match self.source.get(self.instruction_index) {
                                    Some(x) => Ok(x),
                                    None => Err(Error::EOF),
                                }?;
                                if *chr == ']' {
                                    nested -= 1;
                                    if nested < 1 {
                                        break;
                                    }
                                }
                                if *chr == '[' {
                                    nested += 1;
                                }
                            }
                            Ok(true)
                        }
                    }
                    ']' => {
                        if self.tape.get_cell(self.data_index) == 0 {
                            Ok(true)
                        } else {
                            let mut nested = 1;
                            loop {
                                if self.instruction_index < 1 {
                                    return Err(Error::MismatchedBrackets);
                                }
                                self.instruction_index -= 1;
                                let chr = self.source[self.instruction_index];
                                if chr == '[' {
                                    nested -= 1;
                                    if nested < 1 {
                                        break;
                                    }
                                }
                                if chr == ']' {
                                    nested += 1;
                                }
                            }
                            Ok(true)
                        }
                    }
                    _ => Ok(true),
                };
                if result? {
                    self.instruction_index += 1;
                }
                Ok(true)
            }
            None => Ok(false),
        }
    }

    pub fn execute(&mut self) -> Result<(), Error> {
        loop {
            if !self.run_single()? {
                break;
            }
        }
        self.output.flush()?;
        Ok(())
    }

    pub fn new<'a>(src: &str, input: &'a mut R, output: &'a mut W) -> State<'a, R, W> {
        State {
            tape: Tape::new(),
            source: src.chars().collect(),
            instruction_index: 0,
            data_index: 0,
            input,
            output,
            small_buffer: [0; 1],
        }
    }
}

/// Execute a Brainfuck program
///
/// # Example
///
/// ```
/// let input = "+++++[->+++++ +++++<]-- .";
/// heliometer::execute(&input, &mut std::io::stdin(), &mut std::io::stdout()).unwrap();
/// ```
pub fn execute<R: std::io::Read, W: std::io::Write>(
    source: &str,
    input: &mut R,
    output: &mut W,
) -> Result<(), Error> {
    let mut state = State::new(source, input, output);
    state.execute()
}