1 unstable release

0.2.0 Nov 28, 2023

#22 in #arena-allocator

MIT license

9KB
122 lines

simple-arena

A simple but fast arena allocator for a single type. Using it allows you to allocate structs that are guaranteed to have the same lifetime. This is useful for data structures that need to be able to cyclically reference each other, like trees. The downside is that you can't deallocate individual entries, you can deallocate the whole arena at once.

Examples

use simple_arena::Arena;

fn main() {
	let mut arena = Arena::new();
	let node1 = arena.alloc(1);
	let node2 = arena.alloc(2);
	assert_eq!(*node1, 1);
	assert_eq!(*node2, 2);
}

The arena can also be used to allocate structs that contain references to other structs in the arena using Cell.

use simple_arena::Arena;
use std::cell::Cell;

struct Node<'a> {
	next: Cell<Option<&'a Node<'a>>>,
	value: u32,
}

fn main() {
	let mut arena = Arena::new();
	let node1 = arena.alloc(Node { next: Cell::new(None), value: 1 });
	let node2 = arena.alloc(Node { next: Cell::new(Some(node1)), value: 2 });
	node1.next.set(Some(node2));
	assert_eq!(node1.next.get().unwrap().value, 2);
}

Alternatives

Do you need some more features like iterators: typed-arena

Do you need to allocate multiple types: bumpalo

No runtime deps