any_cache/
lib.rs

1use std::any::{Any, TypeId};
2use std::collections::hash_map::{DefaultHasher, HashMap};
3use std::hash::{Hash, Hasher};
4
5/// A cache that can store abitrary values and namespace them by key types.
6pub trait Cache {
7  fn save<K>(&mut self, key: K, value: K::Target) where K::Target: Any + 'static, K: CacheKey;
8  fn get<K>(&self, key: &K) -> Option<&K::Target> where K::Target: Any + 'static, K: CacheKey;
9  fn remove<K>(&mut self, key: &K) -> Option<K::Target> where K::Target: Any + 'static, K: CacheKey;
10  fn clear(&mut self);
11}
12
13/// A key that is usable in a cache.
14///
15/// Cache keys are required to declare the type of values they reference. This is needed to
16/// implement type-level namespacing.
17pub trait CacheKey: 'static + Hash {
18  type Target;
19}
20
21/// An implementation of a cache with a `HashMap`.
22pub struct HashCache {
23  items: HashMap<u64, Box<Any>>
24}
25
26impl HashCache {
27  pub fn new() -> Self {
28    HashCache {
29      items: HashMap::new()
30    }
31  }
32}
33
34impl Default for HashCache {
35  fn default() -> Self {
36    Self::new()
37  }
38}
39
40impl Cache for HashCache {
41  fn save<K>(&mut self, key: K, value: K::Target) where K::Target: Any + 'static, K: CacheKey {
42    let mut hasher = DefaultHasher::new();
43    key.hash(&mut hasher);
44    TypeId::of::<K>().hash(&mut hasher);
45    self.items.insert(hasher.finish(), Box::new(value));
46  }
47
48  fn get<K>(&self, key: &K) -> Option<&K::Target> where K::Target: Any + 'static, K: CacheKey {
49    let mut hasher = DefaultHasher::new();
50    key.hash(&mut hasher);
51    TypeId::of::<K>().hash(&mut hasher);
52    self.items.get(&hasher.finish()).and_then(|a| { a.downcast_ref::<K::Target>() })
53  }
54
55  fn remove<K>(&mut self, key: &K) -> Option<K::Target> where K::Target: Any + 'static, K: CacheKey {
56    let mut hasher = DefaultHasher::new();
57    key.hash(&mut hasher);
58    TypeId::of::<K>().hash(&mut hasher);
59    self.items.remove(&hasher.finish()).and_then(|anybox| anybox.downcast().ok()).map(|b| *b)
60  }
61
62  fn clear(&mut self) {
63    self.items.clear();
64  }
65}
66
67/// An implementation of a cache that actually doesn’t cache at all.
68pub struct DummyCache;
69
70impl DummyCache {
71  pub fn new() -> Self {
72    DummyCache
73  }
74}
75
76impl Default for DummyCache {
77  fn default() -> Self {
78    DummyCache
79  }
80}
81
82impl Cache for DummyCache {
83  fn save<K>(&mut self, _: K, _: K::Target) where K::Target: Any + 'static, K: CacheKey {
84  }
85
86  fn get<K>(&self, _: &K) -> Option<&K::Target> where K::Target: Any + 'static, K: CacheKey {
87    None
88  }
89
90  fn remove<K>(&mut self, _: &K) -> Option<K::Target> where K::Target: Any + 'static, K: CacheKey {
91    None
92  }
93
94  fn clear(&mut self) {
95  }
96}