1个不稳定版本
使用旧的Rust 2015
0.1.0 | 2018年6月15日 |
---|
#275 in 缓存
25KB
288 行
简单的缓存库
core_memo
是一个简单、直接、零成本的Rust缓存库,用于懒加载和缓存。它不进行内存分配或动态分发,且与 #![no_std]
兼容。它没有依赖项。
示例
use core_memo::{Memoize, Memo, MemoExt};
#[derive(Debug, PartialEq, Eq)] // for assert_eq! later
struct MemoSum(i32);
impl Memoize for MemoSum {
type Param = [i32];
fn memoize(p: &[i32]) -> MemoSum {
MemoSum(p.iter().sum())
}
}
// The `Memo` type holds ownership over the parameter for the calculation
// There are also the `MemoExt` and `MemoOnce` types with different semantics
let mut memo: Memo<MemoSum, _> = Memo::new(vec![1, 2]);
// Our `memoize` method is called the first time we call `memo.get()`
assert_eq!(memo.get(), &MemoSum(3));
// Further calls to `memo.get()` return the cached value without reevaluating
assert_eq!(memo.get(), &MemoSum(3));
// We can mutate the parameter held inside the `Memo`:
// via a mutable reference
memo.param_mut().push(3);
// via a closure
memo.update_param(|p| p.push(4));
// either way, the `Memo` forgets any cached value and it will be
// reevaluated on the next call to `memo.get()`
assert_eq!(memo.get(), &MemoSum(10)); // the vec is now `[1, 2, 3, 4]`