#cache #mutation #version #invalidation

versioned

Provides a pointer-like wrapper for counting mutations

1 unstable release

0.1.0 Aug 29, 2020

#261 in Caching

MIT/Apache

13KB
157 lines

docs.rs Build Status

versioned

This tiny crate provides just the pointer-like Versioned<T> wrapper, which counts the number of times its contained T value has been mutably accessed.

This may be useful when caching certain calculation results based on objects, which are expensive to compare or hash, such as large collections. In such cases it might be more convenient to store object version and later check if it changed.

use versioned::Versioned;

let mut versioned_value = Versioned::new("Hello".to_string());

assert_eq!(versioned_value.version(), 0, "version is 0 initially");

// This is an immutable dereference, so it won't change the version.
let value_len = versioned_value.len();

assert_eq!(versioned_value.version(), 0, "version is unchanged after immutable access");

// Now we mutate the value twice.
versioned_value.push_str(" ");
versioned_value.push_str("World!");

assert_eq!(*versioned_value, "Hello World!");
assert_eq!(versioned_value.version(), 2, "version got incremented once per mutable access");

Versioned<T> implements Deref, AsRef and their Mut counterparts. In particular, due to Deref coercion, Versioned<T> values can be passed as &T and &mut T parameters to functions:

use versioned::Versioned;

fn look_at(value: &String) {}
fn modify(value: &mut String) {}

let mut versioned_value = Versioned::new("blabla".to_string());

look_at(&versioned_value);
assert_eq!(versioned_value.version(), 0);

modify(&mut versioned_value);
assert_eq!(versioned_value.version(), 1, "version increased due to mutable dereference");

Note from the example above that, since mutations are counted based on mutable dereferences, version got increased on mutable dereference in the call to modify(), even though ultimately no mutation of the value itself took place.

No runtime deps