diff --git a/src/lib.rs b/src/lib.rs index 90c9857..9d40c04 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ mod images; mod result; mod filter; mod ui; +mod timecache; mod frame_history; mod timeline; diff --git a/src/timecache.rs b/src/timecache.rs new file mode 100644 index 0000000..8fb626f --- /dev/null +++ b/src/timecache.rs @@ -0,0 +1,27 @@ +use std::time::{Duration, Instant}; + +pub struct TimeCached { + last_update: Instant, + expires_in: Duration, + value: Option, + refresh: Box T + 'static>, +} + +impl TimeCached { + pub fn new(expires_in: Duration, refresh: Box T + 'static>) -> Self { + TimeCached { + last_update: Instant::now(), + expires_in, + value: None, + refresh, + } + } + + pub fn get(&mut self) -> &T { + if self.value.is_none() || self.last_update.elapsed() > self.expires_in { + self.last_update = Instant::now(); + self.value = Some((self.refresh)()); + } + self.value.as_ref().unwrap() // This unwrap is safe because we just set the value if it was None. + } +}