| 1 |
# `typed-arena-nomut` |
| 2 |
|
| 3 |
[](https://docs.rs/typed-arena-nomut/) |
| 4 |
[](https://crates.io/crates/typed-arena-nomut) |
| 5 |
[](https://crates.io/crates/typed-arena-nomut) |
| 6 |
|
| 7 |
This is a fork of the typed-arena arena crate that returns an immutable reference instead of |
| 8 |
mutable one. This allows iteration on the arena items while they're borrowed. |
| 9 |
|
| 10 |
**A fast (but limited) allocation arena for values of a single type.** |
| 11 |
|
| 12 |
Allocated objects are destroyed all at once, when the arena itself is destroyed. |
| 13 |
There is no deallocation of individual objects while the arena itself is still |
| 14 |
alive. The flipside is that allocation is fast: typically just a vector push. |
| 15 |
|
| 16 |
There is also a method `into_vec()` to recover ownership of allocated objects |
| 17 |
when the arena is no longer required, instead of destroying everything. |
| 18 |
|
| 19 |
|
| 20 |
## Example |
| 21 |
|
| 22 |
```rust |
| 23 |
use typed_arena_nomut::Arena; |
| 24 |
|
| 25 |
struct Monster { |
| 26 |
level: u32, |
| 27 |
} |
| 28 |
|
| 29 |
let monsters = Arena::new(); |
| 30 |
|
| 31 |
let goku = monsters.alloc(Monster { level: 9001 }); |
| 32 |
assert!(goku.level > 9000); |
| 33 |
``` |
| 34 |
|
| 35 |
## Safe Cycles |
| 36 |
|
| 37 |
All allocated objects get the same lifetime, so you can safely create cycles |
| 38 |
between them. This can be useful for certain data structures, such as graphs |
| 39 |
and trees with parent pointers. |
| 40 |
|
| 41 |
```rust |
| 42 |
use std::cell::Cell; |
| 43 |
use typed_arena_nomut::Arena; |
| 44 |
|
| 45 |
struct CycleParticipant<'a> { |
| 46 |
other: Cell<Option<&'a CycleParticipant<'a>>>, |
| 47 |
} |
| 48 |
|
| 49 |
let arena = Arena::new(); |
| 50 |
|
| 51 |
let a = arena.alloc(CycleParticipant { other: Cell::new(None) }); |
| 52 |
let b = arena.alloc(CycleParticipant { other: Cell::new(None) }); |
| 53 |
|
| 54 |
a.other.set(Some(b)); |
| 55 |
b.other.set(Some(a)); |
| 56 |
``` |
| 57 |
|
| 58 |
## Alternatives |
| 59 |
|
| 60 |
### Need to allocate many different types of values? |
| 61 |
|
| 62 |
Use multiple arenas if you have only a couple different types or try |
| 63 |
[`bumpalo`](https://crates.io/crates/bumpalo), which is a bump-allocation arena |
| 64 |
can allocate heterogenous types of values. |
| 65 |
|
| 66 |
### Want allocation to return identifiers instead of references and dealing with references and lifetimes everywhere? |
| 67 |
|
| 68 |
Check out [`id-arena`](https://crates.io/crates/id-arena) or |
| 69 |
[`generational-arena`](https://crates.io/crates/generational-arena). |
| 70 |
|
| 71 |
### Need to deallocate individual objects at a time? |
| 72 |
|
| 73 |
Check out [`generational-arena`](https://crates.io/crates/generational-arena) |
| 74 |
for an arena-style crate or look for a more traditional allocator. |