| Crates.io | fncache |
| lib.rs | fncache |
| version | 0.1.2 |
| created_at | 2025-08-17 19:06:08.547346+00 |
| updated_at | 2025-08-24 15:37:35.554224+00 |
| description | A zero-boilerplate Rust library for function-level caching with pluggable backends |
| homepage | |
| repository | https://github.com/kumarlokesh/fncache |
| max_upload_size | |
| id | 1799648 |
| size | 316,572 |
A zero-boilerplate Rust library for function-level caching with pluggable backends, inspired by functools.lru_cache and request-cache.
#[fncache] attribute for instant cachingAdd fncache to your Cargo.toml with the desired features:
[dependencies]
fncache = { version = "0.1.1", features = ["memory"] }
tokio = { version = "1", features = ["full"] }
futures = "0.3"
use fncache::{
backends::memory::MemoryBackend,
init_global_cache,
fncache,
Result,
};
use std::time::Instant;
#[fncache(ttl = 60)]
fn expensive_operation(x: u64) -> u64 {
println!("Performing expensive operation for {}", x);
std::thread::sleep(std::time::Duration::from_secs(1));
x * x
}
#[tokio::main]
async fn main() -> Result<()> {
// Initialize with memory backend
init_global_cache(MemoryBackend::new())?;
// First call executes the function
let t1 = Instant::now();
let result1 = expensive_operation(5);
let d1 = t1.elapsed();
println!("Result 1: {} (took {:?})", result1, d1); // ~1s
// Second call returns cached result
let t2 = Instant::now();
let result2 = expensive_operation(5);
let d2 = t2.elapsed();
println!("Result 2: {} (took {:?})", result2, d2); // microseconds
Ok(())
}
Note: The first call performs the real work (~1s here). Subsequent calls with the same arguments return the cached result in microseconds.
use std::time::Duration;
use tokio::time::sleep;
#[fncache(ttl = 300)]
async fn fetch_data(id: &str) -> String {
println!("Fetching data for {}", id);
sleep(Duration::from_secs(1)).await;
format!("Data for {}", id)
}
Memory backend: see examples/backend_memory.rs
cargo run --example backend_memoryFile backend: see examples/backend_file.rs
cargo run --example backend_file --features file-backendRedis backend: see examples/backend_redis.rs
redis://127.0.0.1:6379cargo run --example backend_redis --features redis-backend| Feature | Description | Default |
|---|---|---|
memory |
In-memory cache backend | ✅ |
redis-backend |
Redis backend support | ❌ |
file-backend |
File-based persistent cache | ❌ |
rocksdb-backend |
RocksDB high-performance backend | ❌ |
metrics |
Performance metrics collection | ✅ |
invalidation |
Tag-based cache invalidation | ✅ |
tokio only if you use async cached functions or run async examplesSee benches/ for detailed benchmarks.
See CHANGELOG.md for version history and breaking changes.
MIT License - see LICENSE for details.