FAQ - Help and questions

How do I port objects that point to each other, such as trees with parent links?

#porting#ownership#data-structurespublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Objects that refer to each other in a cycle do not fit single ownership. The simplest port stores all nodes in one Vec and lets them refer to each other by index. Use Rc with Weak only when nodes must be shared and freed independently. Indices also make the structure easy to copy and test.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

In Java, C# or Python a tree node often holds parent and children references, and the garbage collector sorts out who is alive. In Rust every value has one owner. A node owned by its parent that also holds a reference to that parent is a cycle of ownership, and the compiler has no way to say who frees what.

There are three ways to port it, in the order most ports should try them:

  1. Indices into one Vec (an arena). The tree owns all nodes in a Vec<Node>; a node refers to others by position. There are no references between nodes, so the borrow checker has nothing to complain about.
  2. Rc for the owning direction and Weak for the back link, with RefCell when nodes change. The thread on unique_ptr, shared_ptr and weak_ptr shows it. It is the closest to the old code and the most verbose to use.
  3. Restructure. Often the parent link is only used to compute a path or to walk upwards. Passing the path down while walking, or computing it on demand, removes the need for the link.

This program ports class Node { Node parent; List<Node> children; String name; } with the arena. It was compiled and run with rustc 1.93.0.

src/main.rsrust
#[derive(Clone, Copy, PartialEq, Debug)]
struct NodeId(usize);

struct Node {
    name: String,
    parent: Option<NodeId>,
    children: Vec<NodeId>,
}

#[derive(Default)]
struct Tree {
    nodes: Vec<Node>,
}

impl Tree {
    fn add(&mut self, name: &str, parent: Option<NodeId>) -> NodeId {
        let id = NodeId(self.nodes.len());
        self.nodes.push(Node { name: name.to_string(), parent, children: Vec::new() });
        if let Some(p) = parent {
            self.nodes[p.0].children.push(id);
        }
        id
    }

    fn path(&self, mut id: NodeId) -> String {
        let mut parts = vec![self.nodes[id.0].name.as_str()];
        while let Some(p) = self.nodes[id.0].parent {
            parts.push(self.nodes[p.0].name.as_str());
            id = p;
        }
        parts.reverse();
        parts.join("/")
    }
}

fn main() {
    let mut t = Tree::default();
    let root = t.add("src", None);
    let util = t.add("util", Some(root));
    let file = t.add("strings.rs", Some(util));
    println!("{}", t.path(file));
    println!("{} has {} child node(s)", t.nodes[util.0].name, t.nodes[util.0].children.len());
}
text
src/util/strings.rs
util has 1 child node(s)

NodeId is a small Copy value, so you can store it anywhere without borrowing the tree. The cost is that an id can be stale: if you remove a node, ids that point at it are wrong (or point at a different node if you reuse the slot). Either never remove nodes, mark them as removed (Option<Node> in the Vec), or use a library that adds a generation number to each id; those are outside this example.

Common mistakes#

  • Using Rc<RefCell<Node>> for everything because it looks like the old object graph. It works, but borrowing errors move from compile time to run time (RefCell panics when two borrows conflict), and cycles leak unless a link is Weak.
  • Handing out &mut Node from the tree and then needing the tree again. With an arena you get the node by id, use it, and let the borrow end before the next lookup.
  • Treating the index as a stable identity across saves or between program runs. If an id must survive, store a real identifier in the node.

Does an arena leak memory?#

It frees everything when the Tree is dropped. Nodes you stop using stay in the Vec until then, unless you reuse slots.

Is this slower than pointers?#

Not inherently: the nodes sit together in one allocation instead of being scattered, and indexing is a bounds-checked array access. This thread did not measure it, so make no assumption without measuring your own structure.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet