clone_cell
clone_cell provides a Cell implementation that works with types whose Clone
implementations are guaranteed not to mutate the Cell content through the &self
reference. This is enforced with the provided PureClone trait, which is a subtrait
of Clone (and a logical supertrait of Copy). It is only implemented for types
with compliant clone methods.
Overview
The Cell implementation provided by this crate is intended to be a drop-in
replacement of std::cell::Cell. It can work with types that behave like values,
such as Rc<T>, Weak<T> (shared pointers themselves are like values; it is the
pointees that behave like references), Option<T: PureClone>, and more. Some
motivating use cases include implementing the observer pattern and combining Cell
with clone-on-write or immutable collections to enable efficient sharing of data
structures.
PureClone is currently implemented for the following types:
- All primitives such as
i32,usize,f64, etc; Rc<T>andWeak<T>;Option<T: PureClone>; and- Tuples:
(A: PureClone, ...).
See PureClone for a complete list.
Examples
In this example below, we store an Rc<T> in a Cell and later retrieve a copy of it.
let x = new;
x.set;
assert_eq!;
See the documentation for Cell for more.
Limitations
- Similar to
std::cell::Cell, thisCellis!Sync. PureCloneis currently only implemented for some types from the standard library. I hope to support user types as well with a proc macro so that one can automatically derivePureClonefor types when they only contain fields that arePureClone:// Not supported yet! let f = new; f.set; assert_eq!;
Soundness
I believe this is sound, because PureClone is unsafe to implement. This trait is implemented for:
Copytypes;- Types that perform a shallow clone such as
RcandWeak; and - Types whose
clonemethods are otherwise known to be safe, such as compound types that only containPureClonetypes.
See the documentation for more information. Please let me know if you find any soundness issues!
Contributing
Pull requests are welcome and any feedback is appreciated!