I want to model a very large (number of nodes) graph consisting of many very large (memory-wise) nodes. Since the nodes are so large, I would like to only store them once and pass around borrows to them, so conceptually something like this:
struct Graph<'a> {
nodes: Vec<Node<'a>>,
}
struct Node<'a> {
edges: HashMap<String, &'a Node>,
// ...lots of other data...
}
Of course there is no way to construct a Graph
like this because (a) Vec
does not allow me to add new nodes when there are borrows to the elements, and (b) I can't tell rustc that the nodes
vector will live for lifetime 'a
. I can also not use something like Rc
because the graph has cycles.
What I would like to be able to express is an arena of sorts, which lets me allocate a lot of Node
s, make immutable borrows to them as long as the arena lives, and use lifetime checks to ensure that I have no remaining Node
references out when the arena is de-allocated. Something like:
struct Graph<'a> {
nodes: Arena<'a, Node<'a>>,
}
struct Node<'a> {
edges: HashMap<String, &'a Node>,
}
impl<'a, A> Arena<'a, A> {
fn own(&self, a: A) -> &'a A {
// magic
}
}
impl<'a, A> Drop for Arena<'a, A> {
fn drop(&'a mut self) {
// magic
}
}
Is this semantically possible to express in Rust?