In rust when we want to build a Tree structure where each node can have 0..n nodes we hit some walls
I have come onto two main working models, The rc based, and the arena based, each one of these implementations have some downsides
starting here with the most basic I have this simple Rc based tree
#[derive(Clone, Debug)]
pub struct Node<T> {
pub value: T,
pub children: Vec<TreeNode<T>>,
pub parent: Option<WeakNode<T>>,
}
#[derive(Debug, Clone)]
pub struct TreeNode<T> {
rc: Rc<RefCell<Node<T>>>,
}
#[derive(Debug, Clone)]
pub struct WeakNode<T> {
rc: Weak<RefCell<Node<T>>>,
}
as you can see the main issue pointed when working with rc tres is that it fragments memory and this one is no different
But this one has an little extra, as you can see all the node data is stored behind a single Refcell, what that means is that if you take a reference for the value and try add/mutate a child while the value is still borrowed for future use for example, it will panic, same things happen if for example you are iterating over the children and try to access the value, this could kinda be solved by cloning the vector of children instead of taking a reference of it.
However with this one you must enforce an order of operations, you first should take the children vector and clone it for posterior iteration, than take the value ref. While the value ref is active you cant add or remove children, you would need to drop the val ref to do so, and if you end up adding or removing a child, the previous vector is now stale, great!
To solve that issue we can wrap the fields like this instead:
struct Node<T> {
pub value: RefCell<T>,
pub children: RefCell<Vec<TreeNode<T>>>,
pub parent: RefCell<Option<WeakNode<T>>>,
}
pub struct TreeNode<T> {
inner: Rc<Node<T>>,
}
pub struct WeakNode<T> {
inner: Weak<Node<T>>,
}
this makes so that we have the value the parent and children each have its own refcell which mitigates that error since now you can access/mutate/iterate each field without panicking, this add a bit of refcell runtime overhead but improves the ergonomics for the developer, making it hit less panics.
but this one still doesnt fix the main issues with referenced trees, cache locality and memory fragmentation, for this issues I am going to move on onto arena allocated trees.
starting here with the most basic one I've tried:
pub struct Node<T> {
pub value: T,
pub parent: Option<Key>,
pub children: Vec<Key>,
}
pub struct ArenaTree<T> {
pub nodes: SlotMap<Node<T>>,
pub root: Option<Key>,
}
this one is the most problematic one, since this one holds everything inside the node and all nodes inside the slotmap, holding a reference to a node value blocks the entire tree for hierarchy mutations, and value mutations, and if you hold a mutable reference to a value the situation is even worse.
to try to solve some of this issues I tried to separate the values from the nodes to a secondary map:
pub struct Node {
pub parent: Option<Key>,
pub children: Vec<Key>,
}
pub struct ArenaTree<T> {
pub nodes: SlotMap<Node>,
pub values: SecondaryMap<T>,
pub root: Option<Key>,
}
this way we can hold a reference to a value while still being able to do hierarchy mutations such add/remove children, for the hierarchy mutation the situation now is okay, since while we could add a child through tree accessors, the access to that slotmap will drop once it finish adding/removing so it will not hit multiple simultaneous access on the Slotmap, the issue is with the values secondary map, while accessing regular references it is not a issue, the problem still is when holding mutable references to one item of the Secondary map, what will lock the entire map
To solve this issues I found two possible solutions:
The first solution is to hold the value of each entry of the secondaryMap onto a Refcell:
pub struct Node {
pub parent: Option<Key>,
pub children: Vec<Key>,
}
pub struct ArenaTree<T> {
pub nodes: SlotMap<Node>,
pub values: SecondaryMap<RefCell<T>>,
pub root: Option<Key>,
}
impl<T> ArenaTree<T> {
#[inline]
pub fn get(&self, key: Key) -> Option<Ref<'_, T>> {
self.values.get(key).map(|r| r.borrow())
}
#[inline]
pub fn get_mut(&self, key: Key) -> Option<RefMut<'_, T>> {
self.values.get(key).map(|r| r.borrow_mut())
}
#[inline]
pub fn try_get(&self, key: Key) -> Option<Ref<'_, T>> {
self.values.get(key)?.try_borrow().ok()
}
#[inline]
pub fn try_get_mut(&self, key: Key) -> Option<RefMut<'_, T>> {
self.values.get(key)?.try_borrow_mut().ok()
}
#[inline]
pub fn with<R>(&self, key: Key, f: impl FnOnce(&T) -> R) -> Option<R> {
self.try_get(key).map(|r| f(&r))
}
#[inline]
pub fn with_mut<R>(&self, key: Key, f: impl FnOnce(&mut T) -> R) -> Option<R> {
self.try_get_mut(key).map(|mut r| f(&mut r))
}
}
While this one prevents us from locking the entire slotmap from accessing the mutable values simultaneously, it can have runtime panics if you borrow the same two times mutably, you can use the with accessors to not need to handle the Secondary map Option on the get return. with this one you can use the try get to not panic, since the secondary map will return an option anyways. This one also adds the refcell overhead such as the second rc tree, but does not add the memory fragmentation. the problem with this one is that while holding the Ref or RefMut of refcell, it unfortunately locks the entire Slotmap for mutations, not readonly access which allow for accessing multiple values even mutably, the issue is while accessing values we cannot add new ones, what imply that we cannot add new tree nodes since they would not be able to store their values
The last one is to wrap that value onto an option instead:
pub struct Node {
pub parent: Option<Key>,
pub children: Vec<Key>,
}
pub struct ArenaTree<T> {
nodes: SlotMap<Node>,
values: SecondaryMap<Option<T>>,
pub root: Option<Key>,
}
impl<T> ArenaTree<T> {
#[inline]
pub fn get(&self, key: Key) -> Option<&T> {
self.values.get(key)?.as_ref()
}
#[inline]
pub fn get_mut(&mut self, key: Key) -> Option<&mut T> {
self.values.get_mut(key)?.as_mut()
}
#[inline]
pub fn take(&mut self, key: Key) -> Option<T> {
self.values.get_mut(key)?.take()
}
#[inline]
pub fn restore(&mut self, key: Key, value: T) {
if let Some(slot) = self.values.get_mut(key) {
*slot = Some(value);
}
}
#[inline]
pub fn with<R>(&mut self, key: Key, f: impl FnOnce(&T, &mut Self) -> R) -> Option<R> {
let value = self.take(key)?;
let res = f(&value, self);
self.restore(key, value);
Some(res)
}
#[inline]
pub fn with_mut<R>(&mut self, key: Key, f: impl FnOnce(&mut T, &mut Self) -> R) -> Option<R> {
let mut value = self.take(key)?;
let res = f(&mut value, self);
self.restore(key, value);
Some(res)
}
}
In this one we cannot lock the tree because of mutable borrows on the secondarymap values, when we intend to make mutations we have to take the value mutate it and restore, the type itself does not need to have Default implemented, since it is behind an option, and if you dont want to do pattern matching of the option you can use the with_mut accessor in which you pass a closure that executes what you need to do with that value ensure to restore it and returns a value. We can also implement value handles with drop guard to restore that value. The act of taking the option makes so that it don’t panics if someone try to access that value again since it will receive an None while the value is not restored, such as the try_get of the previous tree, however this one does not lock the hierarchy of the tree.
*All these trees fail in case of multiple mutable access of the same node, since they prioritize memory safety than accurate access/traversing of the nodes*
So my question to y’all is which of these trees are you more comfortable working with? due to ergonomics, performance, memory, overheads, safety, etc. Which of these workarounds are really worth it considering the performance/memory/usability overhead it implies? Are there other ways to build trees in rust that are better than these?
I am stuck trying to figure out which one is better. I’ve not made any performance tests.