♻️ Machine::read_memory is now indeed a self method

This commit is contained in:
François Autin 2023-03-24 18:34:06 +01:00
parent 88e1921b3c
commit b33c31ef38
No known key found for this signature in database
GPG Key ID: 343F5D382E1DD77C

View File

@ -105,7 +105,7 @@ impl Machine {
/// - **machine** which contains the main memory
/// - **size** the number of bytes to read (1, 2, 4, 8)
/// - **address** in the memory to read
pub fn read_memory(machine : &mut Machine, size : i32, address : usize) -> u64 {
pub fn read_memory(&self, size : i32, address : usize) -> u64 {
if ![1, 2, 4, 8].contains(&size) {
panic!("ERROR read_memory : wrong size parameter {size}, must be (1, 2, 4 or 8)");
}
@ -113,7 +113,7 @@ impl Machine {
let mut ret: u64 = 0;
for i in 0..size {
ret <<= 8;
ret += machine.main_memory[address + i as usize] as u64;
ret += self.main_memory[address + i as usize] as u64;
}
ret
}
@ -175,7 +175,7 @@ impl Machine {
println!("________________SP________________");
let sp_index = machine.int_reg.get_reg(2);
for i in 0..5 {
println!("SP+{:<2} : {:16x}", i*8, Self::read_memory(machine, 8, (sp_index + i*8) as usize));
println!("SP+{:<2} : {:16x}", i*8, machine.read_memory(8, (sp_index + i*8) as usize));
}
println!("##################################");
}
@ -329,19 +329,19 @@ impl Machine {
fn load_instruction(machine: &mut Machine, inst: Instruction) -> Result<(), MachineError> {
match inst.funct3 {
RISCV_LD_LB | RISCV_LD_LBU => {
let tmp = Self::read_memory(machine, 1, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
let tmp = machine.read_memory(1, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
machine.int_reg.set_reg(inst.rd, tmp);
},
RISCV_LD_LH | RISCV_LD_LHU => {
let tmp = Self::read_memory(machine, 2, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
let tmp = machine.read_memory(2, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
machine.int_reg.set_reg(inst.rd, tmp);
},
RISCV_LD_LW | RISCV_LD_LWU => {
let tmp = Self::read_memory(machine, 4, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
let tmp = machine.read_memory(4, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
machine.int_reg.set_reg(inst.rd, tmp);
},
RISCV_LD_LD => {
let tmp = Self::read_memory(machine, 8, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
let tmp = machine.read_memory(8, (machine.int_reg.get_reg(inst.rs1) + inst.imm12_I_signed as i64) as usize) as i64;
machine.int_reg.set_reg(inst.rd, tmp);
},
_ => panic!("In LD switch case, this should never happen... Instr was {}", inst.value)
@ -653,7 +653,7 @@ mod test {
let mut m = Machine::init_machine();
m.main_memory[4] = 43;
m.main_memory[5] = 150;
assert_eq!((43 << 8) + 150, Machine::read_memory(&mut m, 2, 4));
assert_eq!((43 << 8) + 150, m.read_memory(2, 4));
}
#[test]