Expand description
immutable_arena
provides a type Arena<T>
for objects that are immutable
once allocated, and a smart pointer type Ref<'arena, T>
that may be set
exactly once, allowing the user to create cycles among objects in the
arena.
Example usage:
use immutable_arena::{Arena, Ref};
struct S<'arena> {
id: u32,
next: Ref<'arena, S<'arena>>,
}
fn alloc_cycle<'arena>(arena: &'arena Arena<S<'arena>>)
-> &'arena S<'arena> {
let s1 = arena.alloc(S { id: 1, next: Ref::empty() });
let s2 = arena.alloc(S { id: 2, next: Ref::empty() });
s1.next.set(s2);
s2.next.set(s1);
s1
}
fn test_cycle() {
let arena = Arena::new();
let s1 = alloc_cycle(&arena);
assert!(s1.next.next.id == s1.id);
}
Structsยง
- An
Arena<T>
is a container of objects of typeT
that, once allocated, live as long as the containing arena. Within the arena, objects may refer to other objects using theRef<'arena, T>
smart-pointer type. These object references are allowed to form cycles. Once created, an object is immutable. However, anyRef<'arena, T>
instances within the object may be set exactly once. The common usage pattern is to create objects and set all their refs before returning them to user code; the objects are subsequently completely immutable. - A
Ref<'arena, T>
is a smart pointer type that may be used within an arena-allocated type to hold a reference to another object within that arena. It may be set exactly once, and is immutable thereafter. It dereferences only to a read-only borrow, never a mutable one.