Refactor bit manipulation HL instructions

master
Nick Krichevsky 2023-12-06 15:44:56 -05:00
parent 4202e70240
commit 6447db5df7
1 changed files with 38 additions and 35 deletions

View File

@ -20,41 +20,7 @@ impl Run for BitManipulationInstruction {
}
BitManipulationInstruction::SetHLValueBit { bit } => {
// TODO: wow this code kinda sucks, I kinda wanna make a better to deal with the HL values
let hl_addr = processor
.registers
.get_combined_register(register::Combined::HL);
#[allow(clippy::match_wildcard_for_single_variants)]
let hl_value = processor
.memory
.get(hl_addr.into())
.map_err(|err| match err {
memory::Error::GetInvalidAddress(addr) => {
run::Error::InvalidRegisterAddress(
register::SixteenBit::Combined(register::Combined::HL),
addr,
)
}
err => run::Error::Unknown(Box::new(err)),
})?;
let upd_value = set_nth_bit(hl_value, bit);
#[allow(clippy::match_wildcard_for_single_variants)]
processor
.memory
.set(hl_addr.into(), upd_value)
.map_err(|err| match err {
memory::Error::SetInvalidAddress(addr, _value) => {
run::Error::InvalidRegisterAddress(
register::SixteenBit::Combined(register::Combined::HL),
addr,
)
}
err => run::Error::Unknown(Box::new(err)),
})?;
transform_hl_value(processor, |value| set_nth_bit(value, bit))?;
Ok(Cycles(16))
}
@ -67,3 +33,40 @@ fn set_nth_bit(value: u8, bit: u8) -> u8 {
value | (0x1 << bit)
}
fn transform_hl_value<F: Fn(u8) -> u8>(
processor: &mut Processor,
transform: F,
) -> Result<(), run::Error> {
let hl_addr = processor
.registers
.get_combined_register(register::Combined::HL);
#[allow(clippy::match_wildcard_for_single_variants)]
let hl_value = processor
.memory
.get(hl_addr.into())
.map_err(|err| match err {
memory::Error::GetInvalidAddress(addr) => run::Error::InvalidRegisterAddress(
register::SixteenBit::Combined(register::Combined::HL),
addr,
),
err => run::Error::Unknown(Box::new(err)),
})?;
let upd_value = transform(hl_value);
#[allow(clippy::match_wildcard_for_single_variants)]
processor
.memory
.set(hl_addr.into(), upd_value)
.map_err(|err| match err {
memory::Error::SetInvalidAddress(addr, _value) => run::Error::InvalidRegisterAddress(
register::SixteenBit::Combined(register::Combined::HL),
addr,
),
err => run::Error::Unknown(Box::new(err)),
})?;
Ok(())
}