Skip to main content

matrix_bridge_telegram/
cache.rs

1use std::time::{Duration, Instant};
2
3pub struct TimedCache<T> {
4    data: Option<T>,
5    expires_at: Option<Instant>,
6    ttl: Duration,
7}
8
9impl<T> TimedCache<T> {
10    pub fn new(ttl: Duration) -> Self {
11        Self {
12            data: None,
13            expires_at: None,
14            ttl,
15        }
16    }
17
18    pub fn get(&self) -> Option<&T> {
19        if let Some(expires_at) = self.expires_at {
20            if Instant::now() < expires_at {
21                return self.data.as_ref();
22            }
23        }
24        None
25    }
26
27    pub fn set(&mut self, value: T) {
28        self.data = Some(value);
29        self.expires_at = Some(Instant::now() + self.ttl);
30    }
31
32    pub fn invalidate(&mut self) {
33        self.data = None;
34        self.expires_at = None;
35    }
36}
37
38impl<T: Clone> TimedCache<T> {
39    pub fn get_or_update<F>(&mut self, f: F) -> T
40    where
41        F: FnOnce() -> T,
42    {
43        if let Some(ref data) = self.data {
44            if let Some(expires_at) = self.expires_at {
45                if Instant::now() < expires_at {
46                    return data.clone();
47                }
48            }
49        }
50        let value = f();
51        self.set(value.clone());
52        value
53    }
54}