New Changes
ttl_cache
now expects a duration_s
argument to explicitly state the cache duration
- Added a
only_ok
argument to limit caching to Ok(T)
variants from a function returning a Result<T, E>
(#1)
- Added a
only_some
argument to limit caching to Some(T)
variants of an Option<T>
(#1)
Examples
// only_ok option ensures that only .is_ok values from the returning Result are cached
#[ttl_cache(duration_s = 30, only_ok = true)]
fn some_fallible_function(n: u32) -> Result<u32, String> {
if n == 0 {
return Err(String::from("zeros are not allowed"))
}
Ok(n)
}
fn main() {
// zero is not cached since function returns an Err since n == 0
println!("last: {}", some_fallible_function(0));
// cache miss: 10 is cached since the result is_ok
println!("last: {}", some_fallible_function(10));
// cache hit: 10 is retrieved from the cache
println!("last: {}", some_fallible_function(10));
}
// only_some option ensures that only .is_some values from the returning Option are cached
#[ttl_cache(duration_s = 30, only_some = true)]
fn some_optional_function(n: u32) -> Option<u32> {
if n == 0 {
return None;
}
Some(n)
}
fn main() {
// zero is not cached since function returns None since n == 0
println!("last: {}", some_optional_function(0));
// cache miss: 10 is cached since the result is_some
println!("last: {}", some_optional_function(10));
// cache hit: 10 is retrieved from the cache
println!("last: {}", some_optional_function(10));
}