Expand description
A fast garbage collector based on cycle collection for Rust programs.
This crate provides a Cc
(Cycle Collected) smart pointer, which is basically a Rc
which automatically detects and
deallocates reference cycles. If there are no reference cycles, then Cc
behaves like Rc
and deallocates
immediately when the reference counter drops to zero.
Currently, the cycle collector is not concurrent. As such, Cc
doesn’t implement Send
nor Sync
.
§Examples
§Basic usage
#[derive(Trace, Finalize)]
struct Data {
a: Cc<u32>,
b: RefCell<Option<Cc<Data>>>,
}
// Rc-like API
let my_cc = Cc::new(Data {
a: Cc::new(42),
b: RefCell::new(None),
});
let my_cc_2 = my_cc.clone();
let pointed: &Data = &*my_cc_2;
drop(my_cc_2);
// Create a cycle!
*my_cc.b.borrow_mut() = Some(my_cc.clone());
// Here, the allocated Data instance doesn't get immediately deallocated, since there is a cycle.
drop(my_cc);
// We have to call the cycle collector
collect_cycles();
// collect_cycles() is automatically called from time to time when creating new Ccs,
// calling it directly only ensures that a collection is run (like at the end of the program)
The derive macro for the Finalize
trait generates an empty finalizer. To write custom finalizers implement the Finalize
trait manually:
impl Finalize for Data {
fn finalize(&self) {
// Finalization code called when a Data object is about to be deallocated
// to allow resource clean up (like closing file descriptors, etc)
}
}
§Weak pointers
let cc: Cc<i32> = Cc::new(5);
// Obtain a weak pointer
let weak_ptr: Weak<i32> = cc.downgrade();
// Upgrading a weak pointer cannot fail if the pointed allocation isn't deallocated
let upgraded: Option<Cc<i32>> = weak_ptr.upgrade();
assert!(upgraded.is_some());
// Deallocate the object
drop(cc);
drop(upgraded);
// Upgrading now fails
assert!(weak_ptr.upgrade().is_none());
See the weak
module documentation for more details.
§Cleaners
#[derive(Trace, Finalize)]
struct Foo {
cleaner: Cleaner,
// ...
}
let foo = Cc::new(Foo {
cleaner: Cleaner::new(),
// ...
});
let cleanable = foo.cleaner.register(move || {
// Cleaning action code
// Will be called automatically when foo.cleaner is dropped
});
// It's also possible to call the cleaning action manually
cleanable.clean();
See the cleaners
module documentation for more details.
Modules§
- cleaners
cleaners
Execute cleaning actions on object destruction. - config
auto-collect
Configuration of the garbage collector. - Information about the garbage collector state.
- weak
weak-ptrs
Non-owningWeak
pointers to an allocation.
Structs§
- A thread-local cycle collected pointer.
- The tracing context provided to every invocation of
Trace::trace
.
Traits§
- Trait to finalize objects before freeing them.
- Trait to trace cycle-collectable objects.
Functions§
- Immediately executes the cycle collection algorithm and collects garbage cycles.