Skip to main content

cycle/
cycle.rs

1//! The example in README.md, kept compilable so the two cannot drift.
2use std::cell::RefCell;
3
4use js_gc::{Gc, Heap, Trace, Tracer};
5
6#[derive(Default)]
7struct Node {
8    next: RefCell<Option<Gc<Node>>>,
9}
10
11impl Trace for Node {
12    fn trace(&self, tracer: &mut Tracer<'_>) {
13        if let Some(next) = &*self.next.borrow() {
14            tracer.visit(next);
15        }
16    }
17}
18
19fn main() {
20    let heap = Heap::new();
21    let a = Gc::new(&heap, Node::default());
22    let b = Gc::new(&heap, Node::default());
23    *a.next.borrow_mut() = Some(b.clone());
24    *b.next.borrow_mut() = Some(a.clone()); // a cycle
25    drop((a, b));
26
27    let stats = heap.collect();
28    println!("collected={} live={}", stats.collected, stats.after);
29    assert_eq!(stats.collected, 2, "the cycle should be collected");
30}