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
296
297
298
299
300
301
302
303
304
305
306
307
//! The **Intcode Program** used in solutions for day [2], [5], [7] and [9].
//!
//! [2]: crate::y2019::d02
//! [5]: crate::y2019::d05
//! [7]: crate::y2019::d07
//! [9]: crate::y2019::d09

use std::{
    collections::VecDeque,
    convert::{TryFrom, TryInto},
    iter::FromIterator,
};

use anyhow::{bail, Error, Result};
use thiserror::Error;

/// A list of errors that may occur during the usage of this intcode [`Program`].
#[derive(Debug, Error)]
pub enum ProgramError {
    /// Parsing error while converting an input string with [`parse_input`].
    #[error("invalid integer")]
    ParseInt(#[from] std::num::ParseIntError),
    /// An opcode couldn't be parse because it's not supported by the program.
    #[error("unknown opcode `{0}`")]
    UnknownOpcode(i64),
    /// A parameter mode couldn't be parsed because it's not supported by the program.
    #[error("unknown mode `{0}`")]
    UnknownMode(i64),
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Opcode {
    Add,
    Mul,
    Input,
    Output,
    JumpIfTrue,
    JumpIfFalse,
    LessThan,
    Equals,
    AdjustBase,
    Exit,
}

impl TryFrom<i64> for Opcode {
    type Error = anyhow::Error;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        Ok(match value {
            1 => Self::Add,
            2 => Self::Mul,
            3 => Self::Input,
            4 => Self::Output,
            5 => Self::JumpIfTrue,
            6 => Self::JumpIfFalse,
            7 => Self::LessThan,
            8 => Self::Equals,
            9 => Self::AdjustBase,
            99 => Self::Exit,
            _ => bail!(ProgramError::UnknownOpcode(value)),
        })
    }
}

impl From<Opcode> for i64 {
    fn from(value: Opcode) -> Self {
        match value {
            Opcode::Add => 1,
            Opcode::Mul => 2,
            Opcode::Input => 3,
            Opcode::Output => 4,
            Opcode::JumpIfTrue => 5,
            Opcode::JumpIfFalse => 6,
            Opcode::LessThan => 7,
            Opcode::Equals => 8,
            Opcode::AdjustBase => 9,
            Opcode::Exit => 99,
        }
    }
}

impl Opcode {
    fn len(self) -> usize {
        match self {
            Self::Add | Self::Mul | Self::LessThan | Self::Equals => 4,
            Self::Input | Self::Output | Self::AdjustBase => 2,
            Self::JumpIfTrue | Self::JumpIfFalse => 3,
            Self::Exit => 1,
        }
    }
}

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

impl TryFrom<i64> for Mode {
    type Error = anyhow::Error;

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        Ok(match value {
            0 => Self::Position,
            1 => Self::Immediate,
            2 => Self::Relative,
            _ => bail!(ProgramError::UnknownMode(value)),
        })
    }
}

/// A program that operates on a set of commands which represent Intcodes.
#[derive(Default)]
pub struct Program {
    cmds: Vec<i64>,
    params: VecDeque<i64>,
    pos: usize,
    rel_base: i64,
}

impl Program {
    /// Create a new program that operates on the provided commands. Start parameters can be given
    /// as well.
    pub fn new(cmds: Vec<i64>, start_params: &[i64]) -> Self {
        Self {
            cmds,
            params: VecDeque::from_iter(start_params.iter().cloned()),
            ..Default::default()
        }
    }

