From ef1c9f121e9937720661d0aeecf65542f25c581f Mon Sep 17 00:00:00 2001 From: Zaidoon Abd Al Hadi Date: Tue, 29 Oct 2024 02:24:57 -0400 Subject: add support for removing items from pingora-memory-cache --- .bleep | 2 +- pingora-memory-cache/src/lib.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/.bleep b/.bleep index bd43cdc..f638b17 100644 --- a/.bleep +++ b/.bleep @@ -1 +1 @@ -d715e2d7a34ba00f8872339d4596b2e1e68de304 \ No newline at end of file +bbcce2850360af2c4b60120842701a1dd86b35cc \ No newline at end of file diff --git a/pingora-memory-cache/src/lib.rs b/pingora-memory-cache/src/lib.rs index b6e78bd..22f354d 100644 --- a/pingora-memory-cache/src/lib.rs +++ b/pingora-memory-cache/src/lib.rs @@ -130,6 +130,12 @@ impl MemoryCache { self.store.put(hashed_key, node, 1); } + /// Remove a key from the cache if it exists. + pub fn remove(&self, key: &K) { + let hashed_key = self.hasher.hash_one(key); + self.store.remove(&hashed_key); + } + pub(crate) fn force_put(&self, key: &K, value: T, ttl: Option) { if let Some(t) = ttl { if t.is_zero() { @@ -201,6 +207,31 @@ mod tests { assert_eq!(hit, CacheStatus::Hit); } + #[test] + fn test_put_get_remove() { + let cache: MemoryCache = MemoryCache::new(10); + let (res, hit) = cache.get(&1); + assert_eq!(res, None); + assert_eq!(hit, CacheStatus::Miss); + cache.put(&1, 2, None); + cache.put(&3, 4, None); + cache.put(&5, 6, None); + let (res, hit) = cache.get(&1); + assert_eq!(res.unwrap(), 2); + assert_eq!(hit, CacheStatus::Hit); + cache.remove(&1); + cache.remove(&3); + let (res, hit) = cache.get(&1); + assert_eq!(res, None); + assert_eq!(hit, CacheStatus::Miss); + let (res, hit) = cache.get(&3); + assert_eq!(res, None); + assert_eq!(hit, CacheStatus::Miss); + let (res, hit) = cache.get(&5); + assert_eq!(res.unwrap(), 6); + assert_eq!(hit, CacheStatus::Hit); + } + #[test] fn test_get_expired() { let cache: MemoryCache = MemoryCache::new(10); -- cgit v1.2.3