1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use std::borrow::Borrow;
use std::future::Future;
use std::hash::Hash;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::core::{CacheCore, ExpireEntry};
struct ExpiresAt;
impl<V> ExpireEntry<ExpiringEntry<V>> for ExpiresAt {
fn is_fresh(&self, entry: &ExpiringEntry<V>) -> bool {
entry.is_fresh()
}
}
#[derive(Clone, Debug)]
struct ExpiringEntry<T> {
entry: T,
expires_at: Instant,
}
impl<T> ExpiringEntry<T> {
fn fresh(entry: T, time_to_live: Duration) -> Self {
Self {
entry,
expires_at: Instant::now() + time_to_live,
}
}
fn into_entry(self) -> T {
self.entry
}
fn is_fresh(&self) -> bool {
Instant::now() < self.expires_at
}
}
#[derive(Clone, Debug)]
pub struct TimedCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
time_to_live: Duration,
core: Arc<CacheCore<K, ExpiringEntry<V>>>,
}
impl<K, V> TimedCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
pub fn new(time_to_live: Duration) -> Self {
Self {
time_to_live,
core: Arc::new(CacheCore::new()),
}
}
pub fn read<BK>(&self, key: &BK) -> Option<V>
where
BK: Hash + Eq + ?Sized,
K: Borrow<BK>,
{
self.core
.read(key, &ExpiresAt)
.map(ExpiringEntry::into_entry)
}
pub async fn write<F, E>(&self, key: K, future: F) -> Result<V, E>
where
F: Future<Output = Result<V, E>>,
{
let time_to_live = self.time_to_live;
let entry = self
.core
.write(
key,
async move {
let value = future.await?;
Ok(ExpiringEntry::fresh(value, time_to_live))
},
&ExpiresAt,
)
.await?;
Ok(entry.into_entry())
}
}