use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::hash::{BuildHasherDefault, Hasher};
type AnyMap = HashMap<TypeId, Box<dyn AnyClone + Send + Sync>, BuildHasherDefault<IdHasher>>;
#[derive(Default)]
struct IdHasher(u64);
impl Hasher for IdHasher {
fn write(&mut self, _: &[u8]) {
unreachable!("TypeId calls write_u64");
}
#[inline]
fn write_u64(&mut self, id: u64) {
self.0 = id;
}
#[inline]
fn finish(&self) -> u64 {
self.0
}
}
#[derive(Clone, Default)]
pub struct Extensions {
map: Option<Box<AnyMap>>,
}
impl Extensions {
#[inline]
pub const fn new() -> Extensions {
Extensions { map: None }
}
pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
self.map
.get_or_insert_with(Box::default)
.insert(TypeId::of::<T>(), Box::new(val))
.and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
}
pub fn maybe_insert<T: Clone + Send + Sync + 'static>(
&mut self,
mut val: Option<T>,
) -> Option<T> {
val.take().and_then(|val| self.insert(val))
}
pub fn extend(&mut self, other: Extensions) {
if let Some(other_map) = other.map {
let map = self.map.get_or_insert_with(Box::default);
#[allow(clippy::useless_conversion)]
map.extend(other_map.into_iter());
}
}
pub fn clear(&mut self) {
if let Some(map) = self.map.as_mut() {
map.clear();
}
}
pub fn contains<T: Send + Sync + 'static>(&self) -> bool {
self.map
.as_ref()
.map(|map| map.contains_key(&TypeId::of::<T>()))
.unwrap_or_default()
}
pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.map
.as_ref()
.and_then(|map| map.get(&TypeId::of::<T>()))
.and_then(|boxed| (**boxed).as_any().downcast_ref())
}
pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
self.map
.as_mut()
.and_then(|map| map.get_mut(&TypeId::of::<T>()))
.and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
}
pub fn get_or_insert_with_ext<T: Clone + Send + Sync + 'static>(
&mut self,
f: impl FnOnce(&Self) -> T,
) -> &mut T {
if self.contains::<T>() {
return self.get_mut().unwrap();
}
let v = f(self);
self.insert(v);
self.get_mut().unwrap()
}
pub fn get_or_insert_with<T: Send + Sync + Clone + 'static>(
&mut self,
f: impl FnOnce() -> T,
) -> &mut T {
let map = self.map.get_or_insert_with(Box::default);
let entry = map.entry(TypeId::of::<T>());
let boxed = entry.or_insert_with(|| Box::new(f()));
(**boxed)
.as_any_mut()
.downcast_mut()
.expect("type mismatch")
}
pub fn get_or_insert_from<T, U>(&mut self, src: U) -> &mut T
where
T: Send + Sync + Clone + 'static,
U: Into<T>,
{
let map = self.map.get_or_insert_with(Box::default);
let entry = map.entry(TypeId::of::<T>());
let boxed = entry.or_insert_with(|| Box::new(src.into()));
(**boxed)
.as_any_mut()
.downcast_mut()
.expect("type mismatch")
}
pub fn get_or_insert<T: Clone + Send + Sync + 'static>(&mut self, fallback: T) -> &mut T {
self.get_or_insert_with(|| fallback)
}
pub fn get_or_insert_default<T: Default + Clone + Send + Sync + 'static>(&mut self) -> &mut T {
self.get_or_insert_with(T::default)
}
pub fn remove<T: Clone + Send + Sync + 'static>(&mut self) -> Option<T> {
self.map
.as_mut()
.and_then(|map| map.remove(&TypeId::of::<T>()))
.and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
}
}
impl fmt::Debug for Extensions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Extensions").finish()
}
}
trait AnyClone: Any {
fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn into_any(self: Box<Self>) -> Box<dyn Any>;
}
impl<T: Clone + Send + Sync + 'static> AnyClone for T {
fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
}
impl Clone for Box<dyn AnyClone + Send + Sync> {
fn clone(&self) -> Self {
(**self).clone_box()
}
}
#[test]
fn test_extensions() {
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct MyType(i32);
let mut extensions = Extensions::new();
extensions.insert(5i32);
extensions.insert(MyType(10));
assert_eq!(extensions.get(), Some(&5i32));
let mut ext2 = extensions.clone();
ext2.insert(true);
assert_eq!(ext2.get(), Some(&5i32));
assert_eq!(ext2.get(), Some(&MyType(10)));
assert_eq!(ext2.get(), Some(&true));
let mut extensions = Extensions::new();
extensions.insert(5i32);
extensions.insert(MyType(10));
let mut extensions2 = Extensions::new();
extensions2.extend(extensions);
assert_eq!(extensions2.get(), Some(&5i32));
assert_eq!(extensions2.get(), Some(&MyType(10)));
extensions2.clear();
assert_eq!(extensions2.get::<i32>(), None);
assert_eq!(extensions2.get::<MyType>(), None);
}