changeset 46:e68eee272bb3

Make memoize work for recursive functions by removing deadlock Fixes #3
author Lewin Bormann <lbo@spheniscida.de>
date Wed, 16 Dec 2020 08:18:49 +0100
parents b1f617a45289
children 3ed9875b9139
files src/lib.rs
diffstat 1 files changed, 19 insertions(+), 10 deletions(-) [+]
line wrap: on
line diff
--- a/src/lib.rs	Thu Dec 10 20:39:29 2020 +0100
+++ b/src/lib.rs	Wed Dec 16 08:18:49 2020 +0100
@@ -244,24 +244,30 @@
         match options.time_to_live {
             None => quote::quote! {
                 #sig {
-                    let mut hm = &mut #store_ident.lock().unwrap();
-                    if let Some(r) = hm.#get_fn(&#syntax_names_tuple_cloned) {
-                        return r.clone();
+                    {
+                        let mut hm = &mut #store_ident.lock().unwrap();
+                        if let Some(r) = hm.#get_fn(&#syntax_names_tuple_cloned) {
+                            return r.clone();
+                        }
                     }
                     let r = #memoized_id(#(#input_names.clone()),*);
+                    let mut hm = &mut #store_ident.lock().unwrap();
                     hm.#insert_fn(#syntax_names_tuple, r.clone());
                     r
                 }
             },
             Some(ttl) => quote::quote! {
                 #sig {
-                    let mut hm = &mut #store_ident.lock().unwrap();
-                    if let Some((last_updated, r)) = hm.#get_fn(&#syntax_names_tuple_cloned) {
-                        if last_updated.elapsed() < #ttl {
-                            return r.clone();
+                    {
+                        let mut hm = &mut #store_ident.lock().unwrap();
+                        if let Some((last_updated, r)) = hm.#get_fn(&#syntax_names_tuple_cloned) {
+                            if last_updated.elapsed() < #ttl {
+                                return r.clone();
+                            }
                         }
                     }
                     let r = #memoized_id(#(#input_names.clone()),*);
+                    let mut hm = &mut #store_ident.lock().unwrap();
                     hm.#insert_fn(#syntax_names_tuple, (std::time::Instant::now(), r.clone()));
                     r
                 }
@@ -271,11 +277,14 @@
     #[cfg(not(feature = "full"))]
     let memoizer = quote::quote! {
         #sig {
-            let mut hm = &mut #store_ident.lock().unwrap();
-            if let Some(r) = hm.#get_fn(&#syntax_names_tuple_cloned) {
-                return r.clone();
+            {
+                let mut hm = &mut #store_ident.lock().unwrap();
+                if let Some(r) = hm.#get_fn(&#syntax_names_tuple_cloned) {
+                    return r.clone();
+                }
             }
             let r = #memoized_id(#(#input_names.clone()),*);
+            let mut hm = &mut #store_ident.lock().unwrap();
             hm.#insert_fn(#syntax_names_tuple, r.clone());
             r
         }