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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! # A standalone Advent of Code 2019 Intcode VM implementation
//!
//! That's it. IDK what else to tell ya.
//!
//! # Examples
//!
//! ```
//! use aoc19intcode::IntcodeVM;
//! assert_eq!(
//!     IntcodeVM::from_prog(&[2, 4, 4, 5, 99, 0])
//!         .run_prog()
//!         .unwrap()[5],
//!     9801
//! );
//! ```

use std::{
    cmp::{Ordering, PartialEq},
    fmt,
    ops::{Add, Mul},
    ops::{Index, IndexMut},
    sync::mpsc::{Receiver, Sender},
};

#[derive(Clone, Copy, PartialEq, Debug)]
enum Mode {
    Position,
    Immediate,
    Relative,
}

type Cell = i128;
type Tape = Vec<Cell>;

/// A VM that runs Intcode programs.
///
/// # Examples
///
/// ```
/// use aoc19intcode::IntcodeVM;
/// assert_eq!(
///     IntcodeVM::from_prog(&[2, 4, 4, 5, 99, 0])
///         .run_prog()
///         .expect("Tried to run a halted program.")[5],
///     9801
/// );
/// ```
/// ```
/// use std::{thread, sync::mpsc};
/// use aoc19intcode::IntcodeVM;
/// let input = [2, 4, 4, 5, 99, 0];
/// let (mtx, prx) = mpsc::channel();
/// let (ptx, mrx) = mpsc::channel();
/// let (ftx, frx) = mpsc::channel();
/// mtx.send(2).expect("Failed to send an input to the VM.");
/// thread::spawn(move || {
///     IntcodeVM::with_inp_flag(&input, Some(prx), Some(ptx), Some(ftx))
///         .run_prog()
/// });
/// for _ in frx.recv() {
///     println!("received {}", mrx.recv().expect("VM disconnected."));
/// }
/// ```
#[derive(Debug)]
pub struct IntcodeVM {
    tape: Tape,
    ip: usize,
    rp: isize,
    input: Option<Receiver<Cell>>,
    output: Option<Sender<Cell>>,
    inp_wait_flag: Option<Sender<()>>,
    halted: bool,
}

impl Default for IntcodeVM {
    fn default() -> Self {
        Self {
            tape: Vec::new(),
            ip: 0,
            rp: 0,
            input: None,
            output: None,
            inp_wait_flag: None,
            halted: false,
        }
    }
}

trait Flags {
    fn flags(&self) -> (Mode, Mode, Mode);
}
impl Flags for Cell {
    fn flags(&self) -> (Mode, Mode, Mode) {
        let flag = |argpos| match self / 10_i128.pow(argpos) % 10 {
            0 => Mode::Position,
            1 => Mode::Immediate,
            2 => Mode::Relative,
            _ => unreachable!(),
        };
        (flag(2), flag(3), flag(4))
    }
}

impl IntcodeVM {
    /// Returns a new VM with a program and no I/O controls.
    pub fn from_prog(prog: &[Cell]) -> Self {
        Self {
            tape: prog.to_vec(),
            ..Default::default()
        }
    }

    /// Returns a new VM with a program and I/O controls.
    pub fn with_io(
        prog: &[Cell],
        input: Option<Receiver<Cell>>,
        output: Option<Sender<Cell>>,
    ) -> Self {
        Self {
            tape: prog.to_vec(),
            input,
            output,
            ..Default::default()
        }
    }

    /// Returns a new VM with a program and I/O controls, includes an input
    /// waiting flag sender that sends a unit (`()`) when the VM is expecting
    /// input.
    pub fn with_inp_flag(
        prog: &[Cell],
        input: Option<Receiver<Cell>>,
        output: Option<Sender<Cell>>,
        inp_wait_flag: Option<Sender<()>>,
    ) -> Self {
        Self {
            tape: prog.to_vec(),
            input,
            output,
            inp_wait_flag,
            ..Default::default()
        }
    }

