-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprog.rs
67 lines (58 loc) · 1.31 KB
/
prog.rs
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
#[derive(Debug)]
struct CpuState {
r: [i32;2],
pc: usize,
}
type Op<'a> = &'a dyn Fn(CpuState) -> CpuState;
impl CpuState {
fn run(mut self, prog: &[Op]) -> i32 {
while self.pc < prog.len() {
self = prog[self.pc](self);
}
self.r[0]
}
}
fn log(msg: &str, state: &CpuState) {
println!("{}: {:?}", msg, state);
}
#[allow(unused)]
fn add(mut state: CpuState) -> CpuState {
log("add_start", &state);
state.r[0] += state.r[1];
state.pc += 1;
log("add_end", &state);
state
}
#[allow(unused)]
fn sub(mut state: CpuState) -> CpuState {
log("sub_start", &state);
state.r[0] -= state.r[1];
state.pc += 1;
log("sub_end", &state);
state
}
#[allow(unused)]
fn rst(_state: CpuState) -> CpuState {
let state = CpuState {
r: [0; 2],
pc: 0,
};
log("reset", &state);
state
}
fn make_jmp(target: usize) -> Box<dyn Fn(CpuState) -> CpuState> {
Box::new(move |mut state| {
state.pc = target;
log(&format!("jmp {}", target), &state);
state
})
}
fn main() {
let state = CpuState { r: [0, 1], pc: 0 };
let add: Op = &add;
let sub: Op = ⊂
let _rst: Op = &rst;
let jmp3: Op = &make_jmp(3);
let prog = [jmp3, add, add, sub, add];
println!("{}", state.run(&prog));
}