From 56005a5e47b159996df731fe0d72f89e865dd319 Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Sat, 24 Dec 2022 02:03:20 -0500 Subject: [PATCH] Added time updates to CacheEntry. --- src/morethantext/mod.rs | 87 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/src/morethantext/mod.rs b/src/morethantext/mod.rs index 5a2ccf7..a98ef12 100644 --- a/src/morethantext/mod.rs +++ b/src/morethantext/mod.rs @@ -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 + ); + } +}