Skip to content

Commit

Permalink
feat: add some func to TypeMap (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
wzekin authored Mar 1, 2023
1 parent ff933c1 commit 38c8170
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/type_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ pub struct Entry<'a, K: 'a, V: 'a> {
}

impl<'a, K, V> Entry<'a, K, V> {
#[inline]
pub fn or_insert(self, default: V) -> &'a mut V
where
V: Send + Sync + 'static,
{
let v = self.inner.or_insert(Box::new(default));
v.downcast_mut().unwrap()
}

#[inline]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
where
Expand All @@ -22,6 +31,36 @@ impl<'a, K, V> Entry<'a, K, V> {
let v = self.inner.or_insert_with(|| Box::new(default()));
v.downcast_mut().unwrap()
}

#[inline]
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
where
V: Send + Sync + 'static,
{
let v = self.inner.or_insert_with_key(|key| Box::new(default(key)));
v.downcast_mut().unwrap()
}

#[inline]
pub fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Self
where
V: Send + Sync + 'static,
{
Entry {
inner: self.inner.and_modify(|v| {
f(v.downcast_mut().unwrap());
}),
_marker: PhantomData,
}
}

#[inline]
pub fn or_default(self) -> &'a mut V
where
V: Default + Send + Sync + 'static,
{
self.or_insert(V::default())
}
}

#[derive(Debug, Default)]
Expand All @@ -42,6 +81,13 @@ impl TypeMap {
.and_then(|boxed| boxed.downcast_ref())
}

#[inline]
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.inner
.get_mut(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_mut())
}

#[inline]
pub fn contains<T: 'static>(&self) -> bool {
self.inner.contains_key(&TypeId::of::<T>())
Expand Down

0 comments on commit 38c8170

Please sign in to comment.