Skip to content
This repository has been archived by the owner on Jun 25, 2021. It is now read-only.

Commit

Permalink
Merge 75db37b into 2ff32ce
Browse files Browse the repository at this point in the history
  • Loading branch information
maqi authored Jun 5, 2021
2 parents 2ff32ce + 75db37b commit 7d189fd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
1 change: 1 addition & 0 deletions src/cache/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ mod tests {
#[tokio::test]
async fn expired_when_duration_is_zero() {
let item = Item::new(OBJECT, Some(Duration::new(0, 0)));
tokio::time::sleep(Duration::new(0, 0)).await;
assert_eq!(item.expired(), true);
}
}
24 changes: 14 additions & 10 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use tokio::sync::RwLock;
#[derive(Debug)]
pub struct Cache<T, V>
where
T: Hash + Eq,
T: Hash + Eq + Copy,
{
items: RwLock<BTreeMap<T, Item<V>>>,
item_duration: Option<Duration>,
Expand All @@ -29,7 +29,7 @@ where
#[allow(clippy::len_without_is_empty)]
impl<T, V> Cache<T, V>
where
T: Ord + Hash,
T: Ord + Hash + Copy,
{
/// Creating capacity based `Cache`.
pub fn with_capacity(capacity: usize) -> Self {
Expand Down Expand Up @@ -110,16 +110,20 @@ where
}

///
#[allow(unused_assignments)]
pub async fn remove_expired(&self) {
let read_items = self.items.read().await;
let expired_keys: Vec<_> = read_items
.iter()
.filter(|(_, item)| item.expired())
.map(|(key, _)| key)
.collect();
let mut expired_keys = Vec::new();
{
let read_items = self.items.read().await;
expired_keys = read_items
.iter()
.filter(|(_, item)| item.expired())
.map(|(key, _)| *key)
.collect();
}

for key in expired_keys {
let _ = self.items.write().await.remove(key);
let _ = self.items.write().await.remove(&key);
}
}

Expand Down Expand Up @@ -208,7 +212,7 @@ mod tests {
#[tokio::test]
async fn remove_expired_item() {
let cache = Cache::with_expiry_duration(Duration::from_secs(0));
let _ = cache.set(KEY, VALUE, None).await;
assert!(cache.set(KEY, VALUE, None).await.is_none());
cache.remove_expired().await;
assert!(
cache.items.read().await.get(&KEY).is_none(),
Expand Down

0 comments on commit 7d189fd

Please sign in to comment.