#cache #macro #proc-macro #ttl-cache

simple_cache_macros

简单的Rust缓存工具

7个版本 (0个不稳定)

2.4.1-beta2024年3月20日
2.4.0-beta2023年11月14日
2.3.0-beta2023年10月16日
1.0.0-beta2023年8月10日

#1239 in 过程宏

每月30次下载
simpl_cache 中使用

MIT 许可证

13KB
192 代码行

simpl_cache

简单的Rust缓存工具

用法

将此添加到您的 Cargo.toml

[dependencies]
simpl_cache = "2.4.1-beta"

ttl_cache

此进程宏旨在缓存具有生存时间(TTL)的函数调用。当处理执行昂贵的计算且输出不经常变化的函数时非常有用。

该宏生成一个静态变量,用于缓存,并在具有相同名称和输入参数的所有函数调用之间共享。

如果缓存值可用,则返回该值而不是重新计算结果。如果缓存值已过期或以不同的参数调用函数,则将重新计算函数,并将新值更新到缓存中。

use simpl_cache::ttl_cache;

#[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) 变体。

use simpl_cache::ttl_cache;

// 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) 变体。

use simpl_cache::ttl_cache;

// 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));

}

注意

首先,这仍然是一个正在进行中的工作,因此不建议在生产环境中使用它。

⚠️ 宏对于与结构体和枚举方法一起使用不稳定,特别是那些具有 self 参数的方法。 ⚠️

请注意,只有当被注解的函数返回 Option<T>Result<T, E> 时,才能使用 only_someonly_ok。您也不能同时设置 only_someonly_ok

该宏也不会允许您将其应用于不返回或显式返回单位类型 () 的函数。例如,以下代码将无法编译:

use simpl_cache::ttl_cache;

#[ttl_cache(duration_s = 60)]
fn print_hello_world() {
    println!("Hello, world!");
}

最后,被注解函数返回的类型必须实现 Clone

依赖项

~1.3–2MB
~39K SLoC