commit 2f54a05705c278f9a678062592d544ec7eed60d4
parent 9a4f193e03ee93b802201d07fdc9ee338d53efa3
Author: William Casarin <jb55@jb55.com>
Date: Thu, 15 Feb 2024 12:58:19 -0800
timecache: add timecache help for timed caches
Some things we definitely don't want to generate every frame, such as
relative-time formatted strings, as that would create a heap allocation
each frame.
Introduce TimeCached<T> which is responsible for updating some state
after some expiry.
Signed-off-by: William Casarin <jb55@jb55.com>
Diffstat:
2 files changed, 28 insertions(+), 0 deletions(-)
diff --git 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
@@ -0,0 +1,27 @@
+use std::time::{Duration, Instant};
+
+pub struct TimeCached<T> {
+ last_update: Instant,
+ expires_in: Duration,
+ value: Option<T>,
+ refresh: Box<dyn Fn() -> T + 'static>,
+}
+
+impl<T> TimeCached<T> {
+ pub fn new(expires_in: Duration, refresh: Box<dyn Fn() -> 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.
+ }
+}