From 72b2a105f01af012c21e1a67a9f07c5b04d65bb7 Mon Sep 17 00:00:00 2001 From: Quentin Legot Date: Fri, 27 Jan 2023 11:15:39 +0100 Subject: [PATCH] Add tests to machine --- src/simulator/machine.rs | 68 ++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 9 deletions(-) diff --git a/src/simulator/machine.rs b/src/simulator/machine.rs index e336842..26f4eae 100644 --- a/src/simulator/machine.rs +++ b/src/simulator/machine.rs @@ -139,10 +139,9 @@ impl Machine { /// ### Parameters /// /// - **machine** which contains a table of instructions - pub fn run(machine : Machine){ - let mut m = machine; - loop{ - Machine::one_instruction(&mut m); + pub fn run(&mut self){ + loop { + self.one_instruction(); } } @@ -151,8 +150,8 @@ impl Machine { /// ### Parameters /// /// - **machine** which contains a table of instructions and a pc to the actual instruction - pub fn one_instruction(machine :&mut Machine) { - + pub fn one_instruction(&mut self) { + let mut machine = self; let unsigned_reg1 : u64; let unsigned_reg2 : u64; let long_result : i128; @@ -466,11 +465,21 @@ impl Machine { #[cfg(test)] mod test { - use crate::simulator::machine::Machine; + use crate::simulator::{machine::Machine, decode}; + + + fn init() -> Machine { + let mut m = Machine::_init_machine(); + m.main_memory[0] = 255; + m.main_memory[1] = 43; + m.main_memory[2] = 7; + m.main_memory[3] = 157; + m + } #[test] fn test_read_memory() { - let mut m = Machine::_init_machine(); + let mut m = init(); m.main_memory[4] = 43; m.main_memory[5] = 150; assert_eq!((43 << 8) + 150, Machine::read_memory(&mut m, 2, 4)); @@ -478,9 +487,50 @@ impl Machine { #[test] fn test_write_memory() { - let mut m = Machine::_init_machine(); + let mut m = init(); Machine::write_memory(&mut m, 2, 6, (43 << 8) + 150); assert_eq!(43, m.main_memory[6]); assert_eq!(150, m.main_memory[7]); } + + #[test] + fn test_op_add() { + let mut m = init(); + m.int_reg[6] = 5; // t1 + m.instructions[0] = 0b0000000_00110_00000_000_00101_0110011; + // add t0, zero, t1 + m.one_instruction(); + assert_eq!(m.int_reg[5], 5); + } + + #[test] + fn test_op_sub() { + let mut m = init(); + m.int_reg[6] = 5; // t1 + m.instructions[0] = 0b0100000_00110_00000_000_00101_0110011; + // sub t0, zero, t1 + m.one_instruction(); + assert_eq!(m.int_reg[5], -5); + } + + #[test] + fn test_op_addi() { + let mut m = init(); + m.int_reg[6] = 5; // t1 + m.instructions[0] = 0b11111111111_00110_000_00101_0010011; + // add t0, t1, 2047 + m.one_instruction(); + assert_eq!(m.int_reg[5], 2052); + } + + /// Equivalent of subi + #[test] + fn test_op_addi_neg() { + let mut m = init(); + m.int_reg[6] = -5; // t1 + m.instructions[0] = 0b11111111111_00110_000_00101_0010011; + // addi t0, t1, 2047 + m.one_instruction(); + assert_eq!(m.int_reg[5], 2042); + } }