use std::any::Any;
use std::fmt;
use std::sync::Arc;
use crate::error::ValueResult;
pub trait Resource: Send + Sync + fmt::Debug + 'static {
fn close(&self) -> ValueResult<()>;
fn is_closed(&self) -> bool;
fn resource_type(&self) -> &'static str;
fn as_any(&self) -> &dyn Any;
}
#[derive(Clone)]
pub struct ResourceHandle(pub Arc<dyn Resource>);
impl fmt::Debug for ResourceHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Resource({})", self.0.resource_type())
}
}
impl ResourceHandle {
pub fn new(r: impl Resource) -> Self {
Self(Arc::new(r))
}
pub fn close(&self) -> ValueResult<()> {
self.0.close()
}
pub fn is_closed(&self) -> bool {
self.0.is_closed()
}
pub fn resource_type(&self) -> &'static str {
self.0.resource_type()
}
pub fn downcast<T: Resource>(&self) -> Option<&T> {
self.0.as_any().downcast_ref::<T>()
}
}