cached
Caching structures and simplified function memoization
cached provides implementations of several caching structures as well as a handy macro
for defining memoized functions.
Defining memoized functions using cached!
cached! defined functions will have their results cached using the function's arguments as a key
(or a specific expression when using cached_key!).
When a cached! defined function is called, the function's cache is first checked for an already
computed (and still valid) value before evaluating the function body.
Due to the requirements of storing arguments and return values in a global cache:
- Function return types must be owned and implement
Clone - Function arguments must either be owned and implement
Hash + Eq + CloneOR thecached_key!macro must be used to convert arguments into an owned +Hash + Eq + Clonetype. - Arguments and return values will be
clonedin the process of insertion and retrieval. cached!functions should not be used to produce side-effectual results!
NOTE: Any custom cache that implements cached::Cached can be used with the cached macros in place of the built-ins.
See examples for basic usage and
an example of implementing a custom cache-store.
cached! and cached_key! Usage & Options:
There are several options depending on how explicit you want to be. See below for a full syntax breakdown.
1.) Using the shorthand will use an unbounded cache.
extern crate cached;
extern crate lazy_static;
cached!
2.) Using the full syntax requires specifying the full cache type and providing
an instance of the cache to use. Note that the cache's key-type is a tuple
of the function argument types. If you would like fine grained control over
the key, you can use the cached_key! macro.
For example, a SizedCache (LRU):
extern crate cached;
extern crate lazy_static;
use sleep;
use Duration;
use SizedCache;
cached!
3.) The cached_key macro functions identically, but allows you define the
cache key as an expression.
extern crate cached;
extern crate lazy_static;
use sleep;
use Duration;
use SizedCache;
cached_key!
Syntax
The complete macro syntax is:
cached_key!
Where:
CACHE_NAMEis the unique name used to hold astatic refto the cacheCacheTypeis the full type of the cacheCacheInstanceis any expression that yields an instance ofCacheTypeto be used as the cache-store, followed by;- When using the
cached_key!macro, the "Key" line must be specified. This line must start with the literal tokensKey =, followed by an expression that evaluates to the key, followed by; fn func_name(arg1: arg_type) -> return_typeis the same form as a regular function signature, with the exception that functions with no return value must be explicitly stated (e.g.fn func_name(arg: arg_type) -> ())- The expression following
=is the function body assigned tofunc_name. Note, the function body can make recursive calls to its cached-self (func_name).
License: MIT