aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_arena
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_arena')
-rw-r--r--crates/ra_arena/src/lib.rs2
-rw-r--r--crates/ra_arena/src/map.rs70
2 files changed, 72 insertions, 0 deletions
diff --git a/crates/ra_arena/src/lib.rs b/crates/ra_arena/src/lib.rs
index a5eeb4118..040977dc4 100644
--- a/crates/ra_arena/src/lib.rs
+++ b/crates/ra_arena/src/lib.rs
@@ -6,6 +6,8 @@ use std::{
6 ops::{Index, IndexMut}, 6 ops::{Index, IndexMut},
7}; 7};
8 8
9pub mod map;
10
9#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 11#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct RawId(u32); 12pub struct RawId(u32);
11 13
diff --git a/crates/ra_arena/src/map.rs b/crates/ra_arena/src/map.rs
new file mode 100644
index 000000000..2f09d677f
--- /dev/null
+++ b/crates/ra_arena/src/map.rs
@@ -0,0 +1,70 @@
1//! A map from arena IDs to some other type. Space requirement is O(highest ID).
2
3use std::marker::PhantomData;
4
5use super::ArenaId;
6
7/// A map from arena IDs to some other type. Space requirement is O(highest ID).
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct ArenaMap<ID, T> {
10 v: Vec<Option<T>>,
11 _ty: PhantomData<ID>,
12}
13
14impl<ID: ArenaId, T> ArenaMap<ID, T> {
15 pub fn insert(&mut self, id: ID, t: T) {
16 let idx = Self::to_idx(id);
17 if self.v.capacity() <= idx {
18 self.v.reserve(idx + 1 - self.v.capacity());
19 }
20 if self.v.len() <= idx {
21 while self.v.len() <= idx {
22 self.v.push(None);
23 }
24 }
25 self.v[idx] = Some(t);
26 }
27
28 pub fn get(&self, id: ID) -> Option<&T> {
29 self.v.get(Self::to_idx(id)).and_then(|it| it.as_ref())
30 }
31
32 pub fn values(&self) -> impl Iterator<Item = &T> {
33 self.v.iter().filter_map(|o| o.as_ref())
34 }
35
36 pub fn values_mut(&mut self) -> impl Iterator<Item = &mut T> {
37 self.v.iter_mut().filter_map(|o| o.as_mut())
38 }
39
40 pub fn iter(&self) -> impl Iterator<Item = (ID, &T)> {
41 self.v
42 .iter()
43 .enumerate()
44 .filter_map(|(idx, o)| Some((Self::from_idx(idx), o.as_ref()?)))
45 }
46
47 fn to_idx(id: ID) -> usize {
48 u32::from(id.into_raw()) as usize
49 }
50
51 fn from_idx(idx: usize) -> ID {
52 ID::from_raw((idx as u32).into())
53 }
54}
55
56impl<ID: ArenaId, T> std::ops::Index<ID> for ArenaMap<ID, T> {
57 type Output = T;
58 fn index(&self, id: ID) -> &T {
59 self.v[Self::to_idx(id)].as_ref().unwrap()
60 }
61}
62
63impl<ID, T> Default for ArenaMap<ID, T> {
64 fn default() -> Self {
65 ArenaMap {
66 v: Vec::new(),
67 _ty: PhantomData,
68 }
69 }
70}