Added time updates to CacheEntry.

This commit is contained in:
Jeff Baskin 2022-12-24 02:03:20 -05:00
parent f0f8e7455e
commit 56005a5e47
1 changed files with 85 additions and 2 deletions

View File

@ -7,7 +7,11 @@ use async_std::{
};
use error::DBError;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{collections::HashMap, fmt, str, time::Instant};
use std::{
collections::HashMap,
fmt, str,
time::{Duration, Instant},
};
const DATA: &str = "data";
@ -67,6 +71,19 @@ impl CacheEntry {
last_used: Instant::now(),
}
}
fn elapsed(&self) -> Duration {
self.last_used.elapsed()
}
fn touch(&mut self) {
self.last_used = Instant::now();
}
fn update(&mut self, data: CacheType) {
self.data = data;
self.touch();
}
}
impl fmt::Display for CacheEntry {
@ -349,7 +366,7 @@ mod cache {
}
#[cfg(test)]
mod cache_entry {
mod cache_type {
use super::*;
#[test]
@ -377,3 +394,69 @@ mod cache_entry {
assert_eq!(output.to_string(), holder.to_string());
}
}
#[cfg(test)]
mod cache_entry {
use super::*;
#[test]
fn init() {
let text = "new entry";
let holder = CacheEntry::new(CacheType::Raw(text.to_string()));
assert_eq!(holder.to_string(), text);
let held = holder.elapsed();
assert!(
Duration::from_secs(1) > held,
"Duration was {:?}, should have been close to 0s.",
held
);
}
#[test]
fn older() {
let secs = 800;
let holder = CacheEntry {
data: CacheType::Raw("older".to_string()),
last_used: Instant::now() - Duration::from_secs(secs),
};
let held = holder.elapsed() - Duration::from_secs(secs);
assert!(
Duration::from_secs(1) > held,
"{:?} should be close to {}s",
holder.elapsed(),
secs
);
}
#[test]
fn accessed() {
let mut holder = CacheEntry {
data: CacheType::Raw("older".to_string()),
last_used: Instant::now() - Duration::from_secs(700),
};
holder.touch();
let held = holder.elapsed();
assert!(
Duration::from_secs(1) > held,
"Duration was {:?}, should have been close to 0s.",
held
);
}
#[test]
fn updated() {
let text = "new data";
let mut holder = CacheEntry {
data: CacheType::Raw("old data".to_string()),
last_used: Instant::now() - Duration::from_secs(900),
};
holder.update(CacheType::Raw(text.to_string()));
assert_eq!(holder.to_string(), text);
let held = holder.elapsed();
assert!(
Duration::from_secs(1) > held,
"Duration was {:?}, should have been close to 0s.",
held
);
}
}