use std::collections::HashMap;
use std::fmt;
use std::sync::RwLock;
use std::{
any::{Any, TypeId},
hash::{BuildHasherDefault, Hasher},
};
type AnyVal = Box<dyn Any + Send + Sync>;
type AnyHashMap = RwLock<HashMap<TypeId, AnyVal, BuildHasherDefault<IdHasher>>>;
#[derive(Default)]
struct IdHasher(u64);
impl Hasher for IdHasher {
#[inline]
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, _: &[u8]) {
unreachable!("TypeId calls write_u64");
}
#[inline]
fn write_u64(&mut self, id: u64) {
self.0 = id;
}
}
#[derive(Default)]
pub struct Extensions {
map: AnyHashMap,
}
impl Extensions {
#[inline]
pub fn new() -> Extensions {
Extensions {
map: AnyHashMap::default(),
}
}
pub fn insert<T: Send + Sync + Clone + 'static>(&self, val: T) -> Option<T> {
self.map
.write()
.unwrap()
.insert(TypeId::of::<T>(), Box::new(val))
.and_then(|v| v.downcast().ok().map(|boxed| *boxed))
}
pub fn get<T: Send + Sync + Clone + 'static>(&self) -> Option<T> {
self.map
.read()
.unwrap()
.get(&TypeId::of::<T>())
.and_then(|v| v.downcast_ref::<T>())
.cloned()
}
pub fn remove<T: Send + Sync + 'static>(&self) -> Option<T> {
self.map
.write()
.unwrap()
.remove(&TypeId::of::<T>())
.and_then(|v| v.downcast().ok().map(|boxed| *boxed))
}
#[inline]
pub fn clear(&self) {
self.map.write().unwrap().clear();
}
#[inline]
pub fn is_empty(&self) -> bool {
self.map.read().unwrap().is_empty()
}
#[inline]
pub fn len(&self) -> usize {
self.map.read().unwrap().len()
}
}
impl fmt::Debug for Extensions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Extensions").finish()
}
}
#[test]
fn test_extensions() {
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
struct MyType(i32);
#[derive(Debug, PartialEq)]
struct ComplexSharedType(u64);
let shared = Arc::new(ComplexSharedType(20));
let extensions = Extensions::new();
extensions.insert(5i32);
extensions.insert(MyType(10));
extensions.insert(shared.clone());
assert_eq!(extensions.get(), Some(5i32));
assert_eq!(extensions.get::<Arc<ComplexSharedType>>(), Some(shared));
assert_eq!(extensions.remove::<i32>(), Some(5i32));
assert!(extensions.get::<i32>().is_none());
assert!(extensions.get::<bool>().is_none());
assert_eq!(extensions.get(), Some(MyType(10)));
}