From f17bb032ccf30483274496e3127d3d9d558d8b97 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Mon, 15 Mar 2021 22:41:41 -0500 Subject: [PATCH] fix: implement bitfield macros in timer.rs --- src/timer.rs | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/timer.rs b/src/timer.rs index 45fef55..bda3ae1 100644 --- a/src/timer.rs +++ b/src/timer.rs @@ -1,3 +1,5 @@ +use bitfield::bitfield; + use crate::instruction::Cycles; #[derive(Debug, Clone, Copy)] @@ -34,32 +36,45 @@ impl From for TimerSpeed { 0x01 => Self::Freq262144Hz, 0x10 => Self::Freq65536Hz, 0x11 => Self::Freq16384Hz, - _ => unreachable!(), + _ => unreachable!("{:04X} is not a valid representation of TimerSpeed", byte), } } } -#[derive(Debug, Clone, Copy)] -pub struct TimerControl { - enabled: bool, - speed: TimerSpeed, +impl From for u8 { + fn from(speed: TimerSpeed) -> Self { + speed as u8 + } +} + +bitfield! { + pub struct TimerControl(u8); + impl Debug; + enabled, set_enabled: 2; + from into TimerSpeed, speed, set_speed: 1, 0; +} + +impl Copy for TimerControl {} +impl Clone for TimerControl { + fn clone(&self) -> Self { + *self + } +} + +impl Default for TimerControl { + fn default() -> Self { + Self(0) + } } impl From for TimerControl { fn from(byte: u8) -> Self { - let byte = byte & 0x07; // Clear everything but last 3 bits - - Self { - enabled: (byte >> 2) == 0x01, - speed: (byte & 0x03).into(), // Clear everything but last 2 bits - } + Self(byte) } } impl From for u8 { - fn from(control: TimerControl) -> Self { - let byte: u8 = control.speed as u8; // Get bit 1 and 0. - - (byte & !(1u8 << 2)) | ((control.enabled as u8) << 2) // specifically manipulate bit 2 + fn from(ctrl: TimerControl) -> Self { + ctrl.0 } }