From 2202a42705337d361e2f389f28dc72ece6b9b518 Mon Sep 17 00:00:00 2001 From: Bearmine Date: Mon, 16 Jun 2025 12:07:23 -0500 Subject: [PATCH] Encapsulate cache locking code --- day_07/src/equation/operator_set.rs | 31 ++++++++++++++++++----------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/day_07/src/equation/operator_set.rs b/day_07/src/equation/operator_set.rs index c291157..4e59fde 100644 --- a/day_07/src/equation/operator_set.rs +++ b/day_07/src/equation/operator_set.rs @@ -7,6 +7,17 @@ type OperatorCache = HashMap>>; static OPERATOR_SET_CACHE: LazyLock> = LazyLock::new(|| Mutex::new(HashMap::new())); +fn check_operator_set_cache(cache_key: usize) -> Option>> { + OPERATOR_SET_CACHE.lock().unwrap().get(&cache_key).cloned() +} + +fn store_operator_set_in_cache(cache_key: usize, cache_value: HashSet>) { + OPERATOR_SET_CACHE + .lock() + .unwrap() + .insert(cache_key, cache_value); +} + fn create_operator_set_recurse( operators_permutation_set: &mut HashSet>, operators: Vec, @@ -27,20 +38,16 @@ fn create_operator_set_recurse( } pub fn create_operator_set(num_of_operators: usize) -> HashSet> { - { - // Check cache - if let Some(cached_value) = OPERATOR_SET_CACHE.lock().unwrap().get(&num_of_operators) { - return cached_value.clone(); - } + // Check cache + if let Some(cached_value) = check_operator_set_cache(num_of_operators) { + return cached_value.clone(); } + let mut operator_sets: HashSet> = HashSet::new(); create_operator_set_recurse(&mut operator_sets, vec![false; num_of_operators]); - { - // Store value in cache - OPERATOR_SET_CACHE - .lock() - .unwrap() - .insert(num_of_operators, operator_sets.clone()); - } + + // Store value in cache + store_operator_set_in_cache(num_of_operators, operator_sets.clone()); + operator_sets }