27#include <unordered_map>
30template <
typename Key,
typename Value>
class Cache {
31 using map_type = std::unordered_map<Key, typename std::add_const_t<Value>>;
41 m_max_size = m_cache.max_size();
52 std::minstd_rand m_rand;
62 void drop_random_element() {
66 auto const bucket_count = m_cache.bucket_count();
72 std::uniform_int_distribution<size_type>{0, bucket_count - 1}(m_rand);
74 while (0 == m_cache.bucket_size(bucket)) {
76 bucket = ((bucket + 1) % bucket_count);
80 auto const elem_index = std::uniform_int_distribution<size_type>{
81 0, m_cache.bucket_size(bucket) - 1}(m_rand);
85 std::next(m_cache.cbegin(bucket),
static_cast<long>(elem_index))->first;
88 m_cache.erase(drop_key);
99 bool has(Key
const &k)
const {
return m_cache.contains(k); }
113 template <
typename ValueRef> Value
const *
put(Key
const &k, ValueRef &&v) {
114 auto check_for_k =
true;
119 if ((m_cache.size() >= m_max_size) && !
has(k)) {
120 drop_random_element();
124 if (check_for_k &&
has(k)) {
128 typename map_type::const_iterator it;
129 std::tie(it, std::ignore) = m_cache.emplace(k, std::forward<ValueRef>(v));
131 return &(it->second);
149 template <
typename KeyInputIterator,
typename ValueInputIterator>
150 KeyInputIterator
put(KeyInputIterator kbegin, KeyInputIterator kend,
151 ValueInputIterator vbegin) {
152 auto const range_len = std::distance(kbegin, kend);
153 auto const size_max =
static_cast<decltype(range_len)
>(
max_size());
154 auto const len = (range_len > size_max) ? size_max : range_len;
155 kend = std::next(kbegin, len);
158 while (
static_cast<decltype(len)
>(
max_size() -
size()) < len) {
159 drop_random_element();
162 while (kbegin != kend) {
163 put(*kbegin++, *vbegin++);
175 Value
const *
get(Key
const &k)
const {
176 auto const needle = m_cache.find(k);
178 if (m_cache.end() != needle) {
179 return &(needle->second);
bool has(Key const &k) const
Query if k is contained in the cache.
void invalidate()
Clear the cache.
typename map_type::size_type size_type
size_type size() const
Number of elements currently cached.
Cache(size_type max_size)
KeyInputIterator put(KeyInputIterator kbegin, KeyInputIterator kend, ValueInputIterator vbegin)
Put a range of values into the cache.
Value const * put(Key const &k, ValueRef &&v)
Put a value into the cache.
Value const * get(Key const &k) const
Get a value.
size_type max_size() const
Maximal size of the cache.