2 个版本 (0 个不稳定)
2.0.0-beta | 2023年10月14日 |
---|---|
1.0.0-beta | 2023年8月10日 |
#430 in 进程宏
用于 simpl_cache
8KB
90 行
simple_cache
简单的Rust缓存工具
用法
将此添加到你的 Cargo.toml
[dependencies]
simpl_cache = { version = "2.0.0-beta" }
ttl_cache
宏
此进程宏旨在缓存带有生存时间(TTL)的功能调用。当处理执行昂贵计算且输出不经常变化的函数时,它非常有用。
该宏生成一个静态变量作为缓存,该变量在具有相同名称和输入参数的所有函数调用之间共享。
如果可用的缓存值,则返回缓存值而不是重新计算结果。如果缓存值已过期或使用不同参数调用函数,则将重新计算函数并将新值更新到缓存中。
#[ttl_cache(duration_s = 30)]
fn fibonacci(n: u32) -> u32 {
if n < 2 {
return n;
}
fibonacci(n - 1) + fibonacci(n - 2)
}
fn main() {
println!("first: {}", fibonacci(10)); // cache miss: return value is cached
println!("second: {}", fibonacci(10)); // cached hit: cached value is returned
println!("last: {}", fibonacci(20)); // cache miss: args changed, new result is cached
}
您还可以缓存函数返回的 Ok(T)
变体。
// 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));
}
类似地,您也可以选择只缓存函数返回的 Some(T)
变体。
// 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));
}
注意事项
请注意,only_some
和 only_ok
只能在函数返回 Option<T>
或 Result<T, E>
时使用。您也不能同时设置 only_some
和 only_ok
该宏还将不允许您将其应用于不返回或显式返回单元类型 ()
的函数。例如,以下代码将无法编译
#[ttl_cache(duration_s = 60)]
fn print_hello_world() {
println!("Hello, world!");
}
最后,被注释函数返回的类型必须实现 Clone