Skip to main content

Trace

Trait Trace 

Source
pub trait Trace<T, const N: usize>
where T: Copy,
{ // Required method fn trace<F>(&self, tracer: F) where F: FnMut(ArenaIndex); // Provided method fn trace_with_arena<F>(&self, _arena: &Arena<T, N>, tracer: F) where F: FnMut(ArenaIndex) { ... } }
Expand description

Trait for types that can be traced by the garbage collector.

Implement this for types that contain ArenaIndex fields. The GC will call trace to discover all reachable objects starting from the roots.

§Example

use grift_arena::{Arena, ArenaIndex, Trace};

#[derive(Clone, Copy)]
enum Tree {
    Leaf(isize),
    Branch(ArenaIndex, ArenaIndex),
}

impl<const N: usize> Trace<Tree, N> for Tree {
    fn trace<F: FnMut(ArenaIndex)>(&self, mut tracer: F) {
        match *self {
            Tree::Leaf(_) => {} // No references to trace
            Tree::Branch(left, right) => {
                tracer(left);
                tracer(right);
            }
        }
    }
}

let arena: Arena<Tree, 100> = Arena::new(Tree::Leaf(0));

// Build a tree
let leaf1 = arena.alloc(Tree::Leaf(1)).unwrap();
let leaf2 = arena.alloc(Tree::Leaf(2)).unwrap();
let root = arena.alloc(Tree::Branch(leaf1, leaf2)).unwrap();

// Also allocate some garbage (unreachable nodes)
let garbage1 = arena.alloc(Tree::Leaf(999)).unwrap();
let garbage2 = arena.alloc(Tree::Leaf(888)).unwrap();

assert_eq!(arena.len(), 5);

// Collect garbage, keeping only objects reachable from `root`
let stats = arena.collect_garbage(&[root]);

assert_eq!(stats.collected, 2); // garbage1 and garbage2 were freed
assert_eq!(arena.len(), 3);     // root, leaf1, leaf2 remain

Required Methods§

Source

fn trace<F>(&self, tracer: F)
where F: FnMut(ArenaIndex),

Trace all ArenaIndex references contained in this value.

Call tracer once for each ArenaIndex field in this value. The GC uses this to discover the object graph.

Provided Methods§

Source

fn trace_with_arena<F>(&self, _arena: &Arena<T, N>, tracer: F)
where F: FnMut(ArenaIndex),

Trace with arena access for types that store metadata in the arena.

Some types (like arrays/strings that store their length in the arena) need to read from the arena during tracing to determine how many elements to trace. Override this method for such types.

The default implementation just calls trace().

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<const N: usize> Trace<Value, N> for Value

Implement Trace for GC support

With inline fields, tracing is simpler - we just trace the ArenaIndex fields directly. No arena access needed to determine structure, which improves GC performance.