| Crates.io | rust-arc-gc |
| lib.rs | rust-arc-gc |
| version | 0.2.1 |
| created_at | 2025-05-15 07:50:18.782715+00 |
| updated_at | 2025-07-02 13:42:50.537486+00 |
| description | A simple GCArc implementation for Rust |
| homepage | |
| repository | https://github.com/sjrsjz/arc-gc |
| max_upload_size | |
| id | 1674625 |
| size | 34,760 |
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 using a mark-and-sweep garbage collection algorithm.
GCArcWeak type for solving circular reference problemsGCTraceable trait to make objects part of the garbage collection systemUse cargo add rust-arc-gc to add the library to your project.
GC::new() - Create a new garbage collector instance with default 20% percentage thresholdGC::new_with_percentage(percentage) - Create a garbage collector with custom percentage threshold (e.g., 30 for 30%)GC::new_with_memory_threshold(memory_threshold) - Create a garbage collector with memory threshold in bytesGC::new_with_thresholds(percentage, memory_threshold) - Create a garbage collector with both percentage and memory thresholdsgc.attach(obj) - Add an object to the garbage collector's tracking scope (may trigger automatic collection)gc.detach(obj) - Remove an object from garbage collector tracking, returns true if object was found and removedgc.create(obj) - Create a new object and automatically add it to the garbage collectorgc.collect() - Manually perform mark-and-sweep garbage collectiongc.object_count() - Return the current number of objects managed by the garbage collectorgc.get_all() - Return a vector of all objects currently managed by the garbage collectorgc.allocated_memory() - Get the current estimated allocated memory in bytesgc.memory_threshold() - Get the current memory threshold settinggc.set_memory_threshold(threshold) - Set or update the memory threshold (None to disable)The garbage collector uses multiple strategies to decide when to trigger collection:
attach_count >= current_objects * (percentage / 100)allocated_memory >= memory_threshold (if set)collect() methodBoth thresholds (if configured) work independently - collection triggers when either condition is met.
GCArc::new(obj) - Create a new reference-counted objectarc.as_ref() - Get an immutable reference to the objectarc.get_mut() - Get a mutable reference to the object (panics if not unique)arc.try_as_mut() - Try to get a mutable reference, returns Option<&mut T>arc.as_weak() - Create a weak reference to the objectarc.strong_ref() - Get the current strong reference countarc.weak_ref() - Get the current weak reference countA trait that must be implemented to allow the garbage collector to track object references:
pub trait GCTraceable<T: GCTraceable<T> + 'static> {
/// Collects all reachable objects and adds them to the provided queue.
/// This method is called during the mark phase of garbage collection
/// to traverse the object graph.
fn collect(&self, queue: &mut VecDeque<GCArcWeak<T>>);
}
Implementation Guidelines:
GCArcWeak<T> references held by your object to the queueGCArcWeak::upgrade() - Upgrade a weak reference to a strong reference, returning None if the object has been collectedGCArcWeak::is_valid() - Check if the weak reference is valid (i.e., the object has not been collected)weak.strong_ref() - Get the current strong reference countweak.weak_ref() - Get the current weak reference countuse arc_gc::{GC, GCArc, GCArcWeak, GCTraceable};
use std::collections::VecDeque;
use std::cell::RefCell;
// Define a node structure with potential circular references
struct Node {
value: i32,
children: RefCell<Vec<GCArcWeak<Node>>>,
}
impl GCTraceable<Node> for Node {
fn collect(&self, queue: &mut VecDeque<GCArcWeak<Node>>) {
// Add all child references to the collection queue
if let Ok(children) = self.children.try_borrow() {
for child in children.iter() {
queue.push_back(child.clone());
}
}
}
}
fn main() {
let mut gc = GC::new_with_percentage(25); // 25% threshold
// Create nodes
let node1 = gc.create(Node {
value: 1,
children: RefCell::new(Vec::new()),
});
let node2 = gc.create(Node {
value: 2,
children: RefCell::new(Vec::new()),
});
// Create circular reference
node1.as_ref().children.borrow_mut().push(node2.as_weak());
node2.as_ref().children.borrow_mut().push(node1.as_weak());
println!("Objects before collection: {}", gc.object_count());
// Drop strong references
drop(node1);
drop(node2);
// Manually trigger collection to clean up circular references
gc.collect();
println!("Objects after collection: {}", gc.object_count());
}
The dual-threshold collection system provides flexible memory management:
try_as_mut() instead of get_mut() when mutation might failas_weak() for non-owning references to prevent cyclesallocated_memory() and object_count() for tuning thresholdsThis project is licensed under the MIT License.