|
| 1 | +// |
| 2 | +// cache.hpp |
| 3 | +// hasht |
| 4 | +// |
| 5 | +// Created by Paul Bowen-Huggett on 24/10/2024. |
| 6 | +// |
| 7 | + |
| 8 | +#ifndef CACHE_HPP |
| 9 | +#define CACHE_HPP |
| 10 | + |
| 11 | +#include <cassert> |
| 12 | +#include <cstddef> |
| 13 | +#include <ostream> |
| 14 | +#include <utility> |
| 15 | + |
| 16 | +#include "iumap.hpp" |
| 17 | +#include "lru_list.hpp" |
| 18 | + |
| 19 | +template <typename Key, typename Mapped, std::size_t Size> class cache { |
| 20 | +public: |
| 21 | + using key_type = Key; |
| 22 | + using mapped_type = Mapped; |
| 23 | + using value_type = std::pair<key_type, mapped_type>; |
| 24 | + |
| 25 | + mapped_type *find(key_type const &k); |
| 26 | + bool set(key_type const &k, mapped_type const &v); |
| 27 | + |
| 28 | + void dump(std::ostream &os) { |
| 29 | + lru.dump(os); |
| 30 | + h.dump(os); |
| 31 | + } |
| 32 | + |
| 33 | +private: |
| 34 | + using lru_container = lru_list<value_type, Size>; |
| 35 | + |
| 36 | + lru_container lru; |
| 37 | + iumap<Key const, typename decltype(lru)::node *, Size> h; |
| 38 | +}; |
| 39 | + |
| 40 | +template <typename Key, typename Mapped, std::size_t Size> |
| 41 | +auto cache<Key, Mapped, Size>::find(key_type const &k) -> mapped_type * { |
| 42 | + auto const pos = h.find(k); |
| 43 | + if (pos == h.end()) { |
| 44 | + return nullptr; |
| 45 | + } |
| 46 | + auto *const node = pos->second; |
| 47 | + lru.touch(*node); |
| 48 | + assert(lru.size() == h.size()); |
| 49 | + return &(static_cast<value_type &>(*node).second); |
| 50 | +} |
| 51 | + |
| 52 | +template <typename Key, typename Mapped, std::size_t Size> |
| 53 | +bool cache<Key, Mapped, Size>::set(key_type const &k, mapped_type const &v) { |
| 54 | + auto pos = h.find(k); |
| 55 | + if (pos == h.end()) { |
| 56 | + auto const fn = [this](value_type &kvp) { |
| 57 | + // delete the key being evicted from the LUR-list from the hash table so that |
| 58 | + // they always match. |
| 59 | + if (auto const evict_pos = this->h.find(kvp.first); evict_pos != this->h.end()) { |
| 60 | + this->h.erase(evict_pos); |
| 61 | + } |
| 62 | + }; |
| 63 | + h.insert(std::make_pair(k, &lru.add(std::make_pair(k, v), fn))); |
| 64 | + assert(lru.size() == h.size()); |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + // The key _was_ found in the cache. |
| 69 | + typename lru_container::node &lru_entry = *pos->second; |
| 70 | + lru.touch(lru_entry); |
| 71 | + auto &cached_value = static_cast<value_type &>(lru_entry).second; |
| 72 | + if (cached_value == v) { |
| 73 | + // The key was in the cache and the values are equal. |
| 74 | + assert(lru.size() == h.size()); |
| 75 | + return true; |
| 76 | + } |
| 77 | + cached_value = v; |
| 78 | + assert(lru.size() == h.size()); |
| 79 | + return false; |
| 80 | +} |
| 81 | + |
| 82 | +#endif // CACHE_HPP |
0 commit comments