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
use crate::instruction::Instruction;
use std::collections::HashMap;
use std::fmt;
#[derive(Debug, Default)]
pub struct InstructionTable<T: fmt::Debug>(HashMap<usize, Instruction<T>>);
impl<T: fmt::Debug> InstructionTable<T> {
pub fn new() -> InstructionTable<T> {
InstructionTable(HashMap::new())
}
pub fn by_op_code(&self, op_code: usize) -> Option<&Instruction<T>> {
self.0.get(&op_code)
}
pub fn by_name(&self, name: &str) -> Option<&Instruction<T>> {
self.0.values().find(|ref instr| instr.name == name)
}
pub fn insert(&mut self, instr: Instruction<T>) {
self.0.insert(instr.op_code, instr);
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn symbols(&self) -> Vec<(usize, String)> {
let mut result = vec![];
self.0.keys().for_each(|ref key| {
let instr = &self.0[key];
result.push((instr.op_code, instr.name.clone()));
});
result.sort_by(|lhs, rhs| lhs.0.cmp(&rhs.0));
result
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::machine::Machine;
fn noop(_machine: &mut Machine<usize>, _args: &[usize]) {}
#[test]
fn new() {
let table: InstructionTable<usize> = InstructionTable::new();
assert!(table.is_empty())
}
#[test]
fn insert() {
let mut table: InstructionTable<usize> = InstructionTable::new();
assert!(table.is_empty());
table.insert(Instruction::new(0, "NOOP", 0, noop));
assert!(!table.is_empty());
}
#[test]
fn by_op_code() {
let mut table: InstructionTable<usize> = InstructionTable::new();
table.insert(Instruction::new(0, "NOOP", 0, noop));
let instr = table.by_op_code(0).unwrap();
assert_eq!(instr.name, "NOOP");
}
#[test]
fn by_name() {
let mut table: InstructionTable<usize> = InstructionTable::new();
table.insert(Instruction::new(0, "NOOP", 0, noop));
let instr = table.by_name("NOOP").unwrap();
assert_eq!(instr.op_code, 0);
}
}