use std::{
any::{Any, TypeId},
collections::HashMap,
fmt,
sync::{Arc, PoisonError, RwLock},
};
type Stored = Arc<dyn Any + Send + Sync>;
#[derive(Clone, Default)]
pub struct RequestCache {
entries: Arc<RwLock<HashMap<TypeId, Stored>>>,
}
impl RequestCache {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn get<T>(&self) -> Option<Arc<T>>
where
T: Any + Send + Sync,
{
let entry = {
let entries = self.entries.read().unwrap_or_else(PoisonError::into_inner);
entries.get(&TypeId::of::<T>()).map(Arc::clone)
};
#[cfg(feature = "tracing")]
if tracing::enabled!(target: "gurafi::cache", tracing::Level::TRACE) {
tracing::trace!(
target: "gurafi::cache",
hit = entry.is_some(),
"gurafi.cache.lookup"
);
}
entry?.downcast::<T>().ok()
}
pub fn get_or_insert_with<T>(&self, init: impl FnOnce() -> T) -> Arc<T>
where
T: Any + Send + Sync,
{
if let Some(existing) = self.get::<T>() {
return existing;
}
let mut entries = self.entries.write().unwrap_or_else(PoisonError::into_inner);
if let Some(existing) = entries.get(&TypeId::of::<T>()) {
if let Ok(typed) = Arc::clone(existing).downcast::<T>() {
return typed;
}
}
let value = Arc::new(init());
entries.insert(TypeId::of::<T>(), Arc::clone(&value) as Stored);
#[cfg(feature = "tracing")]
if tracing::enabled!(target: "gurafi::cache", tracing::Level::TRACE) {
tracing::trace!(
target: "gurafi::cache",
hit = false,
inserted = true,
"gurafi.cache.lookup"
);
}
value
}
pub fn insert<T>(&self, value: T) -> Option<Arc<T>>
where
T: Any + Send + Sync,
{
let previous = {
let mut entries = self.entries.write().unwrap_or_else(PoisonError::into_inner);
entries.insert(TypeId::of::<T>(), Arc::new(value) as Stored)
};
previous.and_then(|entry| entry.downcast::<T>().ok())
}
pub fn remove<T>(&self) -> Option<Arc<T>>
where
T: Any + Send + Sync,
{
let entry = {
let mut entries = self.entries.write().unwrap_or_else(PoisonError::into_inner);
entries.remove(&TypeId::of::<T>())
};
entry?.downcast::<T>().ok()
}
#[must_use]
pub fn contains<T>(&self) -> bool
where
T: Any + Send + Sync,
{
self.entries
.read()
.unwrap_or_else(PoisonError::into_inner)
.contains_key(&TypeId::of::<T>())
}
pub fn clear(&self) {
self.entries
.write()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
#[must_use]
pub fn len(&self) -> usize {
self.entries
.read()
.unwrap_or_else(PoisonError::into_inner)
.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl fmt::Debug for RequestCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RequestCache")
.field("entries", &self.len())
.finish()
}
}