From 6447db5df7b0d2d8fbac39acd25c3f2eb485a9a3 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Wed, 6 Dec 2023 15:44:56 -0500 Subject: [PATCH] Refactor bit manipulation HL instructions --- src/cpu/run/manip.rs | 73 +++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/src/cpu/run/manip.rs b/src/cpu/run/manip.rs index 9af119d..16a2ed3 100644 --- a/src/cpu/run/manip.rs +++ b/src/cpu/run/manip.rs @@ -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 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(()) +}