Statically checked interior mutability

I was thinking of ways to minimize runtime state-tracking for Cell-like containers. One option uses a closure with special constraints: it must not capture another Cell object, therefore making it legal to mutably borrow Cell's interiors.

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=7ffa974084dcd19949e7421421e89483

  1. Am I missing some weird corner case that makes it unsound?

  2. Is this too specific? Nightly Cell already has update() for Copy types, but it doesn't require a single-use trait for it to work.

This can be extended in two ways:

a. Add a marker trait InteriorMutability and implement TransactionSafe for & !InteriorMutability rather than for &Cell specifically. This allows adding transact-like apis for custom data types, but at the cost of another super-specialized feature.

b. Make it so a closure is TransactionSafe as long as it does not capture an object of the same type as current Cell instead of forbidding any interior mutability altogether. I think this is possible, but my brain kinda gave up.

I wouldn't call capturing Rc<Cell> a "weird corner case", but that can be fixed. Thread locals are the really problematic "corner case".

Cell::update is nothing fancy. Look at its implementation [edit: I meant to put this link], its just a combination of Cell::set and Cell::get.

I feel like there was some previous discussion in the past with similar ideas somewhere here or in the users forum, but I can't find it right now.

You might like the types that the qcell crate has to offer, in particular the type or marker-lifetime based TCell, LCell and TLCell.

3 Likes

Eh, I thought I could get away with only implementing !TransactionSafe for &Cell.

Having to account for statics is actually unfortunate. It can be worked around, but that would be too ugly for std. Lame.

qcell gets cumbersome for stuff like side-effects in chained combinators. RefCell works, but getting rid of any overhead in certain cases would be nice for gestalt purposes.

I discussed interior mutability in

If you have something interesting to add to the discussion, I can ask a moderator to unlock the thread, again.

This is not statically checked, nor 0 overhead, but is an interesting point in the design space of ergonomic Cell abstractions: GitHub - nikomatsakis/mutable: Tinkering with a more ergonomic cell abstraction