cp_library_rs/tree/
arena.rs1pub trait ArenaNode {}
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub struct Ptr(pub usize);
9
10#[derive(Default)]
12pub struct Arena<N: ArenaNode> {
13 nodes: Vec<N>,
14 id: usize,
15}
16
17impl<N: ArenaNode> Arena<N> {
18 pub fn new() -> Self {
20 Self {
21 nodes: vec![],
22 id: 0,
23 }
24 }
25
26 pub fn with_capacity(n: usize) -> Self {
28 Self {
29 nodes: Vec::with_capacity(n),
30 id: 0,
31 }
32 }
33
34 pub fn alloc(&mut self, node: N) -> Ptr {
36 let id = self.nodes.len();
37 self.nodes.push(node);
38 Ptr(id)
39 }
40
41 pub fn get(&self, ptr: Ptr) -> &N {
43 &self.nodes[ptr.0]
44 }
45
46 pub fn get_mut(&mut self, ptr: Ptr) -> &mut N {
48 &mut self.nodes[ptr.0]
49 }
50}
51
52impl<N: ArenaNode + Default> Arena<N> {
53 pub fn alloc_default(&mut self) -> Ptr {
55 self.alloc(N::default())
56 }
57}