4 #include "common/Mutex.h"
6 template <class K, class V>
10 typename std::list<K>::iterator lru_iter;
13 std::map<K, entry> entries;
14 std::list<K> entries_lru;
23 virtual ~UpdateContext() {}
25 /* update should return true if object is updated */
26 virtual bool update(V *v) = 0;
29 bool _find(const K& key, V *value, UpdateContext *ctx);
30 void _add(const K& key, V& value);
33 lru_map(int _max) : lock("lru_map"), max(_max) {}
36 bool find(const K& key, V& value);
41 * - will return true if object is found
42 * - if ctx is set will return true if object is found and updated
44 bool find_and_update(const K& key, V *value, UpdateContext *ctx);
45 void add(const K& key, V& value);
46 void erase(const K& key);
49 template <class K, class V>
50 bool lru_map<K, V>::_find(const K& key, V *value, UpdateContext *ctx)
52 typename std::map<K, entry>::iterator iter = entries.find(key);
53 if (iter == entries.end()) {
57 entry& e = iter->second;
58 entries_lru.erase(e.lru_iter);
63 r = ctx->update(&e.value);
68 entries_lru.push_front(key);
69 e.lru_iter = entries_lru.begin();
74 template <class K, class V>
75 bool lru_map<K, V>::find(const K& key, V& value)
77 Mutex::Locker l(lock);
78 return _find(key, &value, NULL);
81 template <class K, class V>
82 bool lru_map<K, V>::find_and_update(const K& key, V *value, UpdateContext *ctx)
84 Mutex::Locker l(lock);
85 return _find(key, value, ctx);
88 template <class K, class V>
89 void lru_map<K, V>::_add(const K& key, V& value)
91 typename std::map<K, entry>::iterator iter = entries.find(key);
92 if (iter != entries.end()) {
93 entry& e = iter->second;
94 entries_lru.erase(e.lru_iter);
97 entries_lru.push_front(key);
98 entry& e = entries[key];
100 e.lru_iter = entries_lru.begin();
102 while (entries.size() > max) {
103 typename std::list<K>::reverse_iterator riter = entries_lru.rbegin();
104 iter = entries.find(*riter);
105 // assert(iter != entries.end());
107 entries_lru.pop_back();
112 template <class K, class V>
113 void lru_map<K, V>::add(const K& key, V& value)
115 Mutex::Locker l(lock);
119 template <class K, class V>
120 void lru_map<K, V>::erase(const K& key)
122 Mutex::Locker l(lock);
123 typename std::map<K, entry>::iterator iter = entries.find(key);
124 if (iter == entries.end())
127 entry& e = iter->second;
128 entries_lru.erase(e.lru_iter);