use std::any::Any;
use std::collections::HashMap;
use std::sync::RwLock;
use std::any::TypeId;
use super::capability::Capability;
use super::handle::ResourceHandle;
#[must_use]
pub struct ResourceRegistry {
resources: RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>,
}
impl ResourceRegistry {
pub fn new() -> Self {
Self {
resources: RwLock::new(HashMap::new()),
}
}
pub fn register<H: ResourceHandle + 'static>(&self, capability: Capability<H>) {
let mut resources = self.resources.write().unwrap();
resources.insert(TypeId::of::<H>(), Box::new(capability));
}
pub fn get<H: ResourceHandle + 'static>(&self) -> Option<Capability<H>> {
let resources = self.resources.read().unwrap();
resources.get(&TypeId::of::<H>())
.and_then(|any| any.downcast_ref::<Capability<H>>())
.cloned()
}
pub fn remove<H: ResourceHandle + 'static>(&self) -> Option<Capability<H>> {
let mut resources = self.resources.write().unwrap();
resources.remove(&TypeId::of::<H>())
.and_then(|any| {
let boxed = any.downcast::<Capability<H>>().ok()?;
Some(*boxed)
})
}
pub fn has<H: ResourceHandle + 'static>(&self) -> bool {
let resources = self.resources.read().unwrap();
resources.contains_key(&TypeId::of::<H>())
}
}
impl Default for ResourceRegistry {
fn default() -> Self {
Self::new()
}
}