aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_vfs/src/arena.rs
diff options
context:
space:
mode:
authorbors[bot] <bors[bot]@users.noreply.github.com>2018-12-20 09:16:07 +0000
committerbors[bot] <bors[bot]@users.noreply.github.com>2018-12-20 09:16:07 +0000
commit9a16cf2bf646a4a881f3f5acbf5582dacc4337bf (patch)
treeff90eb390a8f5af47b6d0c6ec4c49b4431b82d1c /crates/ra_vfs/src/arena.rs
parentdbb62b5baa36783bbca06f09c77794fce3ceff0c (diff)
parenta084412f0698d5f54d586f707930e141c88b0673 (diff)
Merge #292
292: Vfs r=matklad a=matklad closes #243 Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/ra_vfs/src/arena.rs')
-rw-r--r--crates/ra_vfs/src/arena.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/crates/ra_vfs/src/arena.rs b/crates/ra_vfs/src/arena.rs
new file mode 100644
index 000000000..6b42ae26d
--- /dev/null
+++ b/crates/ra_vfs/src/arena.rs
@@ -0,0 +1,53 @@
1use std::{
2 marker::PhantomData,
3 ops::{Index, IndexMut},
4};
5
6#[derive(Clone, Debug)]
7pub(crate) struct Arena<ID: ArenaId, T> {
8 data: Vec<T>,
9 _ty: PhantomData<ID>,
10}
11
12pub(crate) trait ArenaId {
13 fn from_u32(id: u32) -> Self;
14 fn to_u32(self) -> u32;
15}
16
17impl<ID: ArenaId, T> Arena<ID, T> {
18 pub fn alloc(&mut self, value: T) -> ID {
19 let id = self.data.len() as u32;
20 self.data.push(value);
21 ID::from_u32(id)
22 }
23 pub fn iter<'a>(&'a self) -> impl Iterator<Item = (ID, &'a T)> {
24 self.data
25 .iter()
26 .enumerate()
27 .map(|(idx, value)| (ID::from_u32(idx as u32), value))
28 }
29}
30
31impl<ID: ArenaId, T> Default for Arena<ID, T> {
32 fn default() -> Arena<ID, T> {
33 Arena {
34 data: Vec::new(),
35 _ty: PhantomData,
36 }
37 }
38}
39
40impl<ID: ArenaId, T> Index<ID> for Arena<ID, T> {
41 type Output = T;
42 fn index(&self, idx: ID) -> &T {
43 let idx = idx.to_u32() as usize;
44 &self.data[idx]
45 }
46}
47
48impl<ID: ArenaId, T> IndexMut<ID> for Arena<ID, T> {
49 fn index_mut(&mut self, idx: ID) -> &mut T {
50 let idx = idx.to_u32() as usize;
51 &mut self.data[idx]
52 }
53}