Debian Codegraph @

src/3rdParty/lru-cache/include/lru/timed-cache.hpp

raw
1 /// The MIT License (MIT)
2 /// Copyright (c) 2016 Peter Goldsborough
3 ///
4 /// Permission is hereby granted, free of charge, to any person obtaining a copy
5 /// of this software and associated documentation files (the "Software"), to
6 /// deal in the Software without restriction, including without limitation the
7 /// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 /// sell copies of the Software, and to permit persons to whom the Software is
9 /// furnished to do so, subject to the following conditions:
10 ///
11 /// The above copyright notice and this permission notice shall be included in
12 /// all copies or substantial portions of the Software.
13 ///
14 /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 /// IN THE SOFTWARE.
21
22 #ifndef LRU_TIMED_CACHE_HPP
23 #define LRU_TIMED_CACHE_HPP
24
25 #include <algorithm>
26 #include <cassert>
27 #include <chrono>
28 #include <cstddef>
29 #include <functional>
30 #include <iterator>
31 #include <list>
32 #include <stdexcept>
33 #include <unordered_map>
34 #include <utility>
35
36 #include <lru/error.hpp>
37 #include <lru/internal/base-cache.hpp>
38 #include <lru/internal/last-accessed.hpp>
39 #include <lru/internal/timed-information.hpp>
40
41 namespace LRU {
42 namespace Internal {
43 template <typename Key,
44 typename Value,
45 typename HashFunction,
46 typename KeyEqual>
47 using TimedCacheBase = BaseCache<Key,
48 Value,
49 Internal::TimedInformation,
50 HashFunction,
51 KeyEqual,
52 Tag::TimedCache>;
53 } // namespace Internal
54
55
56 /// A timed LRU cache.
57 ///
58 /// A timed LRU cache behaves like a regular LRU cache, but adds the concept of
59 /// "expiration". The cache now not only remembers the order of insertion, but
60 /// also the point in time at which each element was inserted into the cache.
61 /// The cache then has an additional "time to live" property, which designates
62 /// the time after which a key in the cache is said to be "expired". Once a key
63 /// has expired, the cache will behave as if the key were not present in the
64 /// cache at all and, for example, return false on calls to `contains()` or
65 /// throw on calls to `lookup()`.
66 ///
67 /// \see LRU::Cache
68 template <typename Key,
69 typename Value,
70 typename Duration = std::chrono::duration<double, std::milli>,
71 typename HashFunction = std::hash<Key>,
72 typename KeyEqual = std::equal_to<Key>>
73 class TimedCache
74 : public Internal::TimedCacheBase<Key, Value, HashFunction, KeyEqual> {
75 private:
76 using super = Internal::TimedCacheBase<Key, Value, HashFunction, KeyEqual>;
77 using PRIVATE_BASE_CACHE_MEMBERS;
78
79 public:
80 using Tag = LRU::Tag::TimedCache;
81 using PUBLIC_BASE_CACHE_MEMBERS;
82 using super::ordered_end;
83 using super::unordered_end;
84 using typename super::size_t;
85
86 /// \param time_to_live The time to live for keys in the cache.
87 /// \copydoc BaseCache::BaseCache(size_t,const HashFunction&,const KeyEqual&)
88 template <typename AnyDurationType = Duration>
89 explicit TimedCache(const AnyDurationType& time_to_live,
90 size_t capacity = Internal::DEFAULT_CAPACITY,
91 const HashFunction& hash = HashFunction(),
92 const KeyEqual& equal = KeyEqual())
93 : super(capacity, hash, equal)
94 , _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
95 }
96
97 /// \param time_to_live The time to live for keys in the cache.
98 /// \copydoc BaseCache::BaseCache(size_t,Iterator,Iterator,const
99 /// HashFunction&,const
100 /// KeyEqual&)
101 template <typename Iterator, typename AnyDurationType = Duration>
102 TimedCache(const AnyDurationType& time_to_live,
103 size_t capacity,
104 Iterator begin,
105 Iterator end,
106 const HashFunction& hash = HashFunction(),
107 const KeyEqual& equal = KeyEqual())
108 : super(capacity, begin, end, hash, equal)
109 , _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
110 }
111
112 /// \param time_to_live The time to live for keys in the cache.
113 /// \copydoc BaseCache::BaseCache(Iterator,Iterator,const HashFunction&,const
114 /// KeyEqual&)
115 template <typename Iterator, typename AnyDurationType = Duration>
116 TimedCache(const AnyDurationType& time_to_live,
117 Iterator begin,
118 Iterator end,
119 const HashFunction& hash = HashFunction(),
120 const KeyEqual& equal = KeyEqual())
121 : super(begin, end, hash, equal)
122 , _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
123 }
124
125 /// \param time_to_live The time to live for keys in the cache.
126 /// \copydoc BaseCache::BaseCache(Range,size_t,const HashFunction&,const
127 /// KeyEqual&)
128 template <typename Range,
129 typename AnyDurationType = Duration,
130 typename = Internal::enable_if_range<Range>>
131 TimedCache(const AnyDurationType& time_to_live,
132 size_t capacity,
133 Range&& range,
134 const HashFunction& hash = HashFunction(),
135 const KeyEqual& equal = KeyEqual())
136 : super(capacity, std::forward<Range>(range), hash, equal)
137 , _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
138 }
139
140 /// \param time_to_live The time to live for keys in the cache.
141 /// \copydoc BaseCache::BaseCache(Range,const HashFunction&,const
142 /// KeyEqual&)
143 template <typename Range,
144 typename AnyDurationType = Duration,
145 typename = Internal::enable_if_range<Range>>
146 explicit TimedCache(const AnyDurationType& time_to_live,
147 Range&& range,
148 const HashFunction& hash = HashFunction(),
149 const KeyEqual& equal = KeyEqual())
150 : super(std::forward<Range>(range), hash, equal)
151 , _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
152 }
153
154 /// \param time_to_live The time to live for keys in the cache.
155 /// \copydoc BaseCache::BaseCache(InitializerList,const HashFunction&,const
156 /// KeyEqual&)
157 template <typename AnyDurationType = Duration>
158 TimedCache(const AnyDurationType& time_to_live,
159 InitializerList list,
160 const HashFunction& hash = HashFunction(),
161 const KeyEqual& equal = KeyEqual()) // NOLINT(runtime/explicit)
162 : super(list, hash, equal),
163 _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
164 }
165
166 /// \param time_to_live The time to live for keys in the cache.
167 /// \copydoc BaseCache::BaseCache(InitializerList,size_t,const
168 /// HashFunction&,const
169 /// KeyEqual&)
170 template <typename AnyDurationType = Duration>
171 TimedCache(const AnyDurationType& time_to_live,
172 size_t capacity,
173 InitializerList list,
174 const HashFunction& hash = HashFunction(),
175 const KeyEqual& equal = KeyEqual()) // NOLINT(runtime/explicit)
176 : super(capacity, list, hash, equal),
177 _time_to_live(std::chrono::duration_cast<Duration>(time_to_live)) {
178 }
179
180 /// \copydoc BaseCache::swap
181 void swap(TimedCache& other) noexcept {
182 using std::swap;
183
184 super::swap(other);
185 swap(_time_to_live, other._time_to_live);
186 }
187
188 /// Swaps the contents of one cache with another cache.
189 ///
190 /// \param first The first cache to swap.
191 /// \param second The second cache to swap.
192 friend void swap(TimedCache& first, TimedCache& second) noexcept {
193 first.swap(second);
194 }
195
196 /// \copydoc BaseCache::find(const Key&)
197 UnorderedIterator find(const Key& key) override {
198 auto iterator = _map.find(key);
199 if (iterator != _map.end()) {
200 if (!_has_expired(iterator->second)) {
201 _register_hit(key, iterator->second.value);
202 _move_to_front(iterator->second.order);
203 _last_accessed = iterator;
204 return {*this, iterator};
205 }
206 }
207
208 _register_miss(key);
209
210 return end();
211 }
212
213 /// \copydoc BaseCache::find(const Key&) const
214 UnorderedConstIterator find(const Key& key) const override {
215 auto iterator = _map.find(key);
216 if (iterator != _map.end()) {
217 if (!_has_expired(iterator->second)) {
218 _register_hit(key, iterator->second.value);
219 _move_to_front(iterator->second.order);
220 _last_accessed = iterator;
221 return {*this, iterator};
222 }
223 }
224
225 _register_miss(key);
226
227 return cend();
228 }
229
230 // no front() because we may have to erase the
231 // entire cache if everything happens to be expired
232
233 /// \returns True if all keys in the cache have expired, else false.
234 bool all_expired() const {
235 // By the laws of predicate logic, any statement about any empty set is true
236 if (is_empty()) return true;
237
238 /// If the most-recently inserted key has expired, all others must have too.
239 auto latest = _map.find(_order.back());
240 return _has_expired(latest->second);
241 }
242
243 /// Erases all expired elements from the cache.
244 ///
245 /// \complexity O(N)
246 /// \returns The number of elements erased.
247 size_t clear_expired() {
248 // We have to do a linear search here because linked lists do not
249 // support O(log N) binary searches given their node-based nature.
250 // Either way, in the worst case the entire cache has expired and
251 // we would have to do O(N) erasures.
252
253 if (is_empty()) return 0;
254
255 auto iterator = _order.begin();
256 size_t number_of_erasures = 0;
257
258 while (iterator != _order.end()) {
259 auto map_iterator = _map.find(*iterator);
260
261 // If the current element hasn't expired, also all elements inserted
262 // after will not have, so we can stop.
263 if (!_has_expired(map_iterator->second)) break;
264
265 _erase(map_iterator);
266
267 iterator = _order.begin();
268 number_of_erasures += 1;
269 }
270
271 return number_of_erasures;
272 }
273
274 /// \returns True if the given key is contained in the cache and has expired.
275 /// \param key The key to test expiration for.
276 bool has_expired(const Key& key) const noexcept {
277 auto iterator = _map.find(key);
278 return iterator != _map.end() && _has_expired(iterator->second);
279 }
280
281 /// \returns True if the key pointed to by the iterator has expired.
282 /// \param ordered_iterator The ordered iterator to check.
283 /// \details If this is the end iterator, this method returns false.
284 bool has_expired(OrderedConstIterator ordered_iterator) const noexcept {
285 if (ordered_iterator == ordered_end()) return false;
286 auto iterator = _map.find(ordered_iterator->key());
287 assert(iterator != _map.end());
288
289 return _has_expired(iterator->second);
290 }
291
292 /// \returns True if the key pointed to by the iterator has expired.
293 /// \param unordered_iterator The unordered iterator to check.
294 /// \details If this is the end iterator, this method returns false.
295 bool has_expired(UnorderedConstIterator unordered_iterator) const noexcept {
296 if (unordered_iterator == unordered_end()) return false;
297 assert(unordered_iterator._iterator != _map.end());
298
299 return _has_expired(unordered_iterator._iterator->second);
300 }
301
302 /// \copydoc BaseCache::is_valid(UnorderedConstIterator)
303 bool is_valid(UnorderedConstIterator unordered_iterator) const
304 noexcept override {
305 if (!super::is_valid(unordered_iterator)) return false;
306 if (has_expired(unordered_iterator)) return false;
307 return true;
308 }
309
310 /// \copydoc BaseCache::is_valid(OrderedConstIterator)
311 bool is_valid(OrderedConstIterator ordered_iterator) const noexcept override {
312 if (!super::is_valid(ordered_iterator)) return false;
313 if (has_expired(ordered_iterator)) return false;
314 return true;
315 }
316
317 /// \copydoc BaseCache::is_valid(UnorderedConstIterator)
318 /// \throws LRU::Error::KeyExpired if the key pointed to by the iterator has
319 /// expired.
320 void
321 throw_if_invalid(UnorderedConstIterator unordered_iterator) const override {
322 super::throw_if_invalid(unordered_iterator);
323 if (has_expired(unordered_iterator)) {
324 throw LRU::Error::KeyExpired();
325 }
326 }
327
328 /// \copydoc BaseCache::is_valid(OrderedConstIterator)
329 /// \throws LRU::Error::KeyExpired if the key pointed to by the iterator has
330 /// expired.
331 void throw_if_invalid(OrderedConstIterator ordered_iterator) const override {
332 super::throw_if_invalid(ordered_iterator);
333 if (has_expired(ordered_iterator)) {
334 throw LRU::Error::KeyExpired();
335 }
336 }
337
338 private:
339 using Clock = Internal::Clock;
340
341 /// \returns True if the last accessed object is valid.
342 /// \details Next to performing the base cache's action, this method also
343 /// checks for expiration of the last accessed key.
344 bool _last_accessed_is_ok(const Key& key) const noexcept override {
345 if (!super::_last_accessed_is_ok(key)) return false;
346 return !_has_expired(_last_accessed.information());
347 }
348
349 /// \copydoc _value_for_last_accessed() const
350 Value& _value_for_last_accessed() override {
351 auto& information = _last_accessed.information();
352 if (_has_expired(information)) {
353 throw LRU::Error::KeyExpired();
354 } else {
355 return information.value;
356 }
357 }
358
359 /// Attempts to access the last accessed key's value.
360 /// \throws LRU::Error::KeyExpired if the key has expired.
361 /// \returns The value of the last accessed key.
362 const Value& _value_for_last_accessed() const override {
363 const auto& information = _last_accessed.information();
364 if (_has_expired(information)) {
365 throw LRU::Error::KeyExpired();
366 } else {
367 return information.value;
368 }
369 }
370
371 /// Checks if a key has expired, given its information.
372 ///
373 /// \param information The information to check expiration with.
374 /// \returns True if the key has expired, else false.
375 bool _has_expired(const Information& information) const noexcept {
376 auto elapsed = Clock::now() - information.insertion_time;
377 return std::chrono::duration_cast<Duration>(elapsed) > _time_to_live;
378 }
379
380 /// The duration after which a key is said to be expired.
381 Duration _time_to_live;
382 };
383
384 namespace Lowercase {
385 template <typename... Ts>
386 using timed_cache = TimedCache<Ts...>;
387 } // namespace Lowercase
388
389 } // namespace LRU
390
391 #endif // LRU_TIMED_CACHE_HPP