From 72340fc8477baaaf5ea0e059e7a8c611ffd767c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Magalh=C3=A3es?= <joamag@gmail.com>
Date: Tue, 28 Jun 2022 21:11:39 +0100
Subject: [PATCH] feat: better stack operations

---
 examples/sdl/src/main.rs |  5 +++--
 src/cpu.rs               | 30 +++++++++++++++++++++++++-----
 2 files changed, 28 insertions(+), 7 deletions(-)

diff --git a/examples/sdl/src/main.rs b/examples/sdl/src/main.rs
index 77da12f8..bc62660b 100644
--- a/examples/sdl/src/main.rs
+++ b/examples/sdl/src/main.rs
@@ -4,9 +4,10 @@ fn main() {
     let mut game_boy = GameBoy::new();
     game_boy.load_boot_default();
 
-    for _ in 0..40000 {
+    for i in 0..24612 {
         game_boy.clock();
-        if game_boy.cpu().pc() >= 0x0032 {
+        if game_boy.cpu().pc() >= 0x3032 {
+            println!("{}", i);
             break;
         }
     }
diff --git a/src/cpu.rs b/src/cpu.rs
index ab674168..d663cdf8 100644
--- a/src/cpu.rs
+++ b/src/cpu.rs
@@ -87,7 +87,7 @@ pub const INSTRUCTIONS: [(fn(&mut Cpu), u8, &'static str); 256] = [
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
-    (nop, 4, "NOP"),
+    (ld_c_a, 4, "LD C, A"),
     // 0x5 opcodes
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
@@ -213,7 +213,7 @@ pub const INSTRUCTIONS: [(fn(&mut Cpu), u8, &'static str); 256] = [
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
-    (nop, 4, "NOP"),
+    (push_bc, 16, "PUSH BC"),
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
     (nop, 4, "NOP"),
@@ -613,6 +613,18 @@ impl Cpu {
         word
     }
 
+    #[inline(always)]
+    fn push_byte(&mut self, byte: u8){
+        self.sp -= 1;
+        self.mmu.write(self.sp, byte);
+    }
+
+    #[inline(always)]
+    fn push_word(&mut self, word: u16) {
+        self.push_byte((word >> 8) as u8);
+        self.push_byte(word as u8);
+    }
+
     #[inline(always)]
     fn get_zero(&self) -> bool {
         self.zero
@@ -771,6 +783,10 @@ fn ld_a_u8(cpu: &mut Cpu) {
     cpu.a = byte;
 }
 
+fn ld_c_a(cpu: &mut Cpu) {
+    cpu.c = cpu.a;
+}
+
 fn xor_a_a(cpu: &mut Cpu) {
     cpu.a ^= cpu.a;
 
@@ -780,10 +796,14 @@ fn xor_a_a(cpu: &mut Cpu) {
     cpu.set_carry(false);
 }
 
+fn push_bc(cpu: &mut Cpu) {
+    cpu.push_word(cpu.bc());
+}
+
 fn call_u16(cpu: &mut Cpu) {
-    // @todo push stack and set the current PC
-    // to be able to jump
-    cpu.sp += 1;
+    let word = cpu.read_u16();
+    cpu.push_word(cpu.pc);
+    cpu.pc = word;
 }
 
 fn ld_mff00u8_a(cpu: &mut Cpu) {
-- 
GitLab