#arena #allocation #allocator #limited #single #object #typed

no-std typed-arena

The arena, a fast but limited type of allocator

14 stable releases

Uses old Rust 2015

2.0.2 Jan 9, 2023
2.0.1 Jan 10, 2020
2.0.0 Dec 3, 2019
2.0.0-rc1 Nov 26, 2019
1.0.1 Apr 10, 2015

#8 in Memory management

Download history 131995/week @ 2024-01-02 138443/week @ 2024-01-09 150304/week @ 2024-01-16 152337/week @ 2024-01-23 155099/week @ 2024-01-30 163336/week @ 2024-02-06 157173/week @ 2024-02-13 145612/week @ 2024-02-20 161253/week @ 2024-02-27 162255/week @ 2024-03-05 169044/week @ 2024-03-12 166326/week @ 2024-03-19 190003/week @ 2024-03-26 182080/week @ 2024-04-02 173631/week @ 2024-04-09 146225/week @ 2024-04-16

719,186 downloads per month
Used in 1,053 crates (92 directly)

MIT license

37KB
572 lines

typed-arena

Github Actions Build Status

A fast (but limited) allocation arena for values of a single type.

Allocated objects are destroyed all at once, when the arena itself is destroyed. There is no deallocation of individual objects while the arena itself is still alive. The flipside is that allocation is fast: typically just a vector push.

There is also a method into_vec() to recover ownership of allocated objects when the arena is no longer required, instead of destroying everything.

Example

use typed_arena::Arena;

struct Monster {
    level: u32,
}

let monsters = Arena::new();

let goku = monsters.alloc(Monster { level: 9001 });
assert!(goku.level > 9000);

Safe Cycles

All allocated objects get the same lifetime, so you can safely create cycles between them. This can be useful for certain data structures, such as graphs and trees with parent pointers.

use std::cell::Cell;
use typed_arena::Arena;

struct CycleParticipant<'a> {
    other: Cell<Option<&'a CycleParticipant<'a>>>,
}

let arena = Arena::new();

let a = arena.alloc(CycleParticipant { other: Cell::new(None) });
let b = arena.alloc(CycleParticipant { other: Cell::new(None) });

a.other.set(Some(b));
b.other.set(Some(a));

Alternatives

Need to allocate many different types of values?

Use multiple arenas if you have only a couple different types or try bumpalo, which is a bump-allocation arena can allocate heterogenous types of values.

Want allocation to return identifiers instead of references and dealing with references and lifetimes everywhere?

Check out id-arena or generational-arena.

Need to deallocate individual objects at a time?

Check out generational-arena for an arena-style crate or look for a more traditional allocator.

No runtime deps