Skip to main content

gc_node_usage/
gc_node_usage.rs

1use gc_lite::{GcHeap, GcRef, GcResult, GcScopeStackId, GcTrace, GcTraceCtx, gc_type_register};
2
3#[derive(Debug)]
4struct StaticNode {
5    _value: i32,
6}
7
8impl GcTrace for StaticNode {
9    fn trace(&self, _ctx: &mut GcTraceCtx) {}
10}
11
12#[derive(Debug)]
13struct OtherNode {
14    _value: i32,
15}
16
17impl GcTrace for OtherNode {
18    fn trace(&self, _ctx: &mut GcTraceCtx) {}
19}
20
21gc_type_register! {
22    StaticNode, drop_pass = 1;
23    OtherNode;
24}
25
26fn alloc_static(
27    heap: &mut GcHeap,
28    stack_id: GcScopeStackId,
29    value: i32,
30) -> GcResult<GcRef<StaticNode>> {
31    heap.with_new_scope(stack_id, |ctx| {
32        let r = ctx
33            .alloc_local(StaticNode { _value: value })
34            .map_err(|(err, _)| err)
35            .map(|gc| gc.into_raw());
36        ctx.clear();
37        r
38    })
39}
40
41fn alloc_other(
42    heap: &mut GcHeap,
43    stack_id: GcScopeStackId,
44    value: i32,
45) -> GcResult<GcRef<OtherNode>> {
46    heap.with_new_scope(stack_id, |ctx| {
47        let r = ctx
48            .alloc_local(OtherNode { _value: value })
49            .map_err(|(err, _)| err)
50            .map(|gc| gc.into_raw());
51        ctx.clear();
52        r
53    })
54}
55
56fn main() -> GcResult<()> {
57    let mut heap = GcHeap::new(&GC_TYPE_REGISTRY);
58    let partition = heap.create_partition(64 * 1024, 16 * 1024);
59    let stack_id = heap.acquire_scope_stack(partition);
60
61    let static_ref = alloc_static(&mut heap, stack_id, 10)?;
62    let other_ref = alloc_other(&mut heap, stack_id, 20)?;
63
64    println!(
65        "Static node value: {}",
66        unsafe { static_ref.as_ref() }._value
67    );
68    println!("Other node value: {}", unsafe { other_ref.as_ref() }._value);
69
70    heap.release_scope_stack(stack_id);
71
72    println!("gc_node_usage example verified");
73
74    Ok(())
75}