use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use crate::binding::{Instance, downcast_instance, instance_of};
#[derive(Default)]
pub struct Extensions {
map: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
}
impl Extensions {
pub fn insert<T: Send + Sync + 'static>(&self, value: T) {
self.map().insert(TypeId::of::<T>(), Arc::new(value));
}
pub fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
let value = self.map().get(&TypeId::of::<T>()).cloned()?;
value.downcast::<T>().ok()
}
pub fn contains<T: Send + Sync + 'static>(&self) -> bool {
self.map().contains_key(&TypeId::of::<T>())
}
pub fn remove<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
let value = self.map().remove(&TypeId::of::<T>())?;
value.downcast::<T>().ok()
}
fn map(&self) -> MutexGuard<'_, HashMap<TypeId, Arc<dyn Any + Send + Sync>>> {
self.map.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Default)]
pub(crate) struct Seeded {
map: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
}
impl Seeded {
pub(crate) fn insert<T: Send + Sync + 'static>(&self, value: T) {
self.map().insert(TypeId::of::<T>(), instance_of(Arc::new(value)));
}
pub(crate) fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
let instance: Instance = self.map().get(&TypeId::of::<T>()).cloned()?;
downcast_instance::<T>(&instance)
}
pub(crate) fn get_erased(&self, ty: TypeId) -> Option<Arc<dyn Any + Send + Sync>> {
self.map().get(&ty).cloned()
}
fn map(&self) -> MutexGuard<'_, HashMap<TypeId, Arc<dyn Any + Send + Sync>>> {
self.map.lock().unwrap_or_else(PoisonError::into_inner)
}
}