Skip to content

Commit 95cf0f6

Browse files
committed
Pad memory to avoid bounds checks
1 parent 57e6b09 commit 95cf0f6

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/year2019/intcode.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
//! Implementation of the full Intcode computer specification.
22
use std::collections::VecDeque;
33

4+
const EXTRA: usize = 2_000;
5+
46
pub enum State {
57
Input,
68
Output(i64),
@@ -15,8 +17,12 @@ pub struct Computer {
1517
}
1618

1719
impl Computer {
18-
pub fn new(code: &[i64]) -> Computer {
19-
Computer { pc: 0, base: 0, code: code.to_vec(), input: VecDeque::new() }
20+
pub fn new(input: &[i64]) -> Computer {
21+
let mut code = Vec::with_capacity(input.len() + EXTRA);
22+
code.extend_from_slice(input);
23+
code.resize(input.len() + EXTRA, 0);
24+
25+
Computer { pc: 0, base: 0, code, input: VecDeque::new() }
2026
}
2127

2228
pub fn input(&mut self, value: i64) {
@@ -120,10 +126,6 @@ impl Computer {
120126
_ => unreachable!(),
121127
};
122128

123-
if index >= self.code.len() {
124-
self.code.resize(index + 1, 0);
125-
}
126-
127129
index
128130
}
129131
}

0 commit comments

Comments
 (0)