timecache.rs (1036B)
1 use std::rc::Rc; 2 use std::time::{Duration, Instant}; 3 4 #[derive(Clone)] 5 pub struct TimeCached<T> { 6 last_update: Instant, 7 expires_in: Duration, 8 value: Option<T>, 9 refresh: Rc<dyn Fn() -> T + 'static>, 10 } 11 12 impl<T> TimeCached<T> { 13 pub fn new(expires_in: Duration, refresh: impl Fn() -> T + 'static) -> Self { 14 TimeCached { 15 last_update: Instant::now(), 16 expires_in, 17 value: None, 18 refresh: Rc::new(refresh), 19 } 20 } 21 22 pub fn needs_update(&self) -> bool { 23 self.value.is_none() || self.last_update.elapsed() > self.expires_in 24 } 25 26 pub fn update(&mut self) { 27 self.last_update = Instant::now(); 28 self.value = Some((self.refresh)()); 29 } 30 31 pub fn get(&self) -> Option<&T> { 32 self.value.as_ref() 33 } 34 35 pub fn get_mut(&mut self) -> &T { 36 if self.needs_update() { 37 self.update(); 38 } 39 self.value.as_ref().unwrap() // This unwrap is safe because we just set the value if it was None. 40 } 41 }