use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use crate::capability::{HCons, HNil, need};
use crate::kernel::{Effect, fail, succeed};
type Slot = (&'static str, Arc<dyn Any + Send + Sync>);
#[derive(Clone, Default)]
pub struct DynEnv {
map: HashMap<TypeId, Slot>,
}
impl fmt::Debug for DynEnv {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut names: Vec<&str> = self.map.values().map(|(name, _)| *name).collect();
names.sort_unstable();
f.debug_struct("DynEnv")
.field("capabilities", &names)
.finish()
}
}
impl DynEnv {
pub fn new() -> Self {
Self::default()
}
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
self.insert_arc(Arc::new(value))
}
pub fn insert_arc<T: Send + Sync + 'static>(&mut self, value: Arc<T>) -> &mut Self {
self
.map
.insert(TypeId::of::<T>(), (std::any::type_name::<T>(), value));
self
}
#[must_use]
pub fn with<T: Send + Sync + 'static>(mut self, value: T) -> Self {
self.insert(value);
self
}
pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
let (_, slot) = self.map.remove(&TypeId::of::<T>())?;
slot.downcast::<T>().ok()
}
pub fn try_get<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, MissingCapability> {
self
.map
.get(&TypeId::of::<T>())
.and_then(|(_, slot)| Arc::clone(slot).downcast::<T>().ok())
.ok_or_else(MissingCapability::of::<T>)
}
pub fn contains<T: Send + Sync + 'static>(&self) -> bool {
self.map.contains_key(&TypeId::of::<T>())
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MissingCapability {
pub type_name: &'static str,
}
impl MissingCapability {
pub fn of<T: ?Sized>() -> Self {
Self {
type_name: std::any::type_name::<T>(),
}
}
}
impl fmt::Display for MissingCapability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"capability `{}` is not in the dynamic environment (`DynEnv`)",
self.type_name
)
}
}
impl std::error::Error for MissingCapability {}
pub fn try_need<T: Send + Sync + 'static>() -> Effect<Arc<T>, MissingCapability, HCons<DynEnv, HNil>>
{
need::<DynEnv>().flat_map(|env| match env.try_get::<T>() {
Ok(t) => succeed(t),
Err(e) => fail(e),
})
}