From dcc1475a58acc83aa180f7d202bf069e214980ee Mon Sep 17 00:00:00 2001 From: HampusM Date: Thu, 17 Oct 2024 01:01:22 +0200 Subject: perf(engine): pre-populate key map --- engine/src/input.rs | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) (limited to 'engine/src') diff --git a/engine/src/input.rs b/engine/src/input.rs index c8ba16a..e292b76 100644 --- a/engine/src/input.rs +++ b/engine/src/input.rs @@ -15,7 +15,7 @@ mod reexports pub use reexports::*; -#[derive(Debug, Clone, Default, Sole)] +#[derive(Debug, Clone, Sole)] pub struct Keys { map: HashMap, @@ -26,33 +26,45 @@ impl Keys #[must_use] pub fn new() -> Self { - Self::default() + Self { + map: Key::KEYS + .iter() + .map(|key| (*key, KeyState::Released)) + .collect(), + } } #[must_use] pub fn get_key_state(&self, key: Key) -> KeyState { - self.map.get(&key).copied().unwrap_or(KeyState::Released) + self.map.get(&key).copied().expect("Key not in key map") } - pub fn set_key_state(&mut self, key: Key, key_state: KeyState) + pub fn set_key_state(&mut self, key: Key, new_key_state: KeyState) { - if matches!(key_state, KeyState::Released) { - self.map.remove(&key); + if matches!(new_key_state, KeyState::Repeat) { return; } - if matches!(key_state, KeyState::Repeat) { - return; - } + let key_state = self.map.get_mut(&key).expect("Key not in key map"); - self.map.insert(key, key_state); + *key_state = new_key_state; } #[must_use] pub fn is_anything_pressed(&self) -> bool { - !self.map.is_empty() + self.map + .values() + .any(|key_state| matches!(key_state, KeyState::Pressed)) + } +} + +impl Default for Keys +{ + fn default() -> Self + { + Self::new() } } -- cgit v1.2.3-18-g5258