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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! The Brainfuck machine state.
//!
//! Useful for creating initial states for testing, and also the interface used by the
//! interpreters to access the state.

use std::default::Default;
use std::io::{Read, Write};
use std::num::Wrapping;

use common::{BfResult, Error};
use traits::IntoUsize;

/// (`== 30_000`) The default number of 8-bit memory cells, as used by
/// [`State::new`](struct.State.html#method.new).
pub const DEFAULT_CAPACITY: usize = 30_000;

/// The Brainfuck machine state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct State {
    memory: Box<[Wrapping<u8>]>,
    pointer: usize,
}

impl State {
    /// Creates a new BF machine state with memory capacity
    /// [`DEFAULT_CAPACITY`](constant.DEFAULT_CAPACITY.html) (30_000).
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_CAPACITY)
    }

    /// Creates a new BF machine state with the given memory capacity.
    pub fn with_capacity(memory_size: usize) -> Self {
        State {
            memory: vec![Wrapping(0); memory_size].into_boxed_slice(),
            pointer: 0,
        }
    }

    /// Decrements/decreases the pointer.
    ///
    /// # Errors
    ///
    /// Return `Err` if pointer would go below 0.
    #[inline]
    pub fn left<C: IntoUsize>(&mut self, count: C) -> BfResult<()> {
        self.pointer = self.neg_offset(count)?;
        Ok(())
    }

    /// Increments/increases the pointer.
    ///
    /// # Errors
    ///
    /// Return `Err` if pointer would go past the end of the memory.
    #[inline]
    pub fn right<C: IntoUsize>(&mut self, count: C) -> BfResult<()> {
        self.pointer = self.pos_offset(count)?;
        Ok(())
    }

    #[inline]
    fn pos_offset<C: IntoUsize>(&self, offset: C) -> BfResult<usize> {
        let offset = offset.into_usize();
        if self.pointer + offset < self.memory.len() {
            Ok(self.pointer + offset)
        } else {
            Err(Error::PointerOverflow)
        }
    }

    #[inline]
    fn neg_offset<C: IntoUsize>(&self, offset: C) -> BfResult<usize> {
        let offset = offset.into_usize();
        if self.pointer >= offset {
            Ok(self.pointer - offset)
        } else {
            Err(Error::PointerUnderflow)
        }
    }

    /// Increments/increases the byte at the pointer.
    ///
    /// Wraps around modulo 256.
    #[inline]
    pub fn up(&mut self, count: u8) {
        self.memory[self.pointer] += Wrapping(count);
    }

    /// Decrements/decreases the byte at the pointer.
    ///
    /// Wraps around modulo 256.
    #[inline]
    pub fn down(&mut self, count: u8) {
        self.memory[self.pointer] -= Wrapping(count);
    }

    /// Gets the value of the byte at the pointer.
    #[inline]
    pub fn load(&self) -> u8 {
        self.memory[self.pointer].0
    }

    /// Sets the value of the byte at the pointer.
    #[inline]
    pub fn store(&mut self, value: u8) {
        self.memory[self.pointer] = Wrapping(value);
    }

    /// Adds the given value at the given positive offset from the pointer.
    #[inline]
    pub fn up_pos_offset<C: IntoUsize>(&mut self, offset: C, value: u8) -> BfResult<()> {
        let address = self.pos_offset(offset)?;
        self.memory[address] += Wrapping(value);
        Ok(())
    }

    /// Adds the given value at the given negative offset from the pointer.
    #[inline]
    pub fn up_neg_offset<C: IntoUsize>(&mut self, offset: C, value: u8) -> BfResult<()> {
        let address = self.neg_offset(offset)?;
        self.memory[address] += Wrapping(value);
        Ok(())
    }

    /// Reads from a `Read` into the byte at the pointer.
    #[inline]
    pub fn read<R: Read>(&mut self, input: &mut R) {
        let mut byte = [0];
        let _ = input.read_exact(&mut byte);
        self.store(byte[0]);
    }

    /// Writes to a `Write` from the byte at the pointer.
    #[inline]
    pub fn write<W: Write>(&self, output: &mut W) {
        let _ = output.write_all(&[self.load()]);
    }

    /// The memory capacity.
    pub fn capacity(&self) -> usize {
        self.memory.len()
    }

    /// Gets a mutable, raw pointer to the start of memory.
    ///
    /// This is used by the JIT RTS to pass the memory pointer to the generated code.
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        // Assumes that Wrapping<u8> == u8:
        self.memory.as_mut_ptr() as *mut u8
    }
}

