Skip to content
Snippets Groups Projects
inst.rs 24.9 KiB
Newer Older
  • Learn to ignore specific revisions
  • fn rst_38h(cpu: &mut Cpu) {
        rst(cpu, 0x0038);
    }
    
    fn rl_c(cpu: &mut Cpu) {
        cpu.c = rl(cpu, cpu.c);
    }
    
    fn swap_a(cpu: &mut Cpu) {
        cpu.a = swap(cpu, cpu.a)
    }
    
    fn bit_7_h(cpu: &mut Cpu) {
        bit_h(cpu, 7);
    }
    
    /// Helper function that rotates (shifts) the given
    /// byte (probably from a register) and updates the
    /// proper flag registers.
    fn rl(cpu: &mut Cpu, byte: u8) -> u8 {
        let carry = cpu.get_carry();
    
        cpu.set_carry(byte & 0x80 == 0x80);
    
        let result = (byte << 1) | carry as u8;
    
        cpu.set_sub(false);
        cpu.set_zero(result == 0);
        cpu.set_half_carry(false);
    
        result
    }
    
    /// Helper function to test one bit in a u8.
    /// Returns true if bit is 0.
    fn bit_zero(val: u8, bit: u8) -> bool {
        (val & (1u8 << (bit as usize))) == 0
    }
    
    fn bit_h(cpu: &mut Cpu, bit: u8) {
        cpu.set_sub(false);
        cpu.set_zero(bit_zero(cpu.h, bit));
        cpu.set_half_carry(true);
    }
    
    fn add_set_flags(cpu: &mut Cpu, first: u8, second: u8) -> u8 {
        let first = first as u32;
        let second = second as u32;
    
        let value = first.wrapping_add(second);
        let value_b = value as u8;
    
        cpu.set_sub(false);
        cpu.set_zero(value_b == 0);
        cpu.set_half_carry((first ^ second ^ value) & 0x10 == 0x10);
        cpu.set_carry(value & 0x100 == 0x100);
    
        value_b
    }
    
    fn sub_set_flags(cpu: &mut Cpu, first: u8, second: u8) -> u8 {
        let first = first as u32;
        let second = second as u32;
    
        let value = first.wrapping_sub(second);
        let value_b = value as u8;
    
        cpu.set_sub(true);
        cpu.set_zero(value_b == 0);
        cpu.set_half_carry((first ^ second ^ value) & 0x10 == 0x10);
        cpu.set_carry(value & 0x100 == 0x100);
    
        value_b
    }
    
    fn add_u16_u16(cpu: &mut Cpu, first: u16, second: u16) -> u16 {
        let first = first as u32;
        let second = second as u32;
        let value = first.wrapping_add(second);
    
        cpu.set_sub(false);
        cpu.set_half_carry((first ^ second ^ value) & 0x1000 == 0x1000);
        cpu.set_carry(value & 0x10000 == 0x10000);
    
        value as u16
    }
    
    fn swap(cpu: &mut Cpu, value: u8) -> u8 {
        cpu.set_sub(false);
        cpu.set_zero(value == 0);
        cpu.set_half_carry(false);
        cpu.set_carry(false);
    
        (value << 4) | (value >> 4)
    }
    
    /// Helper function for RST instructions, pushes the
    /// current PC to the stack and jumps to the provided
    /// address.
    fn rst(cpu: &mut Cpu, addr: u16) {
        cpu.push_word(cpu.pc);
        cpu.pc = addr;
    }