2 releases
Uses old Rust 2015
0.1.1 | Sep 13, 2018 |
---|---|
0.1.0 | Sep 13, 2018 |
#273 in Caching
9KB
114 lines
Timed Cache
This library is an implementation of a cache that stores its contents by a key, as well as the duration of time that value will remain valid once it has been written to the cache.
If the value is missing when the user tries to retrieve a value from the TimedCache
, or the value has outlived the
specified storage Duration
of the cache, the value will be regenerated using a specified function.
Example:
let cache = TimedCache::with_time_to_keep(Duration::from_seconds(60));
cache.get(&"key".to_owned(), || some_mutexed_service.lock().unwrap().call());
For information, please see the tests and documentation.
Contribution
I am more than willing to have help improving and extending this library. Please leave an issue and/or submit a pull request!
lib.rs
:
Example
The following example is obviously overly simplistic, but gives an idea of how one might use this library. In a real-world application, one might have the generator function call an over-the-network service to get some session key.
extern crate timed_cache;
use timed_cache::TimedCache;
use std::time::Duration;
use std::sync::Mutex;
struct TestService(usize);
impl TestService {
fn next(&mut self) -> usize {
let n = self.0;
self.0 += 1;
n
}
}
let time_to_keep = Duration::from_millis(1);
let mut cache = TimedCache::<String, usize>::with_time_to_keep(time_to_keep);
let service = Mutex::new(TestService(0));
let generate_value = || service.lock().unwrap().next();
(0..1000).for_each(|_| {
// this generator method will
let value = cache.get(&"value".to_owned(), generate_value);
println!("{}", value);
});