retdec
caching.h
Go to the documentation of this file.
1 
7 #ifndef RETDEC_LLVMIR2HLL_SUPPORT_CACHING_H
8 #define RETDEC_LLVMIR2HLL_SUPPORT_CACHING_H
9 
10 #include <unordered_map>
11 
12 namespace retdec {
13 namespace llvmir2hll {
14 
49 template<typename CachedKey, typename CachedValue,
50  typename HashFunc = std::hash<CachedKey>>
51 class Caching {
52 public:
54 
60  void enableCaching() {
61  cachingEnabled = true;
62  clearCache();
63  }
64 
70  void disableCaching() {
71  cachingEnabled = false;
72  clearCache();
73  }
74 
78  void clearCache() {
79  cache.clear();
80  }
81 
88  void removeFromCache(const CachedKey &key) {
89  cache.erase(key);
90  }
91 
95  bool isCachingEnabled() const {
96  return cachingEnabled;
97  }
98 
99 protected:
103  void addToCache(const CachedKey &key, const CachedValue &value) {
104  if (cachingEnabled) {
105  cache[key] = value;
106  }
107  }
108 
118  bool getCachedResult(const CachedKey &key, CachedValue &value) const {
119  if (cachingEnabled) {
120  auto it = cache.find(key);
121  if (it != cache.end()) {
122  value = it->second;
123  return true;
124  }
125  }
126  return false;
127  }
128 
129 private:
131  // For performance reasons, it is better to use an unordered_map (i.e. a
132  // hash table) instead of a sorted map (i.e. std::map). The reason is that
133  // a std::map can retrieve a value associated to a key in O(log(n)), where
134  // n is the number of items in the map, while an unordered_map can do this
135  // in O(1). Insertions into the maps have the same complexities.
136  using Cache = std::unordered_map<CachedKey, CachedValue, HashFunc>;
137 
138 private:
141 
144 };
145 
146 } // namespace llvmir2hll
147 } // namespace retdec
148 
149 #endif
A mixin for enabling caching of computed results.
Definition: caching.h:51
Cache cache
Cache for storing cached results.
Definition: caching.h:143
void enableCaching()
Enables caching.
Definition: caching.h:60
void clearCache()
Clears the cache of the already cached results.
Definition: caching.h:78
void disableCaching()
Disables caching.
Definition: caching.h:70
bool isCachingEnabled() const
Returns true if caching is enabled, false otherwise.
Definition: caching.h:95
Caching(bool enableCaching)
Definition: caching.h:53
bool getCachedResult(const CachedKey &key, CachedValue &value) const
If caching is enabled, stores the value associated with key into value.
Definition: caching.h:118
std::unordered_map< CachedKey, CachedValue, HashFunc > Cache
Container for storing cached results.
Definition: caching.h:136
void removeFromCache(const CachedKey &key)
Removes the value corresponding to the given key from the cache.
Definition: caching.h:88
bool cachingEnabled
Is caching enabled?
Definition: caching.h:140
void addToCache(const CachedKey &key, const CachedValue &value)
If caching is enabled, associates the given value with key.
Definition: caching.h:103
A library providing API for working with back-end IR.
Definition: archive_wrapper.h:19