From 4c4e54ac8a9782439744fe15aa31a3bedab92b74 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Thu, 14 Jan 2021 18:47:42 +0300 Subject: prepare to publish el libro de arena --- lib/arena/src/map.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 lib/arena/src/map.rs (limited to 'lib/arena/src/map.rs') 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 @@ +//! A map from arena IDs to some other type. Space requirement is O(highest ID). + +use std::marker::PhantomData; + +use crate::Idx; + +/// A map from arena IDs to some other type. Space requirement is O(highest ID). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ArenaMap { + v: Vec>, + _ty: PhantomData, +} + +impl ArenaMap, V> { + pub fn insert(&mut self, id: Idx, t: V) { + let idx = Self::to_idx(id); + + self.v.resize_with((idx + 1).max(self.v.len()), || None); + self.v[idx] = Some(t); + } + + pub fn get(&self, id: Idx) -> Option<&V> { + self.v.get(Self::to_idx(id)).and_then(|it| it.as_ref()) + } + + pub fn get_mut(&mut self, id: Idx) -> Option<&mut V> { + self.v.get_mut(Self::to_idx(id)).and_then(|it| it.as_mut()) + } + + pub fn values(&self) -> impl Iterator { + self.v.iter().filter_map(|o| o.as_ref()) + } + + pub fn values_mut(&mut self) -> impl Iterator { + self.v.iter_mut().filter_map(|o| o.as_mut()) + } + + pub fn iter(&self) -> impl Iterator, &V)> { + self.v.iter().enumerate().filter_map(|(idx, o)| Some((Self::from_idx(idx), o.as_ref()?))) + } + + fn to_idx(id: Idx) -> usize { + u32::from(id.into_raw()) as usize + } + + fn from_idx(idx: usize) -> Idx { + Idx::from_raw((idx as u32).into()) + } +} + +impl std::ops::Index> for ArenaMap, T> { + type Output = T; + fn index(&self, id: Idx) -> &T { + self.v[Self::to_idx(id)].as_ref().unwrap() + } +} + +impl Default for ArenaMap, T> { + fn default() -> Self { + ArenaMap { v: Vec::new(), _ty: PhantomData } + } +} -- cgit v1.2.3