refactor(registry): use globals instead of storing in event loop

This commit is contained in:
Nova
2022-06-12 00:51:12 -04:00
parent 3ef45a1041
commit 01971b5048
4 changed files with 39 additions and 47 deletions

View File

@@ -1,19 +1,27 @@
use anyhow::{anyhow, Result};
use slab::{Iter, Slab};
use std::sync::Arc;
use std::sync::RwLock;
pub struct Registry<T>(RwLock<Slab<T>>);
pub trait RegistryEntry {
fn store_idx(&self, idx: usize);
}
impl<T> Registry<T> {
pub fn add(&self, t: T) -> Result<usize> {
Ok(self
pub struct Registry<T: RegistryEntry>(RwLock<Slab<Arc<T>>>);
impl<T: RegistryEntry> Registry<T> {
pub fn add(&self, t: T) -> Result<Arc<T>> {
let t_arc = Arc::new(t);
let idx = self
.0
.write()
.ok()
.ok_or_else(|| anyhow!("Registry has been poisoned"))?
.insert(t))
.insert(t_arc.clone());
t_arc.store_idx(idx);
Ok(t_arc)
}
pub fn iterate<F: FnOnce(Iter<'_, T>)>(&self, closure: F) -> Result<()> {
pub fn iterate<F: FnOnce(Iter<'_, Arc<T>>)>(&self, closure: F) -> Result<()> {
closure(
self.0
.read()
@@ -23,17 +31,12 @@ impl<T> Registry<T> {
);
Ok(())
}
pub fn remove(&self, index: usize) -> Result<T> {
Ok(self
.0
.write()
.ok()
.ok_or_else(|| anyhow!("Registry has been poisoned"))?
.remove(index))
pub fn remove(&self, index: usize) -> Result<T, Arc<T>> {
Arc::try_unwrap(self.0.write().unwrap().remove(index))
}
}
impl<T> Default for Registry<T> {
impl<T: RegistryEntry> Default for Registry<T> {
fn default() -> Self {
Registry::<T>(RwLock::new(Slab::new()))
}