diff --git a/src/main.rs b/src/main.rs index dd61d9e..b99b103 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,7 @@ use color_eyre::{ use futures::Future; mod sock; +mod store; mod config; fn setup() -> eyre::Result<()> diff --git a/src/store.rs b/src/store.rs new file mode 100644 index 0000000..4da155b --- /dev/null +++ b/src/store.rs @@ -0,0 +1,58 @@ +//! Arbitrary object store +use std::any::{ + TypeId, + Any, +}; +use std::collections::HashMap; + +/// Arbitrarily typed singleton store. +/// +/// Stores one object per type. +#[derive(Debug)] +pub struct SingletonStore +{ + objects: HashMap>, +} + +#[inline] fn unbox_to(b: Box) -> Option +{ + b.downcast().map(|ok| *ok).ok() +} + +impl SingletonStore +{ + pub fn has(&self) -> bool + { + self.objects.contains_key(&TypeId::of::()) + } + + pub fn remove(&mut self) -> Option + { + self.objects.remove(&TypeId::of::()) + .and_then(|x| x.downcast().ok()) + .map(|x| *x) + } + pub fn insert(&mut self, value: T) -> Option + { + self.objects.insert(TypeId::of::(), Box::new(value)) + .and_then(unbox_to) + } + + pub fn get_mut(&mut self) -> Option<&mut T> + { + self.objects.get_mut(&TypeId::of::()) + .and_then(|x| x.downcast_mut()) + } + pub fn get(&self) -> Option<&T> + { + self.objects.get(&TypeId::of::()) + .and_then(|x| x.downcast_ref()) + } + + pub fn new() -> Self + { + Self { + objects: HashMap::new(), + } + } +}