Attribute Macro comemo_macros::memoize

source · []
#[memoize]
Expand description

Memoize a function.

Memoized functions can take two kinds of arguments:

  • Hashed: This is the default. These arguments are hashed into a high-quality 128-bit hash, which is used as a cache key. For this to be correct, the hash implementations of your arguments must feed all the information your arguments expose to the hasher. Otherwise, memoized results might get reused invalidly.
  • Tracked: The argument is of the form Tracked<T>. These arguments enjoy fine-grained access tracking and needn’t be exactly the same for a cache hit to occur. They only need to be used equivalently.

You can also add the #[memoize] attribute to methods in inherent and trait impls.

Example

/// Evaluate a `.calc` script.
#[comemo::memoize]
fn evaluate(script: &str, files: comemo::Tracked<Files>) -> i32 {
    script
        .split('+')
        .map(str::trim)
        .map(|part| match part.strip_prefix("eval ") {
            Some(path) => evaluate(&files.read(path), files),
            None => part.parse::<i32>().unwrap(),
        })
        .sum()
}

Restrictions

There are certain restrictions that apply to memoized functions. Most of these are checked by comemo, but some are your responsibility:

  • They must be pure, that is, free of observable side effects. This is your responsibility as comemo can’t check it.
  • They must have an explicit return type.
  • They cannot have mutable parameters (conflicts with purity).
  • They cannot use destructuring patterns in their arguments.