A simple safe Rust library to cache functions (or sections of code) in memory, mainly ported from my Python module SimpleCache.
git clone https://github.com/Cyclip/rust_caching/
rust_caching
dependency into Cargo.toml
: [dependencies] rustcaching = {path = "rustcaching"} ```
Here's a demo which caches an expensive function to calculate the number of possible steps to a specific stair; assuming you can only take up to 3: ```rust extern crate rustcaching; use rustcaching::*;
fn stepsto(cache: &mut MemCache, stair: u128) -> u128 {
// check the cache
variable with input arguments stair
,
// with an output type u128
checkcache!(cache, args!(stair), u128, {
// If it isn't cached, it will run this block of code
// and cache it afterwards automatically.
match stair {
1 => { 1 },
2 => { 2 },
3 => { 4 },
_ => {
stepsto(cache, stair - 3)
+ stepsto(cache, stair - 2)
+ steps_to(cache, stair - 1)
}
}})
}
fn main() { // stair = 36 would take about 10 seconds // as stair increases, the time taken expotentially increases let mut cache = MemCache::new(100); // create a new memory cache struct let stair = 120u128;
let result = steps_to(&mut cache, stair);
println!("Steps to {}: {}", stair, result);
println!("Cache size: {}", cache.size());
} ```
The args!
macro converts a group of arguments into a hashed ID which will then be compared with in the future.
The check_cache!
macro takes in the cache struct, input arguments, output type and a block of code to cache and handles it for you.
rust_caching is licensed with the MIT License and is created by Cyclip