15 #include <unordered_map> 21 class HASH = std::hash<KEY>,
22 class PRED = std::equal_to<KEY>,
23 class ALLOC = std::allocator< std::pair<const KEY,T> >
27 std::unordered_map<KEY, T, HASH, PRED, ALLOC> cache_map;
43 size_t size()
const {
return cache_map.size(); }
46 bool Has(
const KEY & k)
const {
return cache_map.find(k) != cache_map.end(); }
49 void Clear() { cache_map.clear(); }
52 void Erase(
const KEY & k) { cache_map.erase(k); }
55 T
Get(KEY k,
const std::function<T(KEY k)> & calc_fun) {
56 auto cache_it = cache_map.find(k);
57 if (cache_it != cache_map.end())
return cache_it->second;
58 return cache_map.emplace(k, calc_fun(k)).first->second;
62 const T &
GetRef(
const KEY & k,
const std::function<T(
const KEY & k)> & calc_fun) {
63 auto cache_it = cache_map.find(k);
64 if (cache_it != cache_map.end())
return cache_it->second;
65 return cache_map.emplace(k, calc_fun(k)).first->second;
void Erase(const KEY &k)
Erase a specific entry from cache.
Definition: Cache.h:52
HASH hasher
Hash method to use.
Definition: Cache.h:38
ALLOC allocator_type
Function to allocate new space.
Definition: Cache.h:40
Cache & operator=(const Cache &)=default
T Get(KEY k, const std::function< T(KEY k)> &calc_fun)
Lookup a specific key; provide a function to use if value is not in cahce.
Definition: Cache.h:55
void Clear()
Erase contents of cache.
Definition: Cache.h:49
T mapped_type
Contents of the value we look up.
Definition: Cache.h:37
size_t size() const
How many entries are stored in the cache?
Definition: Cache.h:43
PRED key_equal
Function to test if two values are identical.
Definition: Cache.h:39
bool Has(const KEY &k) const
Determine if a specific key is already in the cache.
Definition: Cache.h:46
If we are in emscripten, make sure to include the header.
Definition: array.h:37
KEY key_type
Type we are using to look up values.
Definition: Cache.h:36
const T & GetRef(const KEY &k, const std::function< T(const KEY &k)> &calc_fun)
A version of Get that allows calls with const references instead of pass-by-value.
Definition: Cache.h:62
Cache()
Definition: Cache.h:30