    /// Runs the VM.
    pub fn run_prog(&mut self) -> Result<Tape, RanHaltedVMError> {
        if self.halted {
            return Err(RanHaltedVMError);
        }
        while !self.halted {
            match self[self.ip] % 100 {
                1 => self.maths(<i128 as Add>::add),
                2 => self.maths(<i128 as Mul>::mul),
                3 => self.input(),
                4 => self.outpt(),
                5 => self.test0(<i128 as PartialEq>::ne),
                6 => self.test0(<i128 as PartialEq>::eq),
                7 => self.test2(Ordering::Less),
                8 => self.test2(Ordering::Equal),
                9 => self.relpt(),
                99 => self.halted = true,
                _ => unreachable!(),
            }
        }
        Ok(self.tape.to_vec())
    }

    fn get(&mut self, mode: Mode, pad: usize) -> Cell {
        let in1 = self.ip + pad;
        self.reserve(in1);
        let in2 = match mode {
            Mode::Immediate => return self[in1],
            Mode::Position => self[in1] as usize,
            Mode::Relative => (self[in1] as isize + self.rp) as usize,
        };
        self.reserve(in2);
        self[in2]
    }

    #[inline]
    fn reserve(&mut self, s: usize) {
        if s >= self.tape.len() {
            self.tape.resize(s + 1, 0);
        }
    }

    fn maths(&mut self, op: fn(i128, i128) -> i128) {
        let (one, two, three) = self[self.ip].flags();
        let arg1 = self.get(one, 1);
        let arg2 = self.get(two, 2);
        let rel = if three == Mode::Relative { self.rp } else { 0 };
        let loc = (self[self.ip + 3] + rel as i128) as usize;
        self.reserve(loc);
        self[loc] = op(arg1, arg2);
        self.ip += 4;
    }

    fn input(&mut self) {
        let (one, ..) = self[self.ip].flags();
        let rel = if one == Mode::Relative { self.rp } else { 0 };
        let loc = (self[self.ip + 1] + rel as i128) as usize;
        self.reserve(loc);
        if let Some(sender) = &self.inp_wait_flag {
            sender.send(()).expect(
                "Error: failed to send input waiting flag: \
                    receiver disconnected.",
            );
        }
        self[loc] = self
            .input
            .as_ref()
            .expect(
                "Error: found input instruction but no receiver was created.",
            )
            .recv()
            .expect("Error: failed to receive input: sender disconnected.");
        self.ip += 2;
    }

    fn outpt(&mut self) {
        let (one, ..) = self[self.ip].flags();
        let val = self.get(one, 1);
        self.output
            .as_ref()
            .expect(
                "Error: found output instruction but no sender was created.",
            )
            .send(val)
            .expect("Error: failed to send output: receiver disconnected.");
        self.ip += 2;
    }

    // compare a cell against 0
    fn test0(&mut self, checker: fn(&Cell, &Cell) -> bool) {
        let (one, two, _) = self[self.ip].flags();
        let test = self.get(one, 1);
        if checker(&test, &0) {
            self.ip = self.get(two, 2) as usize;
        } else {
            self.ip += 3;
        }
    }

    // compare 2 arguments against each other
    fn test2(&mut self, mode: Ordering) {
        let (one, two, three) = self[self.ip].flags();
        let arg1 = self.get(one, 1);
        let arg2 = self.get(two, 2);
        let rel = if three == Mode::Relative { self.rp } else { 0 };
        let loc = (self[self.ip + 3] + rel as i128) as usize;
        self.reserve(loc);
        let test = arg1.cmp(&arg2) == mode;
        self[loc] = test as i128;
        self.ip += 4;
    }

    fn relpt(&mut self) {
        let (one, ..) = self[self.ip].flags();
        let arg1 = self.get(one, 1);
        self.rp += arg1 as isize;
        self.ip += 2;
    }
}

impl Index<usize> for IntcodeVM {
    type Output = Cell;
    /// To access any cell's value.
    fn index(&self, ix: usize) -> &Self::Output {
        &self.tape[ix]
    }
}

impl IndexMut<usize> for IntcodeVM {
    /// To mutably access any cell's value.
    fn index_mut(&mut self, ix: usize) -> &mut Self::Output {
        &mut self.tape[ix]
    }
}

/// An error returned if the VM is tried to be ran again after halted.
pub struct RanHaltedVMError;

impl std::error::Error for RanHaltedVMError {}

impl fmt::Display for RanHaltedVMError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Error: tried to run an already halted intcode VM")
    }
}

impl fmt::Debug for RanHaltedVMError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Error: tried to run an already halted intcode VM")
    }
}