use cached::macros::concurrent_cached;
use cached::{ConcurrentCached, ShardedCache, ShardedLruCache};
use std::thread;
#[concurrent_cached]
fn compute(x: u64) -> u64 {
x * x
}
#[concurrent_cached(max_size = 128)]
fn compute_lru(x: u64) -> u64 {
x * x
}
#[concurrent_cached(ttl = 60)]
fn compute_ttl(x: u64) -> u64 {
x * x
}
#[concurrent_cached(max_size = 64, ttl = 30)]
fn compute_lru_ttl(x: u64) -> u64 {
x * x
}
#[concurrent_cached(shards = 32)]
fn compute_shards(x: u64) -> u64 {
x * x
}
#[concurrent_cached]
fn load_record(id: u64) -> Result<String, std::io::Error> {
Ok(format!("record_{id}"))
}
#[concurrent_cached]
fn find_record(id: u64) -> Option<String> {
if id == 0 {
None
} else {
Some(format!("record_{id}"))
}
}
fn main() {
let v1 = compute(7);
let v2 = compute(7);
assert_eq!(v1, v2);
assert_eq!(v1, 49);
println!("compute(7) = {v1} (both calls agree)");
let r1 = load_record(42);
let r2 = load_record(42);
assert_eq!(r1.as_deref().expect("infallible"), "record_42");
assert_eq!(r2.as_deref().expect("infallible"), "record_42");
println!("load_record(42) = {:?} (cached)", r1);
assert_eq!(find_record(0), None);
assert_eq!(find_record(0), None); assert_eq!(find_record(1), Some("record_1".to_string()));
println!(
"find_record(0) = None (not cached), find_record(1) = {:?}",
find_record(1)
);
let v = compute_lru(7);
assert_eq!(v, 49);
println!("compute_lru(7) = {v}");
let v = compute_ttl(7);
assert_eq!(v, 49);
println!("compute_ttl(7) = {v}");
let v = compute_lru_ttl(7);
assert_eq!(v, 49);
println!("compute_lru_ttl(7) = {v}");
let v = compute_shards(7);
assert_eq!(v, 49);
println!("compute_shards(7) = {v}");
let handles: Vec<_> = (0..8)
.map(|_| {
thread::spawn(|| {
for i in 0u64..100 {
let _ = compute(i % 10);
}
})
})
.collect();
for h in handles {
h.join().expect("thread panicked");
}
{
let val = COMPUTE.cache_get(&7).expect("infallible");
assert_eq!(val, Some(49));
println!("cache_get(7) = {val:?}");
}
let cache: ShardedCache<u32, String> = ShardedCache::builder().build().unwrap();
cache.cache_set(1, "hello".to_string()).expect("infallible");
cache.cache_set(2, "world".to_string()).expect("infallible");
assert_eq!(
cache.cache_get(&1).expect("infallible").as_deref(),
Some("hello")
);
println!(
"manual ShardedCache: {:?}",
cache.cache_get(&1).expect("infallible")
);
let lru: ShardedLruCache<u32, u32> = ShardedLruCache::builder()
.max_size(256)
.shards(8)
.build()
.expect("valid config");
for i in 0..256u32 {
lru.cache_set(i, i * 2).expect("infallible");
}
println!("ShardedLruCache len = {}", lru.len());
println!("ShardedLruCache shard_sizes = {:?}", lru.shard_sizes());
println!("\ndone!");
}