Line data Source code
1 : use std::ops::{Deref, DerefMut};
2 :
3 : /// A generic trait which exposes types of cache's key and value,
4 : /// as well as the notion of cache entry invalidation.
5 : /// This is useful for [`Cached`].
6 : pub trait Cache {
7 : /// Entry's key.
8 : type Key;
9 :
10 : /// Entry's value.
11 : type Value;
12 :
13 : /// Used for entry invalidation.
14 : type LookupInfo<Key>;
15 :
16 : /// Invalidate an entry using a lookup info.
17 : /// We don't have an empty default impl because it's error-prone.
18 : fn invalidate(&self, _: &Self::LookupInfo<Self::Key>);
19 : }
20 :
21 : impl<C: Cache> Cache for &C {
22 : type Key = C::Key;
23 : type Value = C::Value;
24 : type LookupInfo<Key> = C::LookupInfo<Key>;
25 :
26 0 : fn invalidate(&self, info: &Self::LookupInfo<Self::Key>) {
27 0 : C::invalidate(self, info)
28 0 : }
29 : }
30 :
31 : /// Wrapper for convenient entry invalidation.
32 : pub struct Cached<C: Cache, V = <C as Cache>::Value> {
33 : /// Cache + lookup info.
34 : pub token: Option<(C, C::LookupInfo<C::Key>)>,
35 :
36 : /// The value itself.
37 : pub value: V,
38 : }
39 :
40 : impl<C: Cache, V> Cached<C, V> {
41 : /// Place any entry into this wrapper; invalidation will be a no-op.
42 241 : pub fn new_uncached(value: V) -> Self {
43 241 : Self { token: None, value }
44 241 : }
45 :
46 : /// Drop this entry from a cache if it's still there.
47 19 : pub fn invalidate(self) -> V {
48 19 : if let Some((cache, info)) = &self.token {
49 0 : cache.invalidate(info);
50 19 : }
51 19 : self.value
52 19 : }
53 :
54 : /// Tell if this entry is actually cached.
55 34 : pub fn cached(&self) -> bool {
56 34 : self.token.is_some()
57 34 : }
58 : }
59 :
60 : impl<C: Cache, V> Deref for Cached<C, V> {
61 : type Target = V;
62 :
63 360 : fn deref(&self) -> &Self::Target {
64 360 : &self.value
65 360 : }
66 : }
67 :
68 : impl<C: Cache, V> DerefMut for Cached<C, V> {
69 193 : fn deref_mut(&mut self) -> &mut Self::Target {
70 193 : &mut self.value
71 193 : }
72 : }
|