6 #ifndef _FCITX_LIBIME_CORE_LRU_H_ 7 #define _FCITX_LIBIME_CORE_LRU_H_ 12 #include <boost/container_hash/hash.hpp> 13 #include <boost/unordered_map.hpp> 18 template <
typename K,
typename V,
typename H = boost::hash<K>>
26 boost::unordered_map<K, std::pair<V, typename std::list<K>::iterator>,
29 LRUCache(
size_t sz = 80) : sz_(sz) {}
31 size_t size()
const {
return dict_.size(); }
33 size_t capacity()
const {
return sz_; }
35 bool empty()
const {
return dict_.empty(); }
37 bool contains(
const key_type &key) {
38 return dict_.find(key) != dict_.end();
41 template <
typename... Args>
42 value_type *insert(
const key_type &key, Args &&...args) {
43 auto iter = dict_.find(key);
44 if (iter == dict_.end()) {
49 order_.push_front(key);
50 auto r = dict_.emplace(
51 key, std::make_pair(value_type(std::forward<Args>(args)...),
53 return &r.first->second.first;
58 void erase(
const key_type &key) {
59 auto i = dict_.find(key);
60 if (i == dict_.end()) {
63 order_.erase(i->second.second);
68 value_type *find(
const key_type &key) {
70 auto i = dict_.find(key);
71 return find_helper(i);
74 template <
class CompatibleKey,
class CompatibleHash,
75 class CompatiblePredicate>
76 value_type *find(CompatibleKey
const &k, CompatibleHash
const &h,
77 CompatiblePredicate
const &p) {
78 return find_helper(dict_.find(k, h, p));
89 auto i = std::prev(order_.end());
94 value_type *find_helper(
typename dict_type::iterator i) {
95 if (i == dict_.end()) {
102 auto j = i->second.second;
103 if (j != order_.begin()) {
104 order_.splice(order_.begin(), order_, j, std::next(j));
106 i->second.second = j;
108 return &i->second.first;
118 #endif // _FCITX_LIBIME_CORE_LRU_H_