use std::sync::Arc;
use cachet_tier::CacheEntry;
type InsertPredicate<V> = Arc<dyn Fn(&CacheEntry<V>) -> bool + Send + Sync>;
#[derive(Debug)]
pub struct InsertPolicy<V>(PolicyType<V>);
enum PolicyType<V> {
Always,
Never,
When(InsertPredicate<V>),
}
impl<V> Default for InsertPolicy<V> {
fn default() -> Self {
Self::always()
}
}
impl<V> std::fmt::Debug for PolicyType<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Always => write!(f, "Always"),
Self::Never => write!(f, "Never"),
Self::When(_) => write!(f, "WhenBoxed(<closure>)"),
}
}
}
impl<V> InsertPolicy<V> {
#[must_use]
pub fn always() -> Self {
Self(PolicyType::Always)
}
#[must_use]
pub fn never() -> Self {
Self(PolicyType::Never)
}
pub fn when<F>(predicate: F) -> Self
where
F: Fn(&CacheEntry<V>) -> bool + Send + Sync + 'static,
{
Self(PolicyType::When(Arc::new(predicate)))
}
#[inline]
pub(crate) fn should_insert(&self, response: &CacheEntry<V>) -> bool {
match &self.0 {
PolicyType::Always => true,
PolicyType::Never => false,
PolicyType::When(pred) => pred(response),
}
}
}