InvoDB/invodb/models/cache.h

53 lines
1.2 KiB
C
Raw Normal View History

2021-11-03 09:39:13 +08:00
//
// Created by i on 2021/11/2.
//
#ifndef INVODBCACHEH
#define INVODBCACHEH
#include <list>
#include <map>
template<typename KT, typename VT>
class LRUCache {
public:
LRUCache(int capacity) : capacity(capacity) {}
bool exist(KT const &key) {
return hash.find(key) != hash.end();
}
2021-11-03 22:05:13 +08:00
std::shared_ptr<VT> get(KT const &key) {
2021-11-03 09:39:13 +08:00
if (hash.find(key) == hash.end())
throw "cache error";
else {
2021-11-03 22:05:13 +08:00
std::shared_ptr<VT> value = hash[key]->second;
2021-11-03 09:39:13 +08:00
ls.erase(hash[key]);
ls.push_front(std::make_pair(key, value));
hash[key] = ls.begin();
return value;
}
}
2021-11-03 22:05:13 +08:00
void put(KT const &key, std::shared_ptr<VT> const &value) {
2021-11-03 09:39:13 +08:00
if (hash.find(key) != hash.end()) {
ls.erase(hash[key]);
}
else if (ls.size() >= capacity) {
hash.erase(ls.back().first);
ls.pop_back();
}
ls.push_front(std::make_pair(key, value));
hash[key] = ls.begin();
}
private:
int capacity;
2021-11-03 22:05:13 +08:00
std::list<std::pair<KT, std::shared_ptr<VT>>> ls;
std::unordered_map<KT, typename std::list<std::pair<KT, std::shared_ptr<VT>>>::iterator> hash;
2021-11-03 09:39:13 +08:00
};
#endif //INVODBCACHEH