aboutsummaryrefslogtreecommitdiff
path: root/lib/arena/src/map.rs
diff options
context:
space:
mode:
Diffstat (limited to 'lib/arena/src/map.rs')
-rw-r--r--lib/arena/src/map.rs62
1 files changed, 62 insertions, 0 deletions
diff --git a/lib/arena/src/map.rs b/lib/arena/src/map.rs
new file mode 100644
index 000000000..0f33907c0
--- /dev/null
+++ b/lib/arena/src/map.rs
@@ -0,0 +1,62 @@
1//! A map from arena IDs to some other type. Space requirement is O(highest ID).
2
3use std::marker::PhantomData;
4
5use crate::Idx;
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, V> {
10 v: Vec<Option<V>>,
11 _ty: PhantomData<ID>,
12}
13
14impl<T, V> ArenaMap<Idx<T>, V> {
15 pub fn insert(&mut self, id: Idx<T>, t: V) {
16 let idx = Self::to_idx(id);
17
18 self.v.resize_with((idx + 1).max(self.v.len()), || None);
19 self.v[idx] = Some(t);
20 }
21
22 pub fn get(&self, id: Idx<T>) -> Option<&V> {
23 self.v.get(Self::to_idx(id)).and_then(|it| it.as_ref())
24 }
25
26 pub fn get_mut(&mut self, id: Idx<T>) -> Option<&mut V> {
27 self.v.get_mut(Self::to_idx(id)).and_then(|it| it.as_mut())
28 }
29
30 pub fn values(&self) -> impl Iterator<Item = &V> {
31 self.v.iter().filter_map(|o| o.as_ref())
32 }
33
34 pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
35 self.v.iter_mut().filter_map(|o| o.as_mut())
36 }
37
38 pub fn iter(&self) -> impl Iterator<Item = (Idx<T>, &V)> {
39 self.v.iter().enumerate().filter_map(|(idx, o)| Some((Self::from_idx(idx), o.as_ref()?)))
40 }
41
42 fn to_idx(id: Idx<T>) -> usize {
43 u32::from(id.into_raw()) as usize
44 }
45
46 fn from_idx(idx: usize) -> Idx<T> {
47 Idx::from_raw((idx as u32).into())
48 }
49}
50
51impl<T, V> std::ops::Index<Idx<V>> for ArenaMap<Idx<V>, T> {
52 type Output = T;
53 fn index(&self, id: Idx<V>) -> &T {
54 self.v[Self::to_idx(id)].as_ref().unwrap()
55 }
56}
57
58impl<T, V> Default for ArenaMap<Idx<V>, T> {
59 fn default() -> Self {
60 ArenaMap { v: Vec::new(), _ty: PhantomData }
61 }
62}