jaemk / cached

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

Feature Request: A cache where the value knows how to determine whether it is expired #115

Open absoludity opened 2 years ago

absoludity commented 2 years ago

Thanks for the great library. I've been using cached today to cache authentication tokens which know their own expiry and have a solution that may or may not be best here as a separate cache in src/stores/expired_value_cache.rs or similar.

It works by defining a CanExpire trait:

pub trait CanExpire {
    fn is_expired(&self) -> bool;
}

then implements your Cached trait with the CanExpire restriction on the value:

impl<K: Hash + Eq, V: CanExpire> Cached<K, V> for ExpiredValueCache<K, V> {...}

You can see the full details in the PR at https://github.com/vmware-tanzu/kubeapps/pull/4899/files

Let me know if this is something that you'd like in the repo here and I'll create a PR and update it so the code follows the patterns/structure that I see in the timed.rs implementation. Or if I've missed something and this functionality is already available with what's there, let me know :)

Thanks!

jaemk commented 2 years ago

Nice, definitely would love a PR to add this functionality!