Debian Codegraph @

src/3rdParty/lru-cache/include/lru/internal/base-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_INTERNAL_BASE_CACHE_HPP
23 #define LRU_INTERNAL_BASE_CACHE_HPP
24
25 #include <algorithm>
26 #include <cmath>
27 #include <cstddef>
28 #include <initializer_list>
29 #include <iterator>
30 #include <list>
31 #include <memory>
32 #include <tuple>
33 #include <unordered_map>
34 #include <utility>
35
36 #include <lru/insertion-result.hpp>
37 #include <lru/internal/base-ordered-iterator.hpp>
38 #include <lru/internal/base-unordered-iterator.hpp>
39 #include <lru/internal/callback-manager.hpp>
40 #include <lru/internal/definitions.hpp>
41 #include <lru/internal/last-accessed.hpp>
42 #include <lru/internal/optional.hpp>
43 #include <lru/internal/statistics-mutator.hpp>
44 #include <lru/internal/utility.hpp>
45 #include <lru/statistics.hpp>
46
47 namespace LRU {
48 namespace Internal {
49
50 // Macros are bad, but also more readable sometimes:
51 // Without this macro, it becomes a pain to have a `using` directive for every
52 // new member we add to the `BaseCache` and rename or remove every such
53 // directive when we make a change to the `BaseCache`.
54 // With this macro, you can simply do:
55 // using super = BaseCache<Key, Value, Information>;
56 // using BASE_CACHE_MEMBERS;
57 #define PUBLIC_BASE_CACHE_MEMBERS \
58 super::is_full; \
59 using super::is_empty; \
60 using super::clear; \
61 using super::end; \
62 using super::cend; \
63 using super::operator=; \
64 using typename super::Information; \
65 using typename super::UnorderedIterator; \
66 using typename super::UnorderedConstIterator; \
67 using typename super::OrderedIterator; \
68 using typename super::OrderedConstIterator; \
69 using typename super::InitializerList;
70
71 #define PRIVATE_BASE_CACHE_MEMBERS \
72 super::_map; \
73 using typename super::Map; \
74 using typename super::MapIterator; \
75 using typename super::MapConstIterator; \
76 using typename super::Queue; \
77 using typename super::QueueIterator; \
78 using super::_order; \
79 using super::_last_accessed; \
80 using super::_capacity; \
81 using super::_erase; \
82 using super::_erase_lru; \
83 using super::_move_to_front; \
84 using super::_value_from_result; \
85 using super::_last_accessed_is_ok; \
86 using super::_register_miss; \
87 using super::_register_hit;
88
89 /// The base class for the LRU::Cache and LRU::TimedCache.
90 ///
91 /// This base class (base as opposed to abstract, because it is not intended to
92 /// be used polymorphically) provides the great bulk of the implementation of
93 /// both the LRU::Cache and the timed version. For example, it builds the
94 /// `contains()`, `lookup()` and `operator[]()` functions on top of the pure
95 /// virtual `find()` methods, making the final implementation of the LRU::Cache
96 /// much less strenuous.
97 ///
98 /// This class also defines all concrete iterator classes and provides the main
99 /// iterator interface of all caches via ordered and unordered iterators and
100 /// appropriate `begin()`, `end()` and similar methods.
101 ///
102 /// Lastly, the `BaseCache` provides a statistics interface to register and
103 /// access shared or owned statistics.
104 ///
105 /// \tparam Key The key type of the cache.
106 /// \tparam Value The value type of the cache.
107 /// \tparam InformationType The internal information class to be used.
108 /// \tparam HashFunction The hash function type for the internal map.
109 /// \tparam KeyEqual The type of the key equality function for the internal map.
110 /// \tparam TagType The cache tag type of the concrete derived class.
111 template <typename Key,
112 typename Value,
113 template <typename, typename> class InformationType,
114 typename HashFunction,
115 typename KeyEqual,
116 typename TagType>
117 class BaseCache {
118 protected:
119 using Information = InformationType<Key, Value>;
120 using Queue = Internal::Queue<const Key>;
121 using QueueIterator = typename Queue::const_iterator;
122
123 using Map = Internal::Map<Key, Information, HashFunction, KeyEqual>;
124 using MapIterator = typename Map::iterator;
125 using MapConstIterator = typename Map::const_iterator;
126
127 using CallbackManagerType = CallbackManager<Key, Value>;
128 using HitCallback = typename CallbackManagerType::HitCallback;
129 using MissCallback = typename CallbackManagerType::MissCallback;
130 using AccessCallback = typename CallbackManagerType::AccessCallback;
131 using HitCallbackContainer =
132 typename CallbackManagerType::HitCallbackContainer;
133 using MissCallbackContainer =
134 typename CallbackManagerType::MissCallbackContainer;
135 using AccessCallbackContainer =
136 typename CallbackManagerType::AccessCallbackContainer;
137
138 public:
139 using Tag = TagType;
140 using InitializerList = std::initializer_list<std::pair<Key, Value>>;
141 using StatisticsPointer = std::shared_ptr<Statistics<Key>>;
142 using size_t = std::size_t;
143
144 static constexpr Tag tag() noexcept {
145 return {};
146 }
147
148 /////////////////////////////////////////////////////////////////////////////
149 // ITERATORS CLASSES
150 /////////////////////////////////////////////////////////////////////////////
151
152 /// A non-const unordered iterator.
153 ///
154 /// Unordered iterators provide faster lookup than ordered iterators because
155 /// they have direct access to the underlying map. Also, they can convert to
156 /// ordered iterators cheaply.
157 struct UnorderedIterator
158 : public BaseUnorderedIterator<BaseCache, MapIterator> {
159 using super = BaseUnorderedIterator<BaseCache, MapIterator>;
160 friend BaseCache;
161
162 /// Default constructor.
163 UnorderedIterator() = default;
164
165 /// Constructs a new UnorderedIterator from an unordered base iterator.
166 ///
167 /// \param iterator The iterator to initialize this one from.
168 UnorderedIterator(BaseUnorderedIterator<BaseCache, MapIterator>
169 iterator) // NOLINT(runtime/explicit)
170 : super(std::move(iterator)) {
171 // Note that this only works because these derived iterator
172 // classes dont' have any members of their own.
173 // It is necessary because the increment operators return base iterators.
174 }
175
176 /// Constructs a new UnorderedIterator.
177 ///
178 /// \param cache The cache this iterator references.
179 /// \param iterator The underlying map iterator.
180 UnorderedIterator(BaseCache& cache,
181 MapIterator iterator) // NOLINT(runtime/explicit)
182 : super(cache, iterator) {
183 }
184 };
185
186 /// A const unordered iterator.
187 ///
188 /// Unordered iterators provide faster lookup than ordered iterators because
189 /// they have direct access to the underlying map. Also, they can convert to
190 /// ordered iterators cheaply.
191 struct UnorderedConstIterator
192 : public BaseUnorderedIterator<const BaseCache, MapConstIterator> {
193 using super = BaseUnorderedIterator<const BaseCache, MapConstIterator>;
194 friend BaseCache;
195
196 /// Default constructor.
197 UnorderedConstIterator() = default;
198
199 /// Constructs a new UnorderedConstIterator from any unordered base
200 /// iterator.
201 ///
202 /// \param iterator The iterator to initialize this one from.
203 template <typename AnyCache, typename AnyUnderlyingIterator>
204 UnorderedConstIterator(
205 BaseUnorderedIterator<AnyCache, AnyUnderlyingIterator> iterator)
206 : super(std::move(iterator)) {
207 // Note that this only works because these derived iterator
208 // classes dont' have any members of their own.
209 }
210
211 /// Constructs a new UnorderedConstIterator from a non-const iterator.
212 ///
213 /// \param iterator The non-const iterator to initialize this one from.
214 UnorderedConstIterator(
215 UnorderedIterator iterator) // NOLINT(runtime/explicit)
216 : super(std::move(iterator)) {
217 }
218
219 /// Constructs a new UnorderedConstIterator.
220 ///
221 /// \param cache The cache this iterator references.
222 /// \param iterator The underlying map iterator.
223 UnorderedConstIterator(
224 const BaseCache& cache,
225 MapConstIterator iterator) // NOLINT(runtime/explicit)
226 : super(cache, iterator) {
227 }
228 };
229
230 /// An ordered iterator.
231 ///
232 /// Ordered iterators have a performance disadvantage compared to unordered
233 /// iterators the first time they are dereferenced. However, they may be
234 /// constructed or assigned from unordered iterators (of compatible
235 /// qualifiers).
236 struct OrderedIterator
237 : public BaseOrderedIterator<const Key, Value, BaseCache> {
238 using super = BaseOrderedIterator<const Key, Value, BaseCache>;
239 using UnderlyingIterator = typename super::UnderlyingIterator;
240 friend BaseCache;
241
242 /// Default constructor.
243 OrderedIterator() = default;
244
245 /// Constructs an ordered iterator from an unordered iterator.
246 ///
247 /// \param unordered_iterator The unordered iterator to construct from.
248 explicit OrderedIterator(UnorderedIterator unordered_iterator)
249 : super(std::move(unordered_iterator)) {
250 }
251
252 /// Constructs a new OrderedIterator from an unordered base iterator.
253 ///
254 /// \param iterator The iterator to initialize this one from.
255 OrderedIterator(BaseOrderedIterator<Key, Value, BaseCache>
256 iterator) // NOLINT(runtime/explicit)
257 : super(std::move(iterator)) {
258 // Note that this only works because these derived iterator
259 // classes dont' have any members of their own.
260 // It is necessary because the increment operators return base iterators.
261 }
262
263 /// Constructs a new ordered iterator.
264 ///
265 /// \param cache The cache this iterator references.
266 /// \param iterator The underlying iterator.
267 OrderedIterator(BaseCache& cache, UnderlyingIterator iterator)
268 : super(cache, iterator) {
269 }
270 };
271
272 /// A const ordered iterator.
273 ///
274 /// Ordered iterators have a performance disadvantage compared to unordered
275 /// iterators the first time they are dereferenced. However, they may be
276 /// constructed or assigned from unordered iterators (of compatible
277 /// qualifiers).
278 struct OrderedConstIterator
279 : public BaseOrderedIterator<const Key, const Value, const BaseCache> {
280 using super = BaseOrderedIterator<const Key, const Value, const BaseCache>;
281 using UnderlyingIterator = typename super::UnderlyingIterator;
282
283 friend BaseCache;
284
285 /// Default constructor.
286 OrderedConstIterator() = default;
287
288 /// Constructs a new OrderedConstIterator from a compatible ordered
289 /// iterator.
290 ///
291 /// \param iterator The iterator to initialize this one from.
292 template <typename AnyKey, typename AnyValue, typename AnyCache>
293 OrderedConstIterator(BaseOrderedIterator<AnyKey, AnyValue, AnyCache>
294 iterator) // NOLINT(runtime/explicit)
295 : super(iterator) {
296 // Note that this only works because these derived iterator
297 // classes dont' have any members of their own.
298 }
299
300 /// Constructs a new const ordered iterator from a non-const one.
301 ///
302 /// \param iterator The non-const ordered iterator to construct from.
303 OrderedConstIterator(OrderedIterator iterator) // NOLINT(runtime/explicit)
304 : super(std::move(iterator)) {
305 }
306
307 /// Constructs a new const ordered iterator from an unordered iterator.
308 ///
309 /// \param unordered_iterator The unordered iterator to construct from.
310 explicit OrderedConstIterator(UnorderedIterator unordered_iterator)
311 : super(std::move(unordered_iterator)) {
312 }
313
314 /// Constructs a new const ordered iterator from a const unordered iterator.
315 ///
316 /// \param unordered_iterator The unordered iterator to construct from.
317 explicit OrderedConstIterator(
318 UnorderedConstIterator unordered_iterator) // NOLINT(runtime/explicit)
319 : super(std::move(unordered_iterator)) {
320 }
321
322 /// Constructs a new const ordered iterator.
323 ///
324 /// \param cache The cache this iterator references.
325 /// \param iterator The underlying iterator.
326 OrderedConstIterator(const BaseCache& cache, UnderlyingIterator iterator)
327 : super(cache, iterator) {
328 }
329 };
330
331 using InsertionResultType = InsertionResult<UnorderedIterator>;
332
333 // Can't put these in LRU::Lowercase because they are nested, unfortunately
334 using ordered_iterator = OrderedIterator;
335 using ordered_const_iterator = OrderedConstIterator;
336 using unordered_iterator = UnorderedIterator;
337 using unordered_const_iterator = UnorderedConstIterator;
338
339 /////////////////////////////////////////////////////////////////////////////
340 // SPECIAL MEMBER FUNCTIONS
341 /////////////////////////////////////////////////////////////////////////////
342
343 /// Constructor.
344 ///
345 /// \param capacity The capacity of the cache.
346 /// \param hash The hash function to use for the internal map.
347 /// \param key_equal The key equality function to use for the internal map.
348 BaseCache(size_t capacity,
349 const HashFunction& hash,
350 const KeyEqual& key_equal)
351 : _map(0, hash, key_equal), _capacity(capacity), _last_accessed(key_equal) {
352 }
353
354 /// Constructor.
355 ///
356 /// \param capacity The capacity of the cache.
357 /// \param begin The start of a range to construct the cache with.
358 /// \param end The end of a range to construct the cache with.
359 /// \param hash The hash function to use for the internal map.
360 /// \param key_equal The key equality function to use for the internal map.
361 template <typename Iterator>
362 BaseCache(size_t capacity,
363 Iterator begin,
364 Iterator end,
365 const HashFunction& hash,
366 const KeyEqual& key_equal)
367 : BaseCache(capacity, hash, key_equal) {
368 insert(begin, end);
369 }
370
371 /// Constructor.
372 ///
373 /// The capacity is inferred from the distance between the two iterators and
374 /// lower-bounded by an internal constant $c_0$, usually 128 (i.e. the actual
375 /// capacity will be $\max(\text{distance}, c_0)$).
376 /// This may be expensive for iterators that are not random-access.
377 ///
378 /// \param begin The start of a range to construct the cache with.
379 /// \param end The end of a range to construct the cache with.
380 /// \param hash The hash function to use for the internal map.
381 /// \param key_equal The key equality function to use for the internal map.
382 template <typename Iterator>
383 BaseCache(Iterator begin,
384 Iterator end,
385 const HashFunction& hash,
386 const KeyEqual& key_equal)
387 // This may be expensive
388 : BaseCache(std::max<size_t>(std::distance(begin, end),
389 Internal::DEFAULT_CAPACITY),
390 begin,
391 end,
392 hash,
393 key_equal) {
394 }
395
396 /// Constructor.
397 ///
398 /// \param capacity The capacity of the cache.
399 /// \param range A range to construct the cache with.
400 /// \param hash The hash function to use for the internal map.
401 /// \param key_equal The key equality function to use for the internal map.
402 template <typename Range, typename = Internal::enable_if_range<Range>>
403 BaseCache(size_t capacity,
404 Range& range,
405 const HashFunction& hash,
406 const KeyEqual& key_equal)
407 : BaseCache(capacity, hash, key_equal) {
408 insert(range);
409 }
410
411 /// Constructor.
412 ///
413 /// The capacity is inferred from the distance between the beginning and end
414 /// of the range. This may be expensive for iterators that are not
415 /// random-access.
416 ///
417 /// \param range A range to construct the cache with.
418 /// \param hash The hash function to use for the internal map.
419 /// \param key_equal The key equality function to use for the internal map.
420 template <typename Range, typename = Internal::enable_if_range<Range>>
421 explicit BaseCache(Range& range,
422 const HashFunction& hash,
423 const KeyEqual& key_equal)
424 : BaseCache(std::begin(range), std::end(range), hash, key_equal) {
425 }
426
427 /// Constructor.
428 ///
429 /// Elements of the range will be moved into the cache.
430 ///
431 /// \param capacity The capacity of the cache.
432 /// \param range A range to construct the cache with.
433 /// \param hash The hash function to use for the internal map.
434 /// \param key_equal The key equality function to use for the internal map.
435 template <typename Range, typename = Internal::enable_if_range<Range>>
436 BaseCache(size_t capacity,
437 Range&& range,
438 const HashFunction& hash,
439 const KeyEqual& key_equal)
440 : BaseCache(capacity, hash, key_equal) {
441 insert(std::move(range));
442 }
443
444 /// Constructor.
445 ///
446 /// The capacity is inferred from the distance between the beginning and end
447 /// of the range. This may be expensive for iterators that are not
448 /// random-access.
449 ///
450 /// Elements of the range will be moved into the cache.
451 ///
452 /// \param range A range to construct the cache with.
453 /// \param hash The hash function to use for the internal map.
454 /// \param key_equal The key equality function to use for the internal map.
455 template <typename Range, typename = Internal::enable_if_range<Range>>
456 explicit BaseCache(Range&& range,
457 const HashFunction& hash,
458 const KeyEqual& key_equal)
459 : BaseCache(std::distance(std::begin(range), std::end(range)),
460 std::move(range),
461 hash,
462 key_equal) {
463 }
464
465 /// Constructor.
466 ///
467 /// \param capacity The capacity of the cache.
468 /// \param list The initializer list to construct the cache with.
469 /// \param hash The hash function to use for the internal map.
470 /// \param key_equal The key equality function to use for the internal map.
471 BaseCache(size_t capacity,
472 InitializerList list,
473 const HashFunction& hash,
474 const KeyEqual& key_equal)
475 : BaseCache(capacity, list.begin(), list.end(), hash, key_equal) {
476 }
477
478 /// Constructor.
479 ///
480 /// \param list The initializer list to construct the cache with.
481 /// \param hash The hash function to use for the internal map.
482 /// \param key_equal The key equality function to use for the internal map.
483 BaseCache(InitializerList list,
484 const HashFunction& hash,
485 const KeyEqual& key_equal) // NOLINT(runtime/explicit)
486 : BaseCache(list.size(), list.begin(), list.end(), hash, key_equal) {
487 }
488
489 /// Copy constructor.
490 BaseCache(const BaseCache& other)
491 : _map(other._map)
492 , _order(other._order)
493 , _stats(other._stats)
494 , _last_accessed(other._last_accessed)
495 , _callback_manager(other._callback_manager)
496 , _capacity(other._capacity) {
497 _reassign_references();
498 }
499
500 /// Move constructor.
501 BaseCache(BaseCache&& other) {
502 // Following the copy-swap idiom.
503 swap(other);
504 }
505
506 /// Copy assignment operator.
507 BaseCache& operator=(const BaseCache& other) noexcept {
508 if (this != &other) {
509 _map = other._map;
510 _order = other._order;
511 _stats = other._stats;
512 _last_accessed = other._last_accessed;
513 _callback_manager = other._callback_manager;
514 _capacity = other._capacity;
515 _reassign_references();
516 }
517
518 return *this;
519 }
520
521 /// Move assignment operator.
522 BaseCache& operator=(BaseCache&& other) noexcept {
523 // Following the copy-swap idiom.
524 swap(other);
525 return *this;
526 }
527
528 /// Destructor.
529 virtual ~BaseCache() = default;
530
531 /// Sets the contents of the cache to a range.
532 ///
533 /// If the size of the range is greater than the current capacity,
534 /// the capacity is increased to match the range's size. If the size of
535 /// the range is less than the current capacity, the cache's capacity is *not*
536 /// changed.
537 ///
538 /// \param range A range of pairs to assign to the cache.
539 /// \returns The cache instance.
540 template <typename Range, typename = Internal::enable_if_range<Range>>
541 BaseCache& operator=(const Range& range) {
542 _clear_and_increase_capacity(range);
543 insert(range);
544 return *this;
545 }
546
547 /// Sets the contents of the cache to an rvalue range.
548 ///
549 /// Pairs of the range are moved into the cache.
550 ///
551 /// \param range A range of pairs to assign to the cache.
552 /// \returns The cache instance.
553 template <typename Range, typename = Internal::enable_if_range<Range>>
554 BaseCache& operator=(Range&& range) {
555 _clear_and_increase_capacity(range);
556 insert(std::move(range));
557 return *this;
558 }
559
560 /// Sets the contents of the cache to pairs from a list.
561 ///
562 /// \param list The list to assign to the cache.
563 /// \returns The cache instance.
564 BaseCache& operator=(InitializerList list) {
565 return operator=<InitializerList>(list);
566 }
567
568 /// Swaps the contents of the cache with another cache.
569 ///
570 /// \param other The other cache to swap with.
571 virtual void swap(BaseCache& other) noexcept {
572 using std::swap;
573
574 swap(_order, other._order);
575 swap(_map, other._map);
576 swap(_last_accessed, other._last_accessed);
577 swap(_capacity, other._capacity);
578 }
579
580 /// Swaps the contents of one cache with another cache.
581 ///
582 /// \param first The first cache to swap.
583 /// \param second The second cache to swap.
584 friend void swap(BaseCache& first, BaseCache& second) noexcept {
585 first.swap(second);
586 }
587
588 /// Compares the cache for equality with another cache.
589 ///
590 /// \complexity O(N)
591 /// \param other The other cache to compare with.
592 /// \returns True if the keys __and values__ of the cache are identical to the
593 /// other, else false.
594 bool operator==(const BaseCache& other) const noexcept {
595 if (this == &other) return true;
596 if (this->_map != other._map) return false;
597 // clang-format off
598 return std::equal(
599 this->_order.begin(),
600 this->_order.end(),
601 other._order.begin(),
602 other._order.end(),
603 [](const auto& first, const auto& second) {
604 return first.get() == second.get();
605 });
606 // clang-format on
607 }
608
609 /// Compares the cache for inequality with another cache.
610 ///
611 /// \complexity O(N)
612 /// \param other The other cache to compare with.
613 /// \returns True if there is any mismatch in keys __or their values__
614 /// betweent
615 /// the two caches, else false.
616 bool operator!=(const BaseCache& other) const noexcept {
617 return !(*this == other);
618 }
619
620 /////////////////////////////////////////////////////////////////////////////
621 // ITERATOR INTERFACE
622 /////////////////////////////////////////////////////////////////////////////
623
624 /// \returns An unordered iterator to the beginning of the cache (this need
625 /// not be the first key inserted).
626 UnorderedIterator unordered_begin() noexcept {
627 return {*this, _map.begin()};
628 }
629
630 /// \returns A const unordered iterator to the beginning of the cache (this
631 /// need not be the key least recently inserted).
632 UnorderedConstIterator unordered_begin() const noexcept {
633 return unordered_cbegin();
634 }
635
636 /// \returns A const unordered iterator to the beginning of the cache (this
637 /// need not be the key least recently inserted).
638 UnorderedConstIterator unordered_cbegin() const noexcept {
639 return {*this, _map.cbegin()};
640 }
641
642 /// \returns An unordered iterator to the end of the cache (this
643 /// need not be one past the key most recently inserted).
644 UnorderedIterator unordered_end() noexcept {
645 return {*this, _map.end()};
646 }
647
648 /// \returns A const unordered iterator to the end of the cache (this
649 /// need not be one past the key most recently inserted).
650 UnorderedConstIterator unordered_end() const noexcept {
651 return unordered_cend();
652 }
653
654 /// \returns A const unordered iterator to the end of the cache (this
655 /// need not be one past the key most recently inserted).
656 UnorderedConstIterator unordered_cend() const noexcept {
657 return {*this, _map.cend()};
658 }
659
660 /// \returns An ordered iterator to the beginning of the cache (the key least
661 /// recently inserted).
662 OrderedIterator ordered_begin() noexcept {
663 return {*this, _order.begin()};
664 }
665
666 /// \returns A const ordered iterator to the beginning of the cache (the key
667 /// least recently inserted).
668 OrderedConstIterator ordered_begin() const noexcept {
669 return ordered_cbegin();
670 }
671
672 /// \returns A const ordered iterator to the beginning of the cache (the key
673 /// least recently inserted).
674 OrderedConstIterator ordered_cbegin() const noexcept {
675 return {*this, _order.cbegin()};
676 }
677
678 /// \returns An ordered iterator to the end of the cache (one past the key
679 /// most recently inserted).
680 OrderedIterator ordered_end() noexcept {
681 return {*this, _order.end()};
682 }
683
684 /// \returns A const ordered iterator to the end of the cache (one past the
685 /// key least recently inserted).
686 OrderedConstIterator ordered_end() const noexcept {
687 return ordered_cend();
688 }
689
690 /// \returns A const ordered iterator to the end of the cache (one past the
691 /// key least recently inserted).
692 OrderedConstIterator ordered_cend() const noexcept {
693 return {*this, _order.cend()};
694 }
695
696 /// \copydoc unordered_begin()
697 UnorderedIterator begin() noexcept {
698 return unordered_begin();
699 }
700
701 /// \copydoc unordered_cbegin()
702 UnorderedConstIterator begin() const noexcept {
703 return cbegin();
704 }
705
706 /// \copydoc unordered_cbegin()
707 UnorderedConstIterator cbegin() const noexcept {
708 return unordered_begin();
709 }
710
711 /// \copydoc unordered_end() const
712 UnorderedIterator end() noexcept {
713 return unordered_end();
714 }
715
716 /// \copydoc unordered_cend() const
717 UnorderedConstIterator end() const noexcept {
718 return cend();
719 }
720
721 /// \copydoc unordered_cend() const
722 UnorderedConstIterator cend() const noexcept {
723 return unordered_cend();
724 }
725
726 /// \returns True if the given iterator may be safely dereferenced, else
727 /// false.
728 /// \details Behavior is undefined if the iterator does not point into this
729 /// cache.
730 /// \param unordered_iterator The iterator to check.
731 virtual bool is_valid(UnorderedConstIterator unordered_iterator) const
732 noexcept {
733 return unordered_iterator != unordered_end();
734 }
735
736 /// \returns True if the given iterator may be safely dereferenced, else
737 /// false.
738 /// \details Behavior is undefined if the iterator does not point into this
739 /// cache.
740 /// \param ordered_iterator The iterator to check.
741 virtual bool is_valid(OrderedConstIterator ordered_iterator) const noexcept {
742 return ordered_iterator != ordered_end();
743 }
744
745 /// Checks if the given iterator may be dereferencend and throws an exception
746 /// if not.
747 ///
748 /// The exception thrown, if any, depends on the state of the iterator.
749 ///
750 /// \param unordered_iterator The iterator to check.
751 /// \throws LRU::Error::InvalidIterator if the iterator is the end iterator.
752 virtual void
753 throw_if_invalid(UnorderedConstIterator unordered_iterator) const {
754 if (unordered_iterator == unordered_end()) {
755 throw LRU::Error::InvalidIterator();
756 }
757 }
758
759 /// Checks if the given iterator may be dereferencend and throws an exception
760 /// if not.
761 ///
762 /// The exception thrown, if any, depends on the state of the iterator.
763 ///
764 /// \param ordered_iterator The iterator to check.
765 /// \throws LRU::Error::InvalidIterator if the iterator is the end iterator.
766 virtual void throw_if_invalid(OrderedConstIterator ordered_iterator) const {
767 if (ordered_iterator == ordered_end()) {
768 throw LRU::Error::InvalidIterator();
769 }
770 }
771
772 /////////////////////////////////////////////////////////////////////////////
773 // CACHE INTERFACE
774 /////////////////////////////////////////////////////////////////////////////
775
776 /// Tests if the given key is contained in the cache.
777 ///
778 /// This function may return false even if the key is actually currently
779 /// stored in the cache, but the concrete cache class places some additional
780 /// constraint as to when a key may be accessed (such as a time limit).
781 ///
782 /// \complexity O(1) expected and amortized.
783 /// \param key The key to check for.
784 /// \returns True if the key's value may be accessed via `lookup()` without an
785 /// error, else false.
786 virtual bool contains(const Key& key) const {
787 if (key == _last_accessed) {
788 if (_last_accessed_is_ok(key)) {
789 _register_hit(key, _last_accessed.value());
790 // If this is the last accessed key, it's at the front anyway
791 return true;
792 } else {
793 return false;
794 }
795 }
796
797 return find(key) != end();
798 }
799
800 /// Looks up the value for the given key.
801 ///
802 /// If the key is found in the cache, it is moved to the front. Any iterators
803 /// pointing to that key are still valid, but the subsequent order of
804 /// iteration may be different from what it was before.
805 ///
806 /// \complexity O(1) expected and amortized.
807 /// \param key The key whose value to look for.
808 /// \throws LRU::Error::KeyNotFound if the key's value may not be accessed.
809 /// \returns The value stored in the cache for the given key.
810 /// \see contains()
811 virtual const Value& lookup(const Key& key) const {
812 if (key == _last_accessed) {
813 auto& value = _value_for_last_accessed();
814 _register_hit(key, value);
815 // If this is the last accessed key, it's at the front anyway
816 return value;
817 }
818
819 auto iterator = find(key);
820 if (iterator == end()) {
821 throw LRU::Error::KeyNotFound();
822 } else {
823 return iterator.value();
824 }
825 }
826
827 /// Looks up the value for the given key.
828 ///
829 /// If the key is found in the cache, it is moved to the front. Any iterators
830 /// pointing to that key are still valid, but the subsequent order of
831 /// iteration may be different from what it was before.
832 ///
833 /// \complexity O(1) expected and amortized.
834 /// \param key The key whose value to look for.
835 /// \throws LRU::Error::KeyNotFound if the key's value may not be accessed.
836 /// \returns The value stored in the cache for the given key.
837 /// \see contains()
838 virtual Value& lookup(const Key& key) {
839 if (key == _last_accessed) {
840 auto& value = _value_for_last_accessed();
841 _register_hit(key, value);
842 // If this is the last accessed key, it's at the front anyway
843 return value;
844 }
845
846 auto iterator = find(key);
847 if (iterator == end()) {
848 throw LRU::Error::KeyNotFound();
849 } else {
850 return iterator.value();
851 }
852 }
853
854 /// Attempts to return an iterator to the given key in the cache.
855 ///
856 /// If the key is found in the cache, it is moved to the front. Any iterators
857 /// pointing to that key are still valid, but the subsequent order of
858 /// iteration may be different from what it was before.
859 ///
860 /// \complexity O(1) expected and amortized.
861 /// \param key The key whose value to look for.
862 /// \returns An iterator pointing to the entry with the given key, if one
863 /// exists, else the end iterator.
864 virtual UnorderedIterator find(const Key& key) = 0;
865
866 /// Attempts to return a const iterator to the given key in the cache.
867 ///
868 /// If the key is found in the cache, it is moved to the front. Any iterators
869 /// pointing to that key are still valid, but the subsequent order of
870 /// iteration may be different from what it was before.
871 ///
872 /// \complexity O(1) expected and amortized.
873 /// \param key The key whose value to look for.
874 /// \returns A const iterator pointing to the entry with the given key, if one
875 /// exists, else the end iterator.
876 virtual UnorderedConstIterator find(const Key& key) const = 0;
877
878 /// \copydoc lookup(const Key&)
879 virtual Value& operator[](const Key& key) {
880 return lookup(key);
881 }
882
883 /// \copydoc lookup(const Key&) const
884 virtual const Value& operator[](const Key& key) const {
885 return lookup(key);
886 }
887
888 /// Inserts the given `(key, value)` pair into the cache.
889 ///
890 /// If the cache's capacity is reached, the most recently used element will be
891 /// evicted. Any iterators pointing to that element will be invalidated.
892 /// Iterators pointing to other elements are not affected.
893 ///
894 /// \complexity O(1) expected and amortized.
895 /// \param key The key to insert.
896 /// \param value The value to insert with the key.
897 /// \returns An `InsertionResult`, holding a boolean indicating whether the
898 /// key was newly inserted (true) or only updated (false) as well as an
899 /// iterator pointing to the entry for the key.
900 virtual InsertionResultType insert(const Key& key, const Value& value) {
901 if (_capacity == 0) return {false, end()};
902
903 auto iterator = _map.find(key);
904
905 // To insert, we first check if the key is already present in the cache
906 // and if so, update its value and move its order iterator to the front
907 // of the queue. Else, we insert the key at the end of the queue and
908 // possibly pop the front if the cache has reached its capacity.
909
910 if (iterator == _map.end()) {
911 auto result = _map.emplace(key, Information(value));
912 assert(result.second);
913 auto order = _insert_new_key(result.first->first);
914 result.first->second.order = order;
915
916 _last_accessed = result.first;
917 return {true, {*this, result.first}};
918 } else {
919 _move_to_front(iterator, value);
920 _last_accessed = iterator;
921 return {false, {*this, iterator}};
922 }
923 }
924
925 /// Inserts a range of `(key, value)` pairs.
926 ///
927 /// If, at any point, the cache's capacity is reached, the most recently used
928 /// element will be evicted. Any iterators pointing to that element will
929 /// be invalidated. Iterators pointing to other elements are not affected.
930 ///
931 /// Note: This operation has no performance benefits over
932 /// element-wise insertion via `insert()`.
933 ///
934 /// \param begin An iterator for the start of the range to insert.
935 /// \param end An iterator for the end of the range to insert.
936 /// \returns The number of elements newly inserted (as opposed to only
937 /// updated).
938 template <typename Iterator,
939 typename = Internal::enable_if_iterator_over_pair<Iterator>>
940 size_t insert(Iterator begin, Iterator end) {
941 size_t newly_inserted = 0;
942 for (; begin != end; ++begin) {
943 const auto result = insert(begin->first, begin->second);
944 newly_inserted += result.was_inserted();
945 }
946
947 return newly_inserted;
948 }
949
950 /// Inserts a range of `(key, value)` pairs.
951 ///
952 /// If, at any point, the cache's capacity is reached, the most recently used
953 /// element will be evicted. Any iterators pointing to that element will
954 /// be invalidated. Iterators pointing to other elements are not affected.
955 ///
956 /// This operation has no performance benefits over
957 /// element-wise insertion via `insert()`.
958 ///
959 /// \param range The range of `(key, value)` pairs to insert.
960 /// \returns The number of elements newly inserted (as opposed to only
961 /// updated).
962 template <typename Range, typename = Internal::enable_if_range<Range>>
963 size_t insert(Range& range) {
964 using std::begin;
965 using std::end;
966
967 return insert(begin(range), end(range));
968 }
969
970 /// Moves the elements of the range into the cache.
971 ///
972 /// If, at any point, the cache's capacity is reached, the most recently used
973 /// element will be evicted. Any iterators pointing to that element will
974 /// be invalidated. Iterators pointing to other elements are not affected.
975 ///
976 /// \param range The range of `(key, value)` pairs to move into the cache.
977 /// \returns The number of elements newly inserted (as opposed to only
978 /// updated).
979 template <typename Range, typename = Internal::enable_if_range<Range>>
980 size_t insert(Range&& range) {
981 size_t newly_inserted = 0;
982 for (auto& pair : range) {
983 const auto result =
984 emplace(std::move(pair.first), std::move(pair.second));
985 newly_inserted += result.was_inserted();
986 }
987
988 return newly_inserted;
989 }
990
991 /// Inserts a list `(key, value)` pairs.
992 ///
993 /// If the cache's capacity is reached, the most recently used element will be
994 /// evicted (one or more times). Any iterators pointing to that element will
995 /// be invalidated. Iterators pointing to other elements are not affected.
996 ///
997 /// This operation has no performance benefits over
998 /// element-wise insertion via `insert()`.
999 ///
1000 /// \param list The list of `(key, value)` pairs to insert.
1001 /// \returns The number of elements newly inserted (as opposed to only
1002 /// updated).
1003 virtual size_t insert(InitializerList list) {
1004 return insert(list.begin(), list.end());
1005 }
1006
1007 /// Emplaces a new `(key, value)` pair into the cache.
1008 ///
1009 /// This emplacement function allows perfectly forwarding an arbitrary number
1010 /// of arguments to the constructor of both the key and value type, via
1011 /// appropriate tuples. The intended usage is with `std::forward_as_tuple`,
1012 /// for example:
1013 /// \code{.cpp}
1014 /// struct A { A(int, const std::string&) { } };
1015 /// struct B { B(double) {} };
1016 ///
1017 /// LRU::Cache<A> cache;
1018 ///
1019 /// cache.emplace(
1020 /// std::piecewise_construct,
1021 /// std::forward_as_tuple(1, "hello"),
1022 /// std::forward_as_tuple(5.0),
1023 /// );
1024 /// \endcode
1025 ///
1026 /// There is a convenience overload that requires much less overhead, if both
1027 /// constructors expect only a single argument.
1028 ///
1029 /// If the cache's capacity is reached, the most recently used element will be
1030 /// evicted. Any iterators pointing to that element will be invalidated.
1031 /// Iterators pointing to other elements are not affected.
1032 ///
1033 /// \complexity O(1) expected and amortized.
1034 /// \param _ A dummy parameter to work around overload resolution.
1035 /// \param key_arguments A tuple of arguments to construct a key object with.
1036 /// \param value_arguments A tuple of arguments to construct a value object
1037 /// with.
1038 /// \returns An `InsertionResult`, holding a boolean indicating whether the
1039 /// key was newly inserted (true) or only updated (false) as well as an
1040 /// iterator pointing to the entry for the key.
1041 template <typename... Ks, typename... Vs>
1042 InsertionResultType emplace(std::piecewise_construct_t _,
1043 const std::tuple<Ks...>& key_arguments,
1044 const std::tuple<Vs...>& value_arguments) {
1045 if (_capacity == 0) return {false, end()};
1046
1047 auto key = Internal::construct_from_tuple<Key>(key_arguments);
1048 auto iterator = _map.find(key);
1049
1050 if (iterator == _map.end()) {
1051 auto result = _map.emplace(std::move(key), Information(value_arguments));
1052 auto order = _insert_new_key(result.first->first);
1053 result.first->second.order = order;
1054 assert(result.second);
1055
1056 _last_accessed = result.first;
1057 return {true, {*this, result.first}};
1058 } else {
1059 auto value = Internal::construct_from_tuple<Value>(value_arguments);
1060 _move_to_front(iterator, value);
1061 _last_accessed = iterator;
1062 return {false, {*this, iterator}};
1063 }
1064 }
1065
1066 /// Emplaces a `(key, value)` pair.
1067 ///
1068 /// This is a convenience overload removing the necessity for
1069 /// `std::piecewise_construct` and `std::forward_as_tuple` that may be used in
1070 /// the case that both the key and value have constructors expecting only a
1071 /// single argument.
1072 ///
1073 /// If the cache's capacity is reached, the most recently used element will be
1074 /// evicted. Any iterators pointing to that element will be invalidated.
1075 /// Iterators pointing to other elements are not affected.
1076 ///
1077 /// \param key_argument The argument to construct a key object with.
1078 /// \param value_argument The argument to construct a value object with.
1079 /// \returns An `InsertionResult`, holding a boolean indicating whether the
1080 /// key was newly inserted (true) or only updated (false) as well as an
1081 /// iterator pointing to the entry for the key.
1082 template <typename K, typename V>
1083 InsertionResultType emplace(K&& key_argument, V&& value_argument) {
1084 auto key_tuple = std::forward_as_tuple(std::forward<K>(key_argument));
1085 auto value_tuple = std::forward_as_tuple(std::forward<V>(value_argument));
1086 return emplace(std::piecewise_construct, key_tuple, value_tuple);
1087 }
1088
1089 /// Erases the given key from the cache, if it is present.
1090 ///
1091 /// If the key is not present in the cache, this is a no-op.
1092 /// All iterators pointing to the given key are invalidated.
1093 /// Other iterators are not affected.
1094 ///
1095 /// \param key The key to erase.
1096 /// \returns True if the key was erased, else false.
1097 virtual bool erase(const Key& key) {
1098 // No need to use _last_accessed_is_ok here, because even
1099 // if it has expired, it's no problem to erase it anyway
1100 if (_last_accessed == key) {
1101 _erase(_last_accessed.key(), _last_accessed.information());
1102 return true;
1103 }
1104
1105 auto iterator = _map.find(key);
1106 if (iterator != _map.end()) {
1107 _erase(iterator);
1108 return true;
1109 }
1110
1111 return false;
1112 }
1113
1114 /// Erases the key pointed to by the given iterator.
1115 ///
1116 /// \param iterator The iterator whose key to erase.
1117 /// \throws LRU::Error::InvalidIterator if the iterator is the end iterator.
1118 virtual void erase(UnorderedConstIterator iterator) {
1119 /// We have this overload to avoid the extra conversion-construction from
1120 /// unordered to ordered iterator (and renewed hash lookup)
1121 if (iterator == unordered_cend()) {
1122 throw LRU::Error::InvalidIterator();
1123 } else {
1124 _erase(iterator._iterator);
1125 }
1126 }
1127
1128
1129 /// Erases the key pointed to by the given iterator.
1130 ///
1131 /// \param iterator The iterator whose key to erase.
1132 /// \throws LRU::Error::InvalidIterator if the iterator is the end iterator.
1133 virtual void erase(OrderedConstIterator iterator) {
1134 if (iterator == ordered_cend()) {
1135 throw LRU::Error::InvalidIterator();
1136 } else {
1137 _erase(_map.find(iterator.key()));
1138 }
1139 }
1140
1141 /// Clears the cache entirely.
1142 virtual void clear() {
1143 _map.clear();
1144 _order.clear();
1145 _last_accessed.invalidate();
1146 }
1147
1148 /// Requests shrinkage of the cache to the given size.
1149 ///
1150 /// If the passed size is 0, this operation is equivalent to `clear()`. If the
1151 /// size is greater than the current size, it is a no-op. Otherwise, the size
1152 /// of the cache is reduzed to the given size by repeatedly removing the least
1153 /// recent element.
1154 ///
1155 /// \param new_size The size to (maybe) shrink to.
1156 virtual void shrink(size_t new_size) {
1157 if (new_size >= size()) return;
1158 if (new_size == 0) {
1159 clear();
1160 return;
1161 }
1162
1163 while (size() > new_size) {
1164 _erase_lru();
1165 }
1166 }
1167
1168 /////////////////////////////////////////////////////////////////////////////
1169 // SIZE AND CAPACITY INTERFACE
1170 /////////////////////////////////////////////////////////////////////////////
1171
1172 /// \returns The number of keys present in the cache.
1173 virtual size_t size() const noexcept {
1174 return _map.size();
1175 }
1176
1177 /// Sets the capacity of the cache to the given value.
1178 ///
1179 /// If the given capacity is less than the current capacity of the cache,
1180 /// the least-recently inserted element is removed repeatedly until the
1181 /// capacity is equal to the given value.
1182 ///
1183 /// \param new_capacity The capacity to shrink or grow to.
1184 virtual void capacity(size_t new_capacity) {
1185 // Pop the front of the cache if we have to resize
1186 while (size() > new_capacity) {
1187 _erase_lru();
1188 }
1189 _capacity = new_capacity;
1190 }
1191
1192 /// Returns the current capacity of the cache.
1193 virtual size_t capacity() const noexcept {
1194 return _capacity;
1195 }
1196
1197 /// \returns the number of slots left in the cache.
1198 ///
1199 /// \details After this number of elements have been inserted, the next one
1200 /// insertion is preceded by an erasure of the least-recently inserted
1201 /// element.
1202 virtual size_t space_left() const noexcept {
1203 return _capacity - size();
1204 }
1205
1206 /// \returns True if the cache contains no elements, else false.
1207 virtual bool is_empty() const noexcept {
1208 return size() == 0;
1209 }
1210
1211 /// \returns True if the cache's size equals its capacity, else false.
1212 ///
1213 /// \details If `is_full()` returns `true`, the next insertion is preceded by
1214 /// an erasure of the least-recently inserted element.
1215 virtual bool is_full() const noexcept {
1216 return size() == _capacity;
1217 }
1218
1219 /// \returns The function used to hash keys.
1220 virtual HashFunction hash_function() const {
1221 return _map.hash_function();
1222 }
1223
1224 /// \returns The function used to compare keys.
1225 virtual KeyEqual key_equal() const {
1226 return _map.key_eq();
1227 }
1228
1229 /////////////////////////////////////////////////////////////////////////////
1230 // STATISTICS INTERFACE
1231 /////////////////////////////////////////////////////////////////////////////
1232
1233 /// Registers the given statistics object for monitoring.
1234 ///
1235 /// This method is useful if the statistics object is to
1236 /// be shared between caches.
1237 ///
1238 /// Ownership of the statistics object remains with the user and __not__ with
1239 /// the cache object. Also, behavior is undefined if the lifetime of the cache
1240 /// exceeds that of the registered statistics object.
1241 ///
1242 /// \param statistics The statistics object to register.
1243 virtual void monitor(const StatisticsPointer& statistics) {
1244 _stats = statistics;
1245 }
1246
1247 /// Registers the given statistics object for monitoring.
1248 ///
1249 /// Ownership of the statistics object is transferred to the cache.
1250 ///
1251 /// \param statistics The statistics object to register.
1252 virtual void monitor(StatisticsPointer&& statistics) {
1253 _stats = std::move(statistics);
1254 }
1255
1256 /// Constructs a new statistics in-place in the cache.
1257 ///
1258 /// This method is useful if the cache is to have exclusive ownership of the
1259 /// statistics and out-of-place construction and move is inconvenient.
1260 ///
1261 /// \param args Arguments to be forwarded to the constructor of the statistics
1262 /// object.
1263 template <typename... Args,
1264 typename = std::enable_if_t<
1265 Internal::none_of_type<StatisticsPointer, Args...>>>
1266 void monitor(Args&&... args) {
1267 _stats = std::make_shared<Statistics<Key>>(std::forward<Args>(args)...);
1268 }
1269
1270 /// Stops any monitoring being performed with a statistics object.
1271 ///
1272 /// If the cache is not currently monitoring at all, this is a no-op.
1273 virtual void stop_monitoring() {
1274 _stats.reset();
1275 }
1276
1277 /// \returns True if the cache is currently monitoring statistics, else
1278 /// false.
1279 bool is_monitoring() const noexcept {
1280 return _stats.has_stats();
1281 }
1282
1283 /// \returns The statistics object currently in use by the cache.
1284 /// \throws LRU::Error::NotMonitoring if the cache is currently not
1285 /// monitoring.
1286 virtual Statistics<Key>& stats() {
1287 if (!is_monitoring()) {
1288 throw LRU::Error::NotMonitoring();
1289 }
1290 return _stats.get();
1291 }
1292
1293 /// \returns The statistics object currently in use by the cache.
1294 /// \throws LRU::Error::NotMonitoring if the cache is currently not
1295 /// monitoring.
1296 virtual const Statistics<Key>& stats() const {
1297 if (!is_monitoring()) {
1298 throw LRU::Error::NotMonitoring();
1299 }
1300 return _stats.get();
1301 }
1302
1303 /// \returns A `shared_ptr` to the statistics currently in use by the cache.
1304 virtual StatisticsPointer& shared_stats() {
1305 return _stats.shared();
1306 }
1307
1308 /// \returns A `shared_ptr` to the statistics currently in use by the cache.
1309 virtual const StatisticsPointer& shared_stats() const {
1310 return _stats.shared();
1311 }
1312
1313 /////////////////////////////////////////////////////////////////////////////
1314 // CALLBACK INTERFACE
1315 /////////////////////////////////////////////////////////////////////////////
1316
1317 /// Registers a new hit callback.
1318 ///
1319 /// \param hit_callback The hit callback function to register with the cache.
1320 template <typename Callback,
1321 typename = Internal::enable_if_same<HitCallback, Callback>>
1322 void hit_callback(Callback&& hit_callback) {
1323 _callback_manager.hit_callback(std::forward<Callback>(hit_callback));
1324 }
1325
1326 /// Registers a new miss callback.
1327 ///
1328 /// \param miss_callback The miss callback function to register with the
1329 /// cache.
1330 template <typename Callback,
1331 typename = Internal::enable_if_same<MissCallback, Callback>>
1332 void miss_callback(Callback&& miss_callback) {
1333 _callback_manager.miss_callback(std::forward<Callback>(miss_callback));
1334 }
1335
1336 /// Registers a new access callback.
1337 ///
1338 /// \param access_callback The access callback function to register with the
1339 /// cache.
1340 template <typename Callback,
1341 typename = Internal::enable_if_same<AccessCallback, Callback>>
1342 void access_callback(Callback&& access_callback) {
1343 _callback_manager.access_callback(std::forward<Callback>(access_callback));
1344 }
1345
1346 /// Clears all hit callbacks.
1347 void clear_hit_callbacks() {
1348 _callback_manager.clear_hit_callbacks();
1349 }
1350
1351 /// Clears all miss callbacks.
1352 void clear_miss_callbacks() {
1353 _callback_manager.clear_miss_callbacks();
1354 }
1355
1356 /// Clears all access callbacks.
1357 void clear_access_callbacks() {
1358 _callback_manager.clear_access_callbacks();
1359 }
1360
1361 /// Clears all callbacks.
1362 void clear_all_callbacks() {
1363 _callback_manager.clear();
1364 }
1365
1366 /// \returns All hit callbacks.
1367 const HitCallbackContainer& hit_callbacks() const noexcept {
1368 return _callback_manager.hit_callbacks();
1369 }
1370
1371 /// \returns All miss callbacks.
1372 const MissCallbackContainer& miss_callbacks() const noexcept {
1373 return _callback_manager.miss_callbacks();
1374 }
1375
1376 /// \returns All access callbacks.
1377 const AccessCallbackContainer& access_callbacks() const noexcept {
1378 return _callback_manager.access_callbacks();
1379 }
1380
1381 protected:
1382 // The ordered iterators need to perform lookups without changing
1383 // the order of elements or affecting statistics.
1384 template <typename, typename, typename>
1385 friend class BaseOrderedIterator;
1386
1387 using MapInsertionResult = decltype(Map().emplace());
1388 using LastAccessed =
1389 typename Internal::LastAccessed<Key, Information, KeyEqual>;
1390
1391 /// Moves the key pointed to by the iterator to the front of the order.
1392 ///
1393 /// \param iterator The iterator pointing to the key to move.
1394 virtual void _move_to_front(QueueIterator iterator) const {
1395 if (size() == 1) return;
1396 // Extract the current linked-list node and insert (splice it) at the end
1397 // The original iterator is not invalidated and now points to the new
1398 // position (which is still the same node).
1399 _order.splice(_order.end(), _order, iterator);
1400 }
1401
1402 /// Moves the key pointed to by the iterator to the front of the order and
1403 /// assigns a new value.
1404 ///
1405 /// \param iterator The iterator pointing to the key to move.
1406 /// \param new_value The updated value to move the key with.
1407 virtual void _move_to_front(MapIterator iterator, const Value& new_value) {
1408 // Extract the current linked-list node and insert (splice it) at the end
1409 // The original iterator is not invalidated and now points to the new
1410 // position (which is still the same node).
1411 _move_to_front(iterator->second.order);
1412 iterator->second.value = new_value;
1413 }
1414
1415 /// Erases the element most recently inserted into the cache.
1416 virtual void _erase_lru() {
1417 _erase(_map.find(_order.front()));
1418 }
1419
1420 /// Erases the element pointed to by the iterator.
1421 ///
1422 /// \param iterator The iterator pointing to the key to erase.
1423 virtual void _erase(MapConstIterator iterator) {
1424 if (_last_accessed == iterator) {
1425 _last_accessed.invalidate();
1426 }
1427
1428 _order.erase(iterator->second.order);
1429 _map.erase(iterator);
1430 }
1431
1432 /// Erases the given key.
1433 ///
1434 /// This method is useful if the key and information are already present, to
1435 /// avoid an additional hash lookup to get an iterator to the corresponding
1436 /// map entry.
1437 ///
1438 /// \param key The key to erase.
1439 /// \param information The information associated with the key to erase.
1440 virtual void _erase(const Key& key, const Information& information) {
1441 if (key == _last_accessed) {
1442 _last_accessed.invalidate();
1443 }
1444
1445 // To be sure, we should do this first, since the order stores a reference
1446 // to the key in the map.
1447 _order.erase(information.order);
1448
1449 // Requires an additional hash-lookup, whereas erase(iterator) doesn't
1450 _map.erase(key);
1451 }
1452
1453 /// Convenience methhod to get the value for an insertion result into a map.
1454 /// \returns The value for the given result.
1455 virtual Value& _value_from_result(MapInsertionResult& result) noexcept {
1456 // `result.first` is the map iterator (to a pair), whose `second` member
1457 // is
1458 // the information object, whose `value` member is the value stored.
1459 return result.first->second.value;
1460 }
1461
1462 /// The main use of this method is that it may be override by a base class
1463 /// if
1464 /// there are any stronger constraints (such as time expiration) as to when
1465 /// the last-accessed object may be used to access a key.
1466 ///
1467 /// \param key The key to compare the last accessed object against.
1468 /// \returns True if the last-accessed object is valid.
1469 virtual bool _last_accessed_is_ok(const Key& key) const noexcept {
1470 return true;
1471 }
1472
1473 /// \copydoc _value_for_last_accessed() const
1474 virtual Value& _value_for_last_accessed() {
1475 return _last_accessed.value();
1476 }
1477
1478 /// Attempts to access the last accessed key's value.
1479 /// \returns The value of the last accessed object.
1480 /// \details This method exists so that derived classes may perform
1481 /// additional
1482 /// checks (and possibly throw exceptions) or perform other operations to
1483 /// retrieve the value.
1484 virtual const Value& _value_for_last_accessed() const {
1485 return _last_accessed.value();
1486 }
1487
1488 /// Registers a hit for the key and performs appropriate actions.
1489 /// \param key The key to register a hit for.
1490 /// \param value The value that was found for the key.
1491 virtual void _register_hit(const Key& key, const Value& value) const {
1492 if (is_monitoring()) {
1493 _stats.register_hit(key);
1494 }
1495
1496 _callback_manager.hit(key, value);
1497 }
1498
1499 /// Registers a miss for the key and performs appropriate actions.
1500 /// \param key The key to register a miss for.
1501 virtual void _register_miss(const Key& key) const {
1502 if (is_monitoring()) {
1503 _stats.register_miss(key);
1504 }
1505
1506 _callback_manager.miss(key);
1507 }
1508
1509 /// The common part of both range assignment operators.
1510 ///
1511 /// \param range The range to assign to.
1512 template <typename Range>
1513 void _clear_and_increase_capacity(const Range& range) {
1514 using std::begin;
1515 using std::end;
1516
1517 clear();
1518
1519 auto distance = std::distance(begin(range), end(range));
1520 if (distance > _capacity) {
1521 _capacity = distance;
1522 }
1523 }
1524
1525 /// Looks up each key in the queue and re-assigns it to the proper key in the
1526 /// map.
1527 ///
1528 /// After a copy, the reference (wrappers) in the order queue point
1529 /// to the keys of the other cache's map. Thus we need to re-assign them.
1530 void _reassign_references() noexcept {
1531 for (auto& key_reference : _order) {
1532 key_reference = std::ref(_map.find(key_reference)->first);
1533 }
1534 }
1535
1536 /// Inserts a new key into the queue.
1537 ///
1538 /// If the cache is full, the LRU node is re-used.
1539 /// Else a node is inserted at the order.
1540 ///
1541 /// \returns The resulting iterator.
1542 QueueIterator _insert_new_key(const Key& key) {
1543 if (_is_too_full()) {
1544 _evict_lru_for(key);
1545 } else {
1546 _order.emplace_back(key);
1547 }
1548
1549 return std::prev(_order.end());
1550 }
1551
1552 /// Evicts the LRU element for the given new key.
1553 ///
1554 /// \param key The new key to insert into the queue.
1555 void _evict_lru_for(const Key& key) {
1556 _map.erase(_order.front());
1557 _order.front() = std::ref(key);
1558 _move_to_front(_order.begin());
1559 }
1560
1561 /// \returns True if the cache is too full and an element must be evicted,
1562 /// else false.
1563 bool _is_too_full() const noexcept {
1564 return size() > _capacity;
1565 }
1566
1567 /// The map from keys to information objects.
1568 Map _map;
1569
1570 /// The queue keeping track of the insertion order of elements.
1571 mutable Queue _order;
1572
1573 /// The object to mutate statistics if any are registered.
1574 mutable StatisticsMutator<Key> _stats;
1575
1576 /// The last-accessed cache object.
1577 mutable LastAccessed _last_accessed;
1578
1579 /// The callback manager to store any callbacks.
1580 mutable CallbackManagerType _callback_manager;
1581
1582 /// The current capacity of the cache.
1583 size_t _capacity;
1584 };
1585 } // namespace Internal
1586 } // namespace LRU
1587
1588 #endif // LRU_INTERNAL_BASE_CACHE_HPP