use downcast_rs::Downcast;
use std;
use std::any::Any;
use std::collections::HashMap;
pub type ResourceId = u32;
type ResourceMap = HashMap<ResourceId, Box<dyn Resource>>;
#[derive(Default)]
pub struct ResourceTable {
pub map: ResourceMap,
next_id: u32,
}
impl ResourceTable {
pub fn get<T: Resource>(&self, rid: ResourceId) -> Option<&T> {
if let Some(resource) = self.map.get(&rid) {
return resource.downcast_ref::<T>();
}
None
}
pub fn get_mut<T: Resource>(&mut self, rid: ResourceId) -> Option<&mut T> {
if let Some(resource) = self.map.get_mut(&rid) {
return resource.downcast_mut::<T>();
}
None
}
fn next_rid(&mut self) -> ResourceId {
let next_rid = self.next_id;
self.next_id += 1;
next_rid as ResourceId
}
pub fn add(&mut self, resource: Box<dyn Resource>) -> ResourceId {
let rid = self.next_rid();
let r = self.map.insert(rid, resource);
assert!(r.is_none());
rid
}
pub fn entries(&self) -> Vec<(ResourceId, String)> {
self
.map
.iter()
.map(|(key, value)| (*key, value.inspect_repr().to_string()))
.collect()
}
pub fn close(&mut self, rid: ResourceId) -> Option<()> {
if let Some(resource) = self.map.remove(&rid) {
resource.close();
return Some(());
}
None
}
}
pub trait Resource: Downcast + Any + Send {
fn close(&self) {}
fn inspect_repr(&self) -> &str;
}
impl_downcast!(Resource);