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

Commit

Permalink
fix(cache): address PR comments
Browse files Browse the repository at this point in the history
- Reverses items sorted by elapsed, to drop the oldest.
- Refactors item so that elapsed does not overflow.
  • Loading branch information
oetyng committed Jun 4, 2021
1 parent 67010e1 commit 1e6c0c4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
26 changes: 19 additions & 7 deletions src/cache/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,36 @@ use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct Item<T> {
pub object: T,
expiry: Option<Instant>,
time: Option<Time>,
}

#[derive(Clone, Copy, Debug)]
struct Time {
pub(crate) start: Instant,
pub(crate) expiry: Instant,
}

impl<T> Item<T> {
pub fn new(object: T, item_duration: Option<Duration>) -> Self {
let expiry = item_duration.map(|duration| Instant::now() + duration);
Item { object, expiry }
let time = item_duration.map(|duration| {
let start = Instant::now();
Time {
start,
expiry: start + duration,
}
});
Item { object, time }
}

pub fn expired(&self) -> bool {
self.expiry
.map(|expiry| expiry < Instant::now())
self.time
.map(|time| time.expiry < Instant::now())
.unwrap_or(false)
}

pub fn elapsed(&self) -> u128 {
self.expiry
.map(|expiry| Instant::now() - expiry)
self.time
.map(|time| Instant::now() - time.start)
.unwrap_or_default()
.as_millis()
}
Expand Down
5 changes: 4 additions & 1 deletion src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,18 @@ where
}
}

/// removes keys beyond capacity
async fn drop_excess(&self) {
let len = self.len().await;
if len > self.capacity {
let excess = len - self.capacity;
let read_items = self.items.read().await;
let mut items = read_items.iter().collect_vec();

items.sort_by(|(_, item_a), (_, item_b)| item_a.elapsed().cmp(&item_b.elapsed()));
// reversed sort
items.sort_by(|(_, item_a), (_, item_b)| item_b.elapsed().cmp(&item_a.elapsed()));

// take the excess
for (key, _) in items.iter().take(excess) {
let _ = self.items.write().await.remove(key);
}
Expand Down

0 comments on commit 1e6c0c4

Please sign in to comment.