Spicy
cache.h
1 // Copyright (c) 2020-2021 by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <functional>
6 #include <map>
7 #include <optional>
8 #include <string>
9 #include <utility>
10 
11 namespace hilti::util {
12 
14 template<typename Key, typename Value>
15 class Cache {
16 public:
17  using Callback1 = std::function<Value()>;
18  using Callback2 = std::function<Value(Value& v)>;
19 
20  Cache() = default;
21 
23  bool has(const Key& key) const { return _cache.find(key) != _cache.end(); }
24 
29  std::optional<Value> get(const Key& key, std::optional<Value> default_ = {}) const {
30  if ( auto i = _cache.find(key); i != _cache.end() )
31  return i->second;
32 
33  return std::move(default_);
34  }
35 
41  const Value& getOrCreate(const Key& key, const Callback1& cb) {
42  if ( auto i = _cache.find(key); i != _cache.end() )
43  return i->second;
44 
45  return put(key, cb());
46  }
47 
60  const Value& getOrCreate(const Key& key, const Callback1& cb1, const Callback2& cb2) {
61  if ( auto i = _cache.find(key); i != _cache.end() )
62  return i->second;
63 
64  _cache[key] = cb1();
65  return _cache[key] = cb2(_cache[key]);
66  }
67 
69  const Value& put(const Key& key, Value value) { return _cache[key] = std::move(value); }
70 
72  void remove(const Key& key) { _cache.erase(key); }
73 
74 private:
75  std::map<Key, Value> _cache;
76 };
77 
78 } // namespace hilti::util
bool has(const Key &key) const
Definition: cache.h:23
Definition: cache.h:11
const Value & getOrCreate(const Key &key, const Callback1 &cb)
Definition: cache.h:41
Definition: cache.h:15
const Value & getOrCreate(const Key &key, const Callback1 &cb1, const Callback2 &cb2)
Definition: cache.h:60
const Value & put(const Key &key, Value value)
Definition: cache.h:69