aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_arena/src
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2019-01-04 13:01:06 +0000
committerAleksey Kladov <[email protected]>2019-01-04 13:58:10 +0000
commit291d578938d7dc9b1f9bbd1174e444cc831531d9 (patch)
tree153e44aa0ccb17be658acbc9ae2e62d2a87178ab /crates/ra_arena/src
parent821fa7a50ab8c4886adc60a2093aa8e06cc3a9d6 (diff)
extract area to a crate
Diffstat (limited to 'crates/ra_arena/src')
-rw-r--r--crates/ra_arena/src/lib.rs97
1 files changed, 97 insertions, 0 deletions
diff --git a/crates/ra_arena/src/lib.rs b/crates/ra_arena/src/lib.rs
new file mode 100644
index 000000000..44d9e826b
--- /dev/null
+++ b/crates/ra_arena/src/lib.rs
@@ -0,0 +1,97 @@
1//! Yet another index-based arena.
2
3use std::{
4 fmt,
5 marker::PhantomData,
6 ops::{Index, IndexMut},
7};
8
9#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct RawId(u32);
11
12impl From<RawId> for u32 {
13 fn from(raw: RawId) -> u32 {
14 raw.0
15 }
16}
17
18impl From<u32> for RawId {
19 fn from(id: u32) -> RawId {
20 RawId(id)
21 }
22}
23
24impl fmt::Debug for RawId {
25 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26 self.0.fmt(f)
27 }
28}
29
30impl fmt::Display for RawId {
31 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32 self.0.fmt(f)
33 }
34}
35
36#[derive(Clone, Debug)]
37pub struct Arena<ID: ArenaId, T> {
38 data: Vec<T>,
39 _ty: PhantomData<ID>,
40}
41
42#[macro_export]
43macro_rules! impl_arena_id {
44 ($name:ident) => {
45 impl $crate::ArenaId for $name {
46 fn from_raw(raw: $crate::RawId) -> Self {
47 $name(raw)
48 }
49 fn into_raw(self) -> $crate::RawId {
50 self.0
51 }
52 }
53 };
54}
55
56pub trait ArenaId {
57 fn from_raw(raw: RawId) -> Self;
58 fn into_raw(self) -> RawId;
59}
60
61impl<ID: ArenaId, T> Arena<ID, T> {
62 pub fn alloc(&mut self, value: T) -> ID {
63 let id = RawId(self.data.len() as u32);
64 self.data.push(value);
65 ID::from_raw(id)
66 }
67 pub fn iter<'a>(&'a self) -> impl Iterator<Item = (ID, &'a T)> {
68 self.data
69 .iter()
70 .enumerate()
71 .map(|(idx, value)| (ID::from_raw(RawId(idx as u32)), value))
72 }
73}
74
75impl<ID: ArenaId, T> Default for Arena<ID, T> {
76 fn default() -> Arena<ID, T> {
77 Arena {
78 data: Vec::new(),
79 _ty: PhantomData,
80 }
81 }
82}
83
84impl<ID: ArenaId, T> Index<ID> for Arena<ID, T> {
85 type Output = T;
86 fn index(&self, idx: ID) -> &T {
87 let idx = idx.into_raw().0 as usize;
88 &self.data[idx]
89 }
90}
91
92impl<ID: ArenaId, T> IndexMut<ID> for Arena<ID, T> {
93 fn index_mut(&mut self, idx: ID) -> &mut T {
94 let idx = idx.into_raw().0 as usize;
95 &mut self.data[idx]
96 }
97}