Rust Arc GC (rust-arc-gc)
Introduction
rust-arc-gc is a simple garbage collection (GC) implementation library designed for Rust, providing reference counting functionality similar to Rust's standard library Arc, but with added garbage collection capabilities. This library is particularly suitable for handling circular reference problems and applications requiring efficient memory management.
This library combines Rust's memory safety features with the convenience of garbage collection, offering a safe way to manage complex object graphs in Rust.
Core Features
- Garbage Collection: Can detect and release objects that are no longer referenced, including circularly referenced objects
- Type Safety: Completely type-safe, no need for
unsafecode (except within the library itself) - Concurrency Safety: All operations are thread-safe
- Weak Reference Support: Provides
GCArcWeaktype for solving circular reference problems - Reference Tracking: Implement the
GCTraceabletrait to make objects part of garbage collection
Usage
Installation
Use cargo add rust-arc-gc to add the library to your project.
Basic Example
use ;
use GC;
use GCTraceable;
Handling Circular References
// Create nodes with circular references
let mut node1 = new;
let mut node2 = new;
// Create circular references
node1..children.push;
node2..children.push;
// Add to GC
gc.attach;
gc.attach;
// When nodes are no longer referenced externally, GC will reclaim them
drop;
drop;
gc.collect;
API Reference
GC
GC::new()- Create a new garbage collector instancegc.attach(obj)- Add an object to the garbage collector's tracking scopegc.collect()- Perform garbage collectiongc.object_count()- Return the current number of objects managed by the garbage collectorgc.create<T>(obj)- Create a new object and add it to the garbage collector
GCArc
GCArc::new(obj)- Create a new reference-counted objectarc.downcast::<T>()- Get a reference to the object, with type checkingarc.downcast_mut::<T>()- Get a mutable reference to the object, with type checkingarc.mark_and_visit()- Mark the object and visit its referenced objectsarc.is_marked()- Check if the object is markedarc.as_weak()- Create a weak reference to the object
GCTraceable
A trait that must be implemented to allow the garbage collector to track objects:
GCArcWeak
GCArcWeak::upgrade()- Upgrade a weak reference to a strong reference, returningNoneif the object has been collectedGCArcWeak::is_valid()- Check if the weak reference is valid (i.e., the object has not been collected)
Limitations and Future Plans
- The current implementation uses a mark-sweep garbage collection algorithm; generational collection may be added in the future
- Performance optimization: reduce pause time during garbage collection
- Add richer debugging tools and memory usage statistics
License
This project is licensed under the MIT License.