From fe4418bc0d0f1d34b8e57f6bb13d399aed7c2cb6 Mon Sep 17 00:00:00 2001 From: Joshua Barretto Date: Fri, 27 Mar 2020 13:18:16 +0000 Subject: [PATCH] Added store --- common/src/lib.rs | 1 + common/src/store.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 common/src/store.rs diff --git a/common/src/lib.rs b/common/src/lib.rs index f8da49935d..c9c27fc778 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -34,6 +34,7 @@ pub mod terrain; pub mod util; pub mod vol; pub mod volumes; +pub mod store; /// The networking module containing high-level wrappers of `TcpListener` and /// `TcpStream` (`PostOffice` and `PostBox` respectively) and data types used by diff --git a/common/src/store.rs b/common/src/store.rs new file mode 100644 index 0000000000..cb0916691c --- /dev/null +++ b/common/src/store.rs @@ -0,0 +1,61 @@ +use std::{ + fmt, + hash, + cmp::{PartialEq, Eq}, + marker::PhantomData, +}; + +pub struct Id(usize, PhantomData); + +impl Id { + pub fn id(&self) -> usize { self.0 } +} + +impl Copy for Id {} +impl Clone for Id { + fn clone(&self) -> Self { Self(self.0, PhantomData) } +} +impl Eq for Id {} +impl PartialEq for Id { + fn eq(&self, other: &Self) -> bool { self.0 == other.0 } +} +impl fmt::Debug for Id { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Id<{}>({})", std::any::type_name::(), self.0) + } +} +impl hash::Hash for Id { + fn hash(&self, h: &mut H) { + self.0.hash(h); + } +} + +pub struct Store { + items: Vec, +} + +impl Default for Store { + fn default() -> Self { Self { items: Vec::new() } } +} + +impl Store { + pub fn get(&self, id: Id) -> &T { self.items.get(id.0).unwrap() } + + pub fn get_mut(&mut self, id: Id) -> &mut T { self.items.get_mut(id.0).unwrap() } + + pub fn iter(&self) -> impl Iterator { self.items.iter() } + + pub fn iter_ids(&self) -> impl Iterator, &T)> { + self + .items + .iter() + .enumerate() + .map(|(i, item)| (Id(i, PhantomData), item)) + } + + pub fn insert(&mut self, item: T) -> Id { + let id = Id(self.items.len(), PhantomData); + self.items.push(item); + id + } +}