Spicy
cache.h
1 // Copyright (c) 2020-now by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <map>
6 #include <optional>
7 #include <utility>
8 
9 namespace hilti::util {
10 
12 template<typename Key, typename Value>
13 class Cache {
14 public:
15  Cache() = default;
16 
18  bool has(const Key& key) const { return _cache.find(key) != _cache.end(); }
19 
24  std::optional<Value> get(const Key& key, std::optional<Value> default_ = {}) const {
25  if ( auto i = _cache.find(key); i != _cache.end() )
26  return i->second;
27 
28  return std::move(default_);
29  }
30 
36  template<typename Callback>
37  const Value& getOrCreate(const Key& key, Callback&& cb) {
38  if ( auto i = _cache.find(key); i != _cache.end() )
39  return i->second;
40 
41  return put(key, cb());
42  }
43 
56  template<typename Callback1, typename Callback2>
57  const Value& getOrCreate(const Key& key, Callback1&& cb1, Callback2&& cb2) {
58  if ( auto i = _cache.find(key); i != _cache.end() )
59  return i->second;
60 
61  _cache[key] = cb1();
62  return _cache[key] = cb2(_cache[key]);
63  }
64 
66  const Value& put(const Key& key, Value value) { return _cache[key] = std::move(value); }
67 
69  void remove(const Key& key) { _cache.erase(key); }
70 
71 private:
72  std::map<Key, Value> _cache;
73 };
74 
75 } // namespace hilti::util
Definition: cache.h:13
bool has(const Key &key) const
Definition: cache.h:18
void remove(const Key &key)
Definition: cache.h:69
const Value & getOrCreate(const Key &key, Callback &&cb)
Definition: cache.h:37
std::optional< Value > get(const Key &key, std::optional< Value > default_={}) const
Definition: cache.h:24
const Value & getOrCreate(const Key &key, Callback1 &&cb1, Callback2 &&cb2)
Definition: cache.h:57
const Value & put(const Key &key, Value value)
Definition: cache.h:66