From d89eda68d7311b9b57c71e9d58617d3fa93b51b8 Mon Sep 17 00:00:00 2001 From: zleyyij Date: Fri, 26 Jan 2024 13:14:37 -0700 Subject: [PATCH] feat: added caching for cpu name translations --- src/cpu.rs | 18 ++++++++++++++---- src/main.rs | 2 +- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/cpu.rs b/src/cpu.rs index 6430d07..64c91b8 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -22,9 +22,11 @@ pub struct Cpu { pub struct CpuCache { intel_cpus: Vec, amd_cpus: Vec, + comparison_cache: HashMap, } impl CpuCache { + /// Create a new cache and parse the cpu databases into memory pub fn new() -> Self { let intel_cpus = get_intel_cpus(); @@ -35,13 +37,16 @@ impl CpuCache { Self { intel_cpus, amd_cpus, + comparison_cache: HashMap::new(), } } /// Given a string that contains the inexact name of a cpu, try to find the best fit /// and return it. For example, it might take an input of "AMD Ryzen 5 3600 6-Core Processor", - /// and return the entry with a `name` of "AMD Ryzen™ 5 3600" - pub fn find(&self, input: &str) -> Cpu { + /// and return the entry with a `name` of "AMD Ryzen™ 5 3600". + /// + /// A mutable reference is required so that the comparison cache can be shared between calls + pub fn find(&mut self, input: &str) -> Cpu { let input_model = find_model(input); // a list of CPUs, and the most likely let cpus = if input.contains("AMD") { @@ -49,7 +54,11 @@ impl CpuCache { } else { &self.intel_cpus }; - + // first see if a comparison has already been made + if let Some(cpu_name) = self.comparison_cache.get(input) { + return cpus.into_iter().filter(|cpu| cpu.name == cpu_name.to_string()).nth(0).unwrap().clone() + } + // performing a full search if the cpu isn't found in the cache let mut best_fit = Cpu { name: "FUBAR".to_string(), attributes: HashMap::new(), @@ -65,6 +74,7 @@ impl CpuCache { best_fit = cpu.clone(); } } + self.comparison_cache.insert(input.to_string(), best_fit.name.clone()); debug!( "Given the input: {:?}, the CPU {:?} was found", input, best_fit.name @@ -115,7 +125,7 @@ mod tests { #[test] fn search_resilience() { - let cache = CpuCache::new(); + let mut cache = CpuCache::new(); // on the left is the name stored in the cache, on the right is the name collected from WMI data // these test cases should be filled out as time goes on with failing test cases // any test cases commented out currently fail diff --git a/src/main.rs b/src/main.rs index bb5a371..0fcd83c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -63,7 +63,7 @@ struct CpuQuery { /// It will always attempt to find a cpu, and should always return a cpu. The correctness of the return value is not guaranteed. async fn get_cpu_handler(State(state): State, Json(query): Json) -> Json { // just to get type annotations working - let state: AppState = state; + let mut state: AppState = state; Json(state.cpu_cache.find(&query.name)) }