Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Simplifying this data structure: Rc

$
0
0

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>:

  1. "real" (but lazy) copies, which when modified will not affect the original Vec<T> and will also not be affected when the original Vec<T> is modified.
  2. mutable views, which will allow to mutate the original Vec<T> stored in the HashMap 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 original Vec<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 RefCells.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

  1. I am not (yet) in a multi-threaded scenario, so I don't need to worry about this for now.
  2. 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 and x2 real copies and x3 a mutable view, they should in the beginning all have the same Vec<T>. When I write into x3, this should then only modify the content of x and x2, but not x1 and x2, which should still contain the same Vec<T>.
  3. There will only be one mutable view at a time.

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>