diff --git a/src/main.rs b/src/main.rs index 7e96a0a..b17b5a5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,8 @@ struct Args { } type Register = u16; +type Instruction = u8; +type Address = u16; type ROM = Vec; struct Memory { @@ -29,7 +31,7 @@ impl Memory { ram: [0x0; 8192], } } - fn get(&self, address: u16) -> u8 { + fn get(&self, address: Address) -> u8 { match address { 0x0..0x8000 => { // rom access @@ -100,16 +102,33 @@ struct CPU { } impl CPU { - fn execute(&mut self, opcode: u8) { + fn exec_next(&mut self) { + let opcode = self.next_opcode(); + let p1 = self.next_opcode(); + let p2 = self.next_opcode(); match opcode { - 0 => { + 0x0 => { // noop } + 0x01 => { + self.state.bc = u8s_to_u16(&p1, &p2); + } + 0x66 => { + self.state.hl = u8s_to_u16(&self.memory.get(self.state.hl), &p2); + } + 0xC3 => { + self.state.pc = u8s_to_u16(&p1, &p2); + } _ => { panic!("unimplemented opcode: {:#X}", opcode); } }; } + fn next_opcode(&mut self) -> u8 { + let opcode = self.memory.get(self.state.pc); + self.state.pc += 0x1; + return opcode; + } } fn main() { @@ -121,8 +140,16 @@ fn main() { state: State::default(), }; loop { - let op = cpu.memory.get(cpu.state.pc); - cpu.state.pc += 1; - cpu.execute(op); + cpu.exec_next(); } } + +fn u8s_to_u16(p1: &u8, p2: &u8) -> u16 { + ((*p1 as u16) << 8) | *p2 as u16 +} + +fn u16_to_u8s(p: &u16) -> (u8, u8) { + let p1 = *p as u8; + let p2 = (*p >> 8) as u8; + (p1, p2) +}