impl Default for State {
    fn default() -> Self {
        State::new()
    }
}

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

    #[test]
    fn right_moves_right() {
        let mut actual = make(&[0, 0, 0], 0);
        let expected = make(&[0, 0, 0], 1);

        actual.right(1usize).unwrap();

        assert_eq!(actual, expected);
    }

    #[test]
    fn right_then_left_restores() {
        let mut actual = make(&[0, 0, 0], 0);
        let expected = make(&[0, 0, 0], 0);

        actual.right(1usize).unwrap();
        actual.left(1usize).unwrap();

        assert_eq!(actual, expected);
    }

    #[test]
    fn up_goes_to_1() {
        let mut actual = make(&[0, 0, 0], 0);
        actual.up(1);
        assert_eq!(actual, make(&[1, 0, 0], 0))
    }

    #[test]
    fn down_goes_to_255() {
        let mut actual = make(&[0, 0, 0], 0);
        actual.down(1);
        assert_eq!(actual, make(&[255, 0, 0], 0))
    }

    #[test]
    fn load_reads() {
        assert_eq!(make(&[0, 0, 0], 0).load(), 0);
        assert_eq!(make(&[1, 0, 0], 0).load(), 1);
        assert_eq!(make(&[1, 2, 0], 1).load(), 2);
    }

    #[test]
    fn store_writes() {
        let mut actual = make(&[0, 0, 0], 0);
        actual.store(5);
        assert_eq!(actual, make(&[5, 0, 0], 0));
        actual.right(1usize).unwrap();
        actual.store(8);
        assert_eq!(actual, make(&[5, 8, 0], 1));
    }

    #[test]
    fn longer_sequence_of_actions() {
        let mut actual = make(&[0, 0, 0], 0);
        actual.up(1);
        assert_eq!(actual, make(&[1, 0, 0], 0));
        actual.up(1);
        assert_eq!(actual, make(&[2, 0, 0], 0));
        actual.right(1usize).unwrap();
        assert_eq!(actual, make(&[2, 0, 0], 1));
        actual.down(1);
        assert_eq!(actual, make(&[2, 255, 0], 1));
        actual.down(1);
        assert_eq!(actual, make(&[2, 254, 0], 1));
        actual.right(1usize).unwrap();
        assert_eq!(actual, make(&[2, 254, 0], 2));
        actual.store(77);
        assert_eq!(actual, make(&[2, 254, 77], 2));
    }

    #[test]
    fn right_to_right_edge_is_okay() {
        let mut actual = make(&[0, 0, 0], 0);
        actual.right(1usize).unwrap();
        actual.right(1usize).unwrap();
        assert_eq!(actual, make(&[0, 0, 0], 2));
    }

    #[test]
    #[should_panic]
    fn right_past_edge_is_error() {
        let mut actual = make(&[0, 0, 0], 0);
        actual.right(1usize).unwrap();
        actual.right(1usize).unwrap();
        actual.right(1usize).unwrap();
    }

    #[test]
    #[should_panic]
    fn move_left_is_error() {
        let mut machine = make(&[0, 0, 0], 0);
        machine.left(1usize).unwrap();
    }

    fn make(memory: &[u8], pointer: usize) -> State {
        State {
            memory: memory.iter().map(|&b| Wrapping(b)).collect::<Vec<_>>().into_boxed_slice(),
            pointer: pointer,
        }
    }
}