Open T0mstone opened 1 year ago
This could be unsound as there is nothing to stop you borrowing the same cell twice mutably.
It IS sound to do multiple mutable borrows using the same owner, but that requires cross-checking that no two of them refer to the same memory. This is convenient to check if the caller presents all of them at the same time which is what rw2()
and rw3()
methods do. To do something more dynamic like what you're proposing would mean building up a list of memory addresses already borrowed and checking new borrows against that. Is this going to be any more efficient than your workarounds?
Alternatively perhaps once you know you're looking at two TCells, you could drop the borrow on the first and then use rw2
to get borrows on both of them at the same time.
Okay, I think I can see what you're saying now. Since rw_nested
knows the address of both cells, it can do the cross-check. It seems like quite a specific case, but valid. I wonder whether it can be generalized in some way. I will think about it.
I have an idea. It would go something like: let (borrow1, chain) = owner.rw_chain(&tcell); let borrow2 = chain.rw(&borrow1.tcell);
. I think I can let people chain borrows indefinitely, although it has to do an O(N) scan down the chain each time a new borrow is added. But it may panic if two TCells turn out to be the same one. So I think I also need try_rw
and try_rw_chain
so that those cases can be handled in the caller. I will have a go later on.
My usecase is in a programming language, for type-inferring. I have type variables in
Rc<TCell<>>
, such that multiple places can share their inferred type automatically. The problem is that a type can contain another type variable (that might not be known yet), so I have some situations where I would effectively need to get the innermost value (mutably) out of aRc<TCell<Rc<TCell<_>>>>
. I have some workarounds for this, but they are all limiting in some way.I think the nested access pattern should be possible for all the cells, since the owner is borrowed mutably and so no other accesses can happen simultaneously. Is my reasoning wrong? If not, it would be great if we could get a function like
On a related note, we could also introduce a lower-level,
UnsafeCell
-like unsafe API to get pointers without having the owner. This would allow one to implement the above function oneself, by using the fact that the owner is borrowed mutably to fulfill the safety conditions of, say,(This should then also exist for all the cells)