boat
C++23 geospatial library
Loading...
Searching...
No Matches
lru.hpp
Go to the documentation of this file.
1// Andrew Naplavkov
2
3#ifndef BOAT_GUI_CACHES_LRU_HPP
4#define BOAT_GUI_CACHES_LRU_HPP
5
7#include <boost/multi_index/hashed_index.hpp>
8#include <boost/multi_index/key.hpp>
9#include <boost/multi_index/sequenced_index.hpp>
10#include <boost/multi_index_container.hpp>
11#include <mutex>
12#include <utility>
13
14namespace boat::gui::caches {
15
17class lru : public cache {
18 using entry = std::pair<any_hashable, std::any>;
19 mutable std::mutex guard_;
20 cache_stats stats_;
21 size_t capacity_;
22 boost::multi_index_container<
23 entry,
24 boost::multi_index::indexed_by<
25 boost::multi_index::sequenced<>,
26 boost::multi_index::hashed_unique<
27 boost::multi_index::key<&entry::first>>>>
28 data_;
29
30public:
31 explicit lru(size_t capacity) : capacity_{capacity} {}
32
33 std::any get(any_hashable const& key) override
34 {
35 auto lock = std::lock_guard{guard_};
36 ++stats_.requests;
37 auto& index = data_.get<1>();
38 if (auto it = index.find(key); it != index.end()) {
39 data_.relocate(data_.end(), data_.project<0>(it));
40 stats_.misses += !it->second.has_value();
41 return it->second;
42 }
43 ++stats_.misses;
44 return {};
45 }
46
47 void put(any_hashable key, std::any val) override
48 {
49 auto lock = std::lock_guard{guard_};
50 auto it = data_.push_back({std::move(key), {}}).first;
51 data_.replace(it, {it->first, std::move(val)});
52 data_.relocate(data_.end(), it);
53 if (data_.size() > capacity_)
54 data_.pop_front();
55 }
56
57 cache_stats stats() const override
58 {
59 auto lock = std::lock_guard{guard_};
60 return stats_;
61 }
62};
63
64} // namespace boat::gui::caches
65
66#endif // BOAT_GUI_CACHES_LRU_HPP
void put(any_hashable key, std::any val) override
Definition lru.hpp:47
std::any get(any_hashable const &key) override
Returns empty on a miss.
Definition lru.hpp:33
cache_stats stats() const override
Definition lru.hpp:57
lru(size_t capacity)
Definition lru.hpp:31
Definition cache.hpp:9
Counts get() calls and misses.
Definition cache.hpp:12
Definition cache.hpp:17