I built a garbage collector for Rust (2023)
In 2023, a programmer decided to create a garbage collector for Rust, a language designed to eliminate garbage collection. The project aimed to build a piece of software that manages allocations for another, more exciting piece of software. The garbage collector was written in Rust and integrated with the Rust standard library.
Rust's memory model relies on affine typing and the borrow checker, which enforces that values can only be bound to one identifier at a time and that borrow (references) cannot outlive the scope binding their referent. To handle shared ownership of heap-allocated values, Rust's standard library provides two reference-counted garbage collectors: Rc and Arc. However, these are limited when it comes to cyclic references.
The programmer aimed to create a Gc data structure with a similar API to Rc and Arc, capable of managing cycles. To do this, they needed to detect whether a Gc was reachable without scanning the stack. They approached this by using graph-theoretical language, imagining each allocation as a node and Gc as an edge connecting two nodes. An allocation is considered reachable if it can be accessed in the graph-theoretical sense.
The programmer outlined an approach to determine if a node is accessible using a serpentine implementation in pseudocode. They implemented is_accessible in linear time and created two visitors, one for the depth-first search (DFS) step and another for the mark step. They also implemented additional collectors, such as marking and destroying allocations.
The project faced challenges, such as implementing is_accessible, which required scanning edges and having to add a small constraint to every garbage-collected type. Despite the difficulties, the programmer successfully built a garbage collector that could handle most data types inside Rust.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.