Skip to content

Commit

Permalink
added jmpf and jmpb
Browse files Browse the repository at this point in the history
  • Loading branch information
AdityaKhowalGithub committed Apr 11, 2024
1 parent d6c5b6f commit 2301287
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ pub enum Opcode {
MUL, //multiply
DIV, //divide
JMP, //jump
JMPF,
JMPB,
}

//an instruction itself is 32 bits
Expand All @@ -34,6 +36,8 @@ impl From<u8> for Opcode {
4 => Opcode::MUL,
5 => Opcode::DIV,
6 => Opcode::JMP,
7 => Opcode::JMPF,
8 => Opcode::JMPB,
_ => Opcode::IGL,
}
}
Expand Down
28 changes: 28 additions & 0 deletions src/vm.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::usize;

use super::instruction::Opcode;
pub struct VM {
registers: [i32; 32],
Expand Down Expand Up @@ -84,6 +86,14 @@ impl VM {
let target = self.registers[self.next8bits() as usize];
self.pc = target as usize;
}
Opcode::JMPF => {
let value = self.registers[self.next8bits() as usize];
self.pc += value as usize;
}
Opcode::JMPB => {
let value = self.registers[self.next8bits() as usize];
self.pc -= value as usize;
}

_ => {
println!("unrecognized opcode, terminating");
Expand Down Expand Up @@ -208,4 +218,22 @@ mod tests {
test_vm.run_once();
assert_eq!(test_vm.pc, 1);
}

#[test]
fn test_jmpf_opcode() {
let mut test_vm = get_test_vm();
test_vm.registers[0] = 1;
test_vm.program = vec![7, 0, 0, 0];
test_vm.run_once();
assert_eq!(test_vm.pc, 1);
}

#[test]
fn test_jmpb_opcode() {
let mut test_vm = get_test_vm();
test_vm.registers[0] = 1;
test_vm.program = vec![8, 0, 0, 0];
test_vm.run_once();
assert_eq!(test_vm.pc, 1);
}
}

0 comments on commit 2301287

Please sign in to comment.