From f2f47e13d427fb44f8f6005200a4bf0932e0e2b5 Mon Sep 17 00:00:00 2001 From: John Breaux Date: Tue, 28 Mar 2023 07:35:18 -0500 Subject: [PATCH] bus: Change named ranges from hashmap to array Improves performance by 0.4 seconds in unit tests --- justfile | 2 +- src/bus.rs | 14 +++++++++----- src/error.rs | 1 + 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/justfile b/justfile index e807e32..ed178b5 100644 --- a/justfile +++ b/justfile @@ -4,7 +4,7 @@ cover: cargo llvm-cov --open --doctests test: - cargo test --all + cargo test --doc && cargo nextest run tokei: tokei --exclude tests/chip8-test-suite diff --git a/src/bus.rs b/src/bus.rs index 0094f10..b2e4f0f 100644 --- a/src/bus.rs +++ b/src/bus.rs @@ -7,7 +7,6 @@ use crate::error::Result; use std::{ - collections::HashMap, fmt::{Debug, Display, Formatter}, ops::Range, slice::SliceIndex, @@ -49,12 +48,14 @@ pub trait Write { } /// Represents a named region in memory +#[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Region { Charset, Program, Screen, Stack, + Count, } impl Display for Region { @@ -67,6 +68,7 @@ impl Display for Region { Region::Program => "program", Region::Screen => "screen", Region::Stack => "stack", + _ => "", } ) } @@ -76,7 +78,7 @@ impl Display for Region { #[derive(Clone, Debug, Default, PartialEq)] pub struct Bus { memory: Vec, - region: HashMap>, + region: [Option>; Region::Count as usize], } impl Bus { @@ -153,7 +155,9 @@ impl Bus { /// ``` pub fn add_region(mut self, name: Region, range: Range) -> Self { self.with_size(range.end); - self.region.insert(name, range); + if let Some(region) = self.region.get_mut(name as usize) { + *region = Some(range); + } self } /// Loads data into a named region @@ -242,7 +246,7 @@ impl Bus { ///# } /// ``` pub fn get_region(&self, name: Region) -> Option<&[u8]> { - self.get(self.region.get(&name)?.clone()) + self.get(self.region.get(name as usize)?.clone()?) } /// Gets a mutable slice of a named region of memory @@ -257,7 +261,7 @@ impl Bus { ///# } /// ``` pub fn get_region_mut(&mut self, name: Region) -> Option<&mut [u8]> { - self.get_mut(self.region.get(&name)?.clone()) + self.get_mut(self.region.get(name as usize)?.clone()?) } /// Prints the region of memory called `Screen` at 1bpp using box characters diff --git a/src/error.rs b/src/error.rs index 76ba5ef..0bc9e51 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,6 +6,7 @@ use thiserror::Error; pub type Result = std::result::Result; + #[derive(Debug, Error)] pub enum Error { #[error("Unrecognized opcode {word}")]