LeechCraft 0.6.70-16373-g319c272718
Modular cross-platform feature rich live environment.
Loading...
Searching...
No Matches
assoccache.h
Go to the documentation of this file.
1/**********************************************************************
2 * LeechCraft - modular cross-platform feature rich internet client.
3 * Copyright (C) 2006-2014 Georg Rudoy
4 *
5 * Distributed under the Boost Software License, Version 1.0.
6 * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
7 **********************************************************************/
8
9#pragma once
10
11#include <algorithm>
12#include <QHash>
13
14namespace LC::Util
15{
16 namespace CacheStrat
17 {
18 class LRU
19 {
20 size_t Current_ = 0;
21 public:
23 {
24 size_t LastAccess_ = 0;
25 };
26
28 {
29 return { ++Current_ };
30 }
31
32 void Clear ()
33 {
34 Current_ = 0;
35 }
36
37 void Touch (ValueAddon& add)
38 {
39 add.LastAccess_ = ++Current_;
40 }
41 };
42
44 {
45 return v1.LastAccess_ < v2.LastAccess_;
46 }
47 }
48
49 template<typename K, typename V, typename CS = CacheStrat::LRU>
51 {
52 struct ValueHolder
53 {
54 V V_;
55 size_t Cost_;
56 typename CS::ValueAddon CacheInfo_;
57 };
58
59 QHash<K, ValueHolder> Hash_;
60
61 size_t CurrentCost_ = 0;
62 const size_t MaxCost_;
63
64 CS CacheStratState_;
65 public:
66 explicit AssocCache (size_t maxCost)
67 : MaxCost_ { maxCost }
68 {
69 }
70
71 size_t size () const;
72 void clear ();
73 bool contains (const K&) const;
74
75 V& operator[] (const K&);
76 private:
77 void CheckShrink ();
78 };
79
80 template<typename K, typename V, typename CS>
82 {
83 return Hash_.size ();
84 }
85
86 template<typename K, typename V, typename CS>
88 {
89 Hash_.clear ();
90 CacheStratState_.Clear ();
91 }
92
93 template<typename K, typename V, typename CS>
94 bool AssocCache<K, V, CS>::contains (const K& k) const
95 {
96 return Hash_.contains (k);
97 }
98
99 template<typename K, typename V, typename CS>
101 {
102 if (!Hash_.contains (key))
103 {
104 Hash_.insert (key, { {}, 1, CacheStratState_.CreateInfo () });
105 ++CurrentCost_;
106
107 CheckShrink ();
108 }
109 else
110 CacheStratState_.Touch (Hash_ [key].CacheInfo_);
111
112 return Hash_ [key].V_;
113 }
114
115 template<typename K, typename V, typename CS>
116 void AssocCache<K, V, CS>::CheckShrink ()
117 {
118 while (CurrentCost_ > MaxCost_)
119 {
120 const auto pos = std::min_element (Hash_.begin (), Hash_.end (),
121 [] (const ValueHolder& left, const ValueHolder& right)
122 { return left.CacheInfo_ < right.CacheInfo_; });
123 CurrentCost_ -= pos->Cost_;
124 Hash_.erase (pos);
125 }
126 }
127}
size_t size() const
Definition assoccache.h:81
V & operator[](const K &)
Definition assoccache.h:100
bool contains(const K &) const
Definition assoccache.h:94
AssocCache(size_t maxCost)
Definition assoccache.h:66
void Touch(ValueAddon &add)
Definition assoccache.h:37
bool operator<(LRU::ValueAddon v1, LRU::ValueAddon v2)
Definition assoccache.h:43