12 #ifndef DOCWIRE_LRU_MEMORY_CACHE_H
13 #define DOCWIRE_LRU_MEMORY_CACHE_H
18 #include <unordered_map>
32 template<
typename Key,
typename Value>
42 : m_max_size(max_size)
52 Value&
get_or_create(
const Key& key,
const std::function<Value(
const Key&)>& producer)
54 auto it = m_entry_list_iter_map.find(key);
55 if (it != m_entry_list_iter_map.end()) {
56 m_entry_list.splice(m_entry_list.begin(), m_entry_list, it->second);
58 Value value = producer(key);
59 m_entry_list.emplace_front(key, value);
60 m_entry_list_iter_map.emplace(key, m_entry_list.begin());
61 if (m_entry_list.size() > m_max_size) {
62 m_entry_list_iter_map.erase(std::prev(m_entry_list.end())->key);
63 m_entry_list.pop_back();
66 return m_entry_list.begin()->value;
75 entry(
const Key& key,
const Value& value) : key(key), value(value) {}
77 std::list<entry> m_entry_list;
78 std::unordered_map<Key, typename std::list<entry>::iterator> m_entry_list_iter_map;
Least Recently Used (LRU) cache with fixed memory size.
lru_memory_cache(size_t max_size=std::numeric_limits< size_t >::max())
Constructs LRU cache with specified maximum size.
Value & get_or_create(const Key &key, const std::function< Value(const Key &)> &producer)
Returns value for specified key. If key is not in the cache, it calls producer function to create val...
The main namespace for the DocWire SDK.