jaemk / cached

Rust cache structures and easy function memoization
MIT License
1.58k stars 95 forks source link

Ability to clear/defeat cache stores #10

Closed linclelinkpart5 closed 6 years ago

linclelinkpart5 commented 6 years ago

I was wondering if there are plans to add functionality to clear caches programatically, or be able to force recomputation/defeat the cache on certain calls?

I'd love to contribute as I can, but I wanted to make sure this fit within the scope of what this crate intends to do. :)

jaemk commented 6 years ago

That's certainly something that could be added in some capacity! Maybe adding a Cached::cache_reset trait method? I'd be a little hesitant to add that logic into the macro though since you could manually grab a lock and mutate the cache from within the cached! function:

cached! {
    WOMP: SizedCache<(u32), u32> = SizedCache::with_size(50);
    fn womp(n: u32) -> u32 = {
        use cached::Cached;
        let mut cache = WOMP.lock().unwrap();
        // this could be resetting instead
        cache.cache_set((1), 1);
        cache.cache_set((2), 2);
        cache.cache_set((3), 3);
        n
    }
}

pub fn main() {
    womp(10);
    {
        use cached::Cached;
        let cache = WOMP.lock().unwrap();
        println!("size=4 -> {:?}", cache.cache_size() == 4);
    }
}
linclelinkpart5 commented 6 years ago

@jaemk I see, is there a way to add that trait method without adding it to the macro invocation? Not sure I understand, I'm unfamiliar with creating custom Rust macros.

jaemk commented 6 years ago

Yes, the trait method could be added here in lib.rs and then implemented for all the stores in stores.rs. The macros wouldn't need to be updated

jaemk commented 6 years ago

added in #14

emirror-de commented 1 year ago

Is there a way to use this functionality in combination with the proc-macro?

jaemk commented 1 year ago

@emirror-de the cache_clear and cache_reset methods are available on cache types. Which macro was used doesn't matter. The proc macros will generate a global identifier either equal to the name argument passed to the macro or equal to the function name uppercased.

use cached::Cached;
use cached::proc_macro::cached;

#[cached]
fn my_func() -> i32 { ... }

#[cached(name = "MY_FUNC_2")]
fn my_funky_func() -> i32 { ... }

{
    MY_FUNC.lock().unwrap().cache_reset()
    MY_FUNC_2.lock().unwrap().cache_reset()
}
emirror-de commented 1 year ago

Awesome! Thank you!