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
mod instruction;
use crate::types::Numeric;
use crate::types::Numeric::*;
pub use self::instruction::Instruction;
pub use self::instruction::Instruction::*;
pub use self::instruction::{CalculationMethod, ComparisonMethod, BitwiseMethod};
use byteorder::{LittleEndian, WriteBytesExt};
pub fn convert_instruction(instruction: Instruction) -> Vec<u8> {
match instruction {
Halt => {
vec![1, 0, 0, 0]
},
Load { value, register } => {
let mut bytecode = vec![2, register as u8, 0, 0];
match value {
Int { value } => bytecode.write_i64::<LittleEndian>(value).unwrap(),
UInt { value } => bytecode.write_u64::<LittleEndian>(value).unwrap(),
Float { value } => bytecode.write_f64::<LittleEndian>(value).unwrap(),
}
bytecode
},
_ => vec![0, 0, 0, 0]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn convert_halt() {
assert_eq!(
convert_instruction(Instruction::Halt),
vec![1, 0, 0, 0]
)
}
#[test]
fn convert_load() {
assert_eq!(
convert_instruction(Instruction::Load { value: Numeric::Int { value: 200 }, register: 7 }),
vec![
2, 7, 0, 0,
200, 0, 0, 0, 0, 0, 0, 0
]
)
}
}