Hasty Briefsbeta

Bilingual

Garbage Collection Without Unsafe Code

a day ago
  • #rust
  • #memory-safety
  • #garbage-collection
  • The author created a garbage collection library for Rust called safe-gc that uses no unsafe code.
  • Unlike other GC libraries in Rust, safe-gc's Trace trait is safe to implement, avoiding unsafe traits.
  • Objects are allocated in independently garbage-collected Heaps, and access requires indexing into the Heap.
  • Two reference types are provided: Gc<T> (non-rooted, Copy) and Root<T> (rooted, not Copy).
  • The heap uses a hash map from TypeId to arenas (Vec-based storage) with free lists for management.
  • Garbage collection is implemented via mark-and-sweep, using per-type mark stacks and a root set for each arena.
  • safe-gc prevents classic GC footguns by using Drop safely and ensuring memory safety even with incorrect usage.
  • A copying collector was considered but abandoned due to borrowing complexities in a heterogeneous heap.
  • The library prioritizes safety and simplicity over performance, making it a novel point in Rust's GC design space.