use crate::error::bad_resource_id;
use crate::error::not_supported;
use crate::ZeroCopyBuf;
use anyhow::Error;
use futures::Future;
use std::any::type_name;
use std::any::Any;
use std::any::TypeId;
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::iter::Iterator;
use std::pin::Pin;
use std::rc::Rc;
pub type AsyncResult<T> = Pin<Box<dyn Future<Output = Result<T, Error>>>>;
pub trait Resource: Any + 'static {
fn name(&self) -> Cow<str> {
type_name::<Self>().into()
}
fn read(self: Rc<Self>, _buf: ZeroCopyBuf) -> AsyncResult<usize> {
Box::pin(futures::future::err(not_supported()))
}
fn write(self: Rc<Self>, _buf: ZeroCopyBuf) -> AsyncResult<usize> {
Box::pin(futures::future::err(not_supported()))
}
fn shutdown(self: Rc<Self>) -> AsyncResult<()> {
Box::pin(futures::future::err(not_supported()))
}
fn close(self: Rc<Self>) {}
}
impl dyn Resource {
#[inline(always)]
fn is<T: Resource>(&self) -> bool {
self.type_id() == TypeId::of::<T>()
}
#[inline(always)]
#[allow(clippy::needless_lifetimes)]
pub fn downcast_rc<'a, T: Resource>(self: &'a Rc<Self>) -> Option<&'a Rc<T>> {
if self.is::<T>() {
let ptr = self as *const Rc<_> as *const Rc<T>;
Some(unsafe { &*ptr })
} else {
None
}
}
}
pub type ResourceId = u32;
#[derive(Default)]
pub struct ResourceTable {
index: BTreeMap<ResourceId, Rc<dyn Resource>>,
next_rid: ResourceId,
}
impl ResourceTable {
pub fn add<T: Resource>(&mut self, resource: T) -> ResourceId {
self.add_rc(Rc::new(resource))
}
pub fn add_rc<T: Resource>(&mut self, resource: Rc<T>) -> ResourceId {
let resource = resource as Rc<dyn Resource>;
let rid = self.next_rid;
let removed_resource = self.index.insert(rid, resource);
assert!(removed_resource.is_none());
self.next_rid += 1;
rid
}
pub fn has(&self, rid: ResourceId) -> bool {
self.index.contains_key(&rid)
}
pub fn get<T: Resource>(&self, rid: ResourceId) -> Result<Rc<T>, Error> {
self
.index
.get(&rid)
.and_then(|rc| rc.downcast_rc::<T>())
.map(Clone::clone)
.ok_or_else(bad_resource_id)
}
pub fn get_any(&self, rid: ResourceId) -> Result<Rc<dyn Resource>, Error> {
self
.index
.get(&rid)
.map(Clone::clone)
.ok_or_else(bad_resource_id)
}
pub fn take<T: Resource>(&mut self, rid: ResourceId) -> Result<Rc<T>, Error> {
let resource = self.get::<T>(rid)?;
self.index.remove(&rid);
Ok(resource)
}
pub fn take_any(
&mut self,
rid: ResourceId,
) -> Result<Rc<dyn Resource>, Error> {
self.index.remove(&rid).ok_or_else(bad_resource_id)
}
pub fn close(&mut self, rid: ResourceId) -> Result<(), Error> {
self
.index
.remove(&rid)
.ok_or_else(bad_resource_id)
.map(|resource| resource.close())
}
pub fn names(&self) -> impl Iterator<Item = (ResourceId, Cow<str>)> {
self
.index
.iter()
.map(|(&id, resource)| (id, resource.name()))
}
}