#[cfg(test)]
mod tests {
use crate::op_code::*;
use crate::op_code::Opcode::{OpAdd, OpConst};
#[test]
fn test_make() {
struct Test {
op: Opcode,
operands: Vec<usize>,
expected: Vec<u8>,
}
let tests = vec![
Test { op: Opcode::OpConst, operands: vec![65534], expected: vec![OpConst as u8, 255, 254] },
Test { op: Opcode::OpAdd, operands: vec![], expected: vec![OpAdd as u8] },
];
for t in tests {
let ins = make_instructions(t.op, &t.operands);
assert_eq!(ins, t.expected)
}
}
#[test]
fn test_read_operands() {
struct Test {
op: Opcode,
operands: Vec<usize>,
bytes_read: usize,
}
let tests = vec! {
Test { op: Opcode::OpConst, operands: vec![65534], bytes_read: 2 },
Test { op: Opcode::OpConst, operands: vec![255], bytes_read: 2 },
};
for t in tests {
let ins = make_instructions(t.op, &t.operands);
let (operands_read, n) = read_operands(DEFINITIONS.get(&t.op).unwrap(), &ins[1..]);
assert_eq!(operands_read, t.operands);
assert_eq!(n, t.bytes_read);
}
}
#[test]
fn test_instructions_string() {
let ins = vec![
Instructions { data: make_instructions(OpAdd, &vec![]) },
Instructions { data: make_instructions(OpConst, &vec![2]) },
Instructions { data: make_instructions(OpConst, &vec![65535]) },
];
let expected = "0000 OpAdd\n\
0001 OpConst 2\n\
0004 OpConst 65535\n";
let merged_ins = ins.iter().fold(vec![], |sum, i| [sum.as_slice(), i.data.as_slice()].concat());
let concatted = Instructions { data: merged_ins }.string();
assert_eq!(concatted, expected);
}
}