aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_vfs/src/arena.rs
blob: 6b42ae26d22d432d188aa459de45c8ddfc9ac42b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use std::{
    marker::PhantomData,
    ops::{Index, IndexMut},
};

#[derive(Clone, Debug)]
pub(crate) struct Arena<ID: ArenaId, T> {
    data: Vec<T>,
    _ty: PhantomData<ID>,
}

pub(crate) trait ArenaId {
    fn from_u32(id: u32) -> Self;
    fn to_u32(self) -> u32;
}

impl<ID: ArenaId, T> Arena<ID, T> {
    pub fn alloc(&mut self, value: T) -> ID {
        let id = self.data.len() as u32;
        self.data.push(value);
        ID::from_u32(id)
    }
    pub fn iter<'a>(&'a self) -> impl Iterator<Item = (ID, &'a T)> {
        self.data
            .iter()
            .enumerate()
            .map(|(idx, value)| (ID::from_u32(idx as u32), value))
    }
}

impl<ID: ArenaId, T> Default for Arena<ID, T> {
    fn default() -> Arena<ID, T> {
        Arena {
            data: Vec::new(),
            _ty: PhantomData,
        }
    }
}

impl<ID: ArenaId, T> Index<ID> for Arena<ID, T> {
    type Output = T;
    fn index(&self, idx: ID) -> &T {
        let idx = idx.to_u32() as usize;
        &self.data[idx]
    }
}

impl<ID: ArenaId, T> IndexMut<ID> for Arena<ID, T> {
    fn index_mut(&mut self, idx: ID) -> &mut T {
        let idx = idx.to_u32() as usize;
        &mut self.data[idx]
    }
}