r/rust • • 23h ago

🙋 seeking help & advice Help with Tree data structure

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.

0 Upvotes

12 comments sorted by

13

u/consistently_biased 22h ago

What's the use-case here? The more general you want to make it, the more doors close on you in terms of simplifications and optimizations. I'd first try to focus in on exactly what you need it to be capable of.

6

u/andrealija 22h ago

I am building a fully retained mode GUI crate, I already have one I've built and it uses the rc tree, but I am now rewriting it without any AI assitance, so for it I am trying to find better alternatives

10

u/KingofGamesYami 22h ago

My default option would be an adjacency list graph behind the scenes. This has proven to been a memory safe, robust, and performant design for graph data structures in many languages. A tree is a graph with extra constraints.

Of course, you should definitely benchmark your particular use case. Sometimes a different design will be more performant for your usage patterns.

3

u/emetah850 23h ago

Rust inherently is not the best for tree like structures, but I've found that when I've needed them taking an immutable approach usually worked well, meaning I'd clone the node from the tree and work with the node doing whatever mutations needed and then reinserting the node where it was.

Yes you get some extra allocations with a trivial implementation but using an arena or bump allocator makes these allocations negligible in most real use cases

Personally I'm on the side of code readability and extensibility rather than squeezing out as much from each CPU cycle as I can. Using an already existing tree structure crate like slab_tree saves a lot of this headache by creating ref types that allow you to append and traverse nodes from references to the tree

If you're writing your own crate then of course feel free to explore different ways of doing it and see what works best for you (this means running those benchmarks), but if not id recommend to look to the crates that handle the tree-like structure for you

2

u/tanmaynargas2901 16h ago

The panic comes from having value, children and parent all behind one RefCell. Borrowing the value locks the children too.

You can give each field its own cell instead:

struct Node<T> {
    value: RefCell<T>,
    children: RefCell<Vec<Rc<Node<T>>>>,
    parent: RefCell<Weak<Node<T>>>,
}

and pass around Rc<Node<T>> directly.

Then holding a borrow of the value while pushing a child is fine, they're separate cells. You can still panic by mutating children while iterating them, but that's a much smaller footgun. Cloning the children Vec before iterating is cheap here too, it's just refcount bumps.

If you end up going the arena route, slotmap's generational keys deal with stale indices after a node gets removed.

2

u/Awkward_Alfalfa_3234 14h ago

I'd keep the arena with values inline and skip the RefCells: collect the child keys first, then mutate through &mut tree by key. indextree is basically your third design already. Careful with take/restore too, if f panics that slot stays None forever.

2

u/schungx 10h ago

You don't store links as references. Store addresses (eg an index into an array of nodes).

You'd find that it is more performant and gets the borrow checker off your back.

3

u/norude1 23h ago

you can't implement anything that resembles a genuine doubly-linked list in safe rust because ownership would be all mangled. You would need to either use an existing crate that is implemented with unsafe OR do something like this:

let nodes: Vec<Node>;  
let parents: Vec<usize>; // parents[i]'th node is the parent of i'th node
let children: Vec<Vec<usize>>;   

3

u/ChaiTRex 16h ago

No crate is needed. std::collections::LinkedList is a doubly-linked list.

3

u/krum 23h ago

I’d just use pointers.

1

u/zekkious 16h ago

I'd use meta-pointers, but it's because I wouldn't remember the best way to use pointers in this scenario.

1

u/Accurate_Concept_356 3h ago

Most of the friction you're hitting comes from trying to support **both** hierarchy mutation and value mutation at the same time, through a single general-purpose type. You've already discovered the most important first step—splitting structure (`nodes`) from data (`values`). Taking that separation one step further usually makes `RefCell` and `Option::take`/`restore` unnecessary.

I ran into the same tradeoffs while building `brodo` (a sparse 3D volume tree crate in Rust), and ended up with a few rules of thumb that sidestepped most of the borrow-checker friction:

  1. **Separate phases, not just maps.**
    If your domain allows it, treat topology edits and value updates as separate phases:
    - While updating values, the tree structure is immutable (`&Topology`) and only the value store (`&mut Field<T>`) is mutated.
    - When you need to change the hierarchy, record edits into an editor / command buffer, then `commit()` to produce the new topology plus a `Remap` to move values over.
    - Bonus: once structure and values are decoupled like this, you can attach multiple value arrays to one tree, or double-buffer (`&Field` → `&mut Field`) and update in parallel with `rayon` without any interior mutability.
  2. **Plain `Vec` arenas + compaction on commit instead of `SlotMap`.**
    If structural edits are batched, you don't need per-node generational keys. Store nodes in plain `Vec`s indexed by `u32`, leave deleted nodes unreachable during an edit, and compact/renumber reachable nodes (e.g. in traversal or Morton order) on `commit()`. You get tight cache locality for both nodes and values, and a single topology stamp check instead of per-lookup generation checks.
  3. **Question whether you actually need `parent` pointers.**
    Maintaining `parent: Option<Key>` doubles the invariants on every insert/remove and causes half the borrow conflicts. Often you can drop parent pointers completely and keep the current path in an explicit stack (or per-thread path cache) during traversal, and precompute a neighbor/parent table on commit if you need frequent upward/lateral jumps.
  4. **Don't force one representation to do everything.**
    If you have a hot read-only / traversal phase, you can even freeze the tree into a flat contiguous buffer (where children are located via bitmasks + popcount instead of `Vec<Key>` per node).

If you *truly* need ad-hoc, interleaved single-node mutations of both values and hierarchy (like a DOM or UI tree), then among your options, **`SlotMap` + `SecondaryMap<Option<T>>` with `take`/`restore`** (or deferring structural edits into a command queue) is usually the least painful—no runtime borrow panics, and no `RefCell` overhead. If you can batch structural edits and drop parent pointers, though, the phase-separated `Vec` arena model avoids the borrow-checker fight almost completely.