I have some data Vec<T>
that is stored -- wrapped in some data structure -- in a HashMap
.From this HashMap
, I want to retrieve two types of copies of this Vec<T>
:
- "real" (but lazy) copies, which when modified will not affect the original
Vec<T>
and will also not be affected when the originalVec<T>
is modified. - mutable views, which will allow to mutate the original
Vec<T>
stored in theHashMap
but which will not modify all the "real" copies. (There will be at most exactly one such mutable view, but it is necessary to be able to create more real copies in the presence of such a mutable view). I don't have to worry what happens when the originalVec<T>
is modified when I have such a mutable view, as this cannot happen. Also, there will only be one such mutable view.
The data structure I came up with is a Rc<RefCell<Rc<Vec<T>>>
.To create real copies, I can clone the inner Rc and wrap it into a new outer Rc<RefCell<...>>
, giving it its own RefCell
. To create the mutable copies, I can just clone the outer Rc
, which will share RefCell
s.Modifying the content of the Vec<T>
can then always be achieved by using RefCell::replace_with()
.
I think this achieves what I want, but what I don't like about this solution is that it is a rather complex data structure and I was wondering whether this can also be achieved using a simpler solution?
Why I cannot use Rc<Vec<T>>
(I think):
Just relying on an Rc<Vec<T>>
almost does what I want, and I would love to just use this data structure for simplicity. The problem is, however, that when I create a &mut T
using make_mut()
, no other real copies can be created from the Rc<Vec<T>>
.
Edit:
I think I did not specify what I want here explicitly enough, so I am now trying to give more information
- I am not (yet) in a multi-threaded scenario, so I don't need to worry about this for now.
- I want the "real" copies do be done lazily, i.e. only once they are modified, they will create a copy of the data. But their data should not be modified when a mutable view is modified. E.g. if
x
is the original vector,x1
andx2
real copies andx3
a mutable view, they should in the beginning all have the sameVec<T>
. When I write intox3
, this should then only modify the content ofx
andx2
, but notx1
andx2
, which should still contain the sameVec<T>
. - There will only be one mutable view at a time.