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.
```rust use versioned::Versioned;
let mut versionedvalue = Versioned::new("Hello".tostring());
asserteq!(versionedvalue.version(), 0, "version is 0 initially");
// This is an immutable dereference, so it won't change the version. let valuelen = versionedvalue.len();
asserteq!(versionedvalue.version(), 0, "version is unchanged after immutable access");
// Now we mutate the value twice. versionedvalue.pushstr(" "); versionedvalue.pushstr("World!");
asserteq!(*versionedvalue, "Hello World!"); asserteq!(versionedvalue.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:
```rust
use versioned::Versioned;
fn look_at(value: &String) {} fn modify(value: &mut String) {}
let mut versionedvalue = Versioned::new("blabla".tostring());
lookat(&versionedvalue); asserteq!(versionedvalue.version(), 0);
modify(&mut versionedvalue);
asserteq!(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.