    /// Run one cycle of the program. A cycle is finished when either the position is at the end of
    /// all commands, or an **output** (`4`) or **exit** (`99`) command is reached. In general this
    /// function should be repeatedly called until [`is_finished`] returns `true`.
    ///
    /// The program can still be run even if it's already finished, but the output will always be
    /// zero.
    ///
    /// [`is_finished`]: Program::is_finished
    ///
    /// # Example
    ///
    /// ```rust
    /// use aoc::y2019::intcode::{parse_input, Program};
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut program = Program::new(parse_input("3,5,4,5,99,0")?, &[1]);
    ///
    ///     assert_eq!(1, program.run(&[])?);
    ///     assert!(program.is_finished());
    ///
    ///     assert_eq!(0, program.run(&[])?); // Already finished
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn run(&mut self, params: &[i64]) -> Result<i64> {
        self.params.extend(params);

        while self.pos < self.cmds.len() {
            let (opcode, mode1, mode2, mode3) = parse_opcode(self.cmds[self.pos])?;
            match opcode {
                Opcode::Add => {
                    let x = self.get_value(1, mode1);
                    let y = self.get_value(2, mode2);
                    self.set_value(3, mode3, x + y);
                    self.pos += opcode.len();
                }
                Opcode::Mul => {
                    let x = self.get_value(1, mode1);
                    let y = self.get_value(2, mode2);
                    self.set_value(3, mode3, x * y);
                    self.pos += opcode.len();
                }
                Opcode::Input => {
                    let value = self.params.pop_front().unwrap();
                    self.set_value(1, mode1, value);
                    self.pos += opcode.len();
                }
                Opcode::Output => {
                    let value = self.get_value(1, mode1);
                    self.pos += opcode.len();
                    return Ok(value);
                }
                Opcode::JumpIfTrue => {
                    self.pos = if self.get_value(1, mode1) != 0 {
                        self.get_value(2, mode2).try_into()?
                    } else {
                        self.pos + opcode.len()
                    };
                }
                Opcode::JumpIfFalse => {
                    self.pos = if self.get_value(1, mode1) == 0 {
                        self.get_value(2, mode2).try_into()?
                    } else {
                        self.pos + opcode.len()
                    };
                }
                Opcode::LessThan => {
                    let x = self.get_value(1, mode1);
                    let y = self.get_value(2, mode2);
                    self.set_value(3, mode3, i64::from(x < y));
                    self.pos += opcode.len();
                }
                Opcode::Equals => {
                    let x = self.get_value(1, mode1);
                    let y = self.get_value(2, mode2);
                    self.set_value(3, mode3, i64::from(x == y));
                    self.pos += opcode.len();
                }
                Opcode::AdjustBase => {
                    self.rel_base += self.get_value(1, mode1);
                    self.pos += opcode.len();
                }
                Opcode::Exit => {
                    break;
                }
            }
        }
        Ok(0)
    }

    /// Check whether this program is still executable or reached the end of execution. The end is
    /// reached when either the current position is at the end of commands or the current command is
    /// the **exit** (`99`) code.
    pub fn is_finished(&self) -> bool {
        self.pos >= self.cmds.len() || self.cmds[self.pos] == i64::from(Opcode::Exit)
    }

    /// Return the current state of the commands this program runs. This will consume the program.
    pub fn cmds(self) -> Vec<i64> {
        self.cmds
    }

    fn get_address(&self, offset: usize, mode: Mode) -> usize {
        let pos = self.pos + offset;
        match mode {
            Mode::Immediate => pos,
            Mode::Position => self.cmds[pos] as usize,
            Mode::Relative => (self.cmds[pos] + self.rel_base) as usize,
        }
    }

    fn get_value(&self, offset: usize, mode: Mode) -> i64 {
        let i = self.get_address(offset, mode);
        if self.cmds.len() <= i {
            return 0;
        }

        self.cmds[i]
    }

    fn set_value(&mut self, offset: usize, mode: Mode, value: i64) {
        let pos = self.get_address(offset, mode);
        if self.cmds.len() <= pos {
            self.cmds.resize(pos + 1, 0);
        }
        self.cmds[pos] = value;
    }
}

/// Parse an input string for use by the [`Program`]. The string is expected to be a list of
/// integers separated by comma `,`.
///
/// # Errors
///
/// If the input is invalid in any way, a [`ProgramError::ParseInt`] is returned.
pub fn parse_input(input: &str) -> Result<Vec<i64>> {
    input
        .split(',')
        .map(|v| v.trim().parse::<i64>().map_err(ProgramError::from).map_err(Error::from))
        .collect()
}

fn parse_opcode(opcode: i64) -> Result<(Opcode, Mode, Mode, Mode)> {
    Ok((
        (opcode % 100).try_into()?,
        (opcode / 100 % 10).try_into()?,
        (opcode / 1000 % 10).try_into()?,
        (opcode / 10000 % 10).try_into()?,
    ))
}

#[cfg(test)]
pub(crate) mod tests {
    use itertools::Itertools;

    use super::*;

    /// Turn a slice of integers back into a comma separated string. For testing purposes.
    pub fn input_to_string(input: &[i64]) -> String {
        input.iter().map(|i| i.to_string()).join(",")
    }

    #[test]
    fn test_parse_opcode() {
        assert_eq!(
            (Opcode::Mul, Mode::Position, Mode::Immediate, Mode::Position),
            parse_opcode(1002).unwrap()
        );
        assert_eq!(
            (Opcode::Add, Mode::Immediate, Mode::Immediate, Mode::Position),
            parse_opcode(1101).unwrap()
        );
    }
}