Ultra 0.9.4
Loading...
Searching...
No Matches
cache.h
Go to the documentation of this file.
1
12
13#if !defined(ULTRA_CACHE_H)
14#define ULTRA_CACHE_H
15
16#include <algorithm>
17#include <bit>
18#include <mutex>
19#include <optional>
20#include <shared_mutex>
21#include <vector>
22
23#include "kernel/fitness.h"
24#include "kernel/hash_t.h"
25
26namespace ultra
27{
28
30using bitwidth = unsigned;
39
48template<Fitness F, std::size_t LOCK_GROUP_SIZE = 128>
49class cache
50{
51public:
52 // ---- Constructors ----
53 cache() = default; // empty cache
54 explicit cache(bitwidth);
55
56 // ---- Capacity ----
57 [[nodiscard]] bitwidth bits() const;
59 // ---- Modifiers ----
61 void clear() noexcept;
62 void clear(const hash_t &);
63 void insert(const hash_t &, const F &);
64
65 // ---- Misc ----
66 [[nodiscard]] std::optional<F> find(const hash_t &) const;
67
68 [[nodiscard]] bool is_valid() const;
69
70 // ---- Serialization ----
71 bool load(std::istream &);
72 bool save(std::ostream &) const;
73
74private:
75 static constexpr bitwidth max_cache_bitwidth {30}; // about 1 billion slots
77 // ---- Private support methods ----
78 [[nodiscard]] std::size_t index(const hash_t &) const noexcept;
79 [[nodiscard]] std::size_t lock_index(std::size_t) const noexcept;
80 [[nodiscard]] static std::size_t table_size(bitwidth);
81
82 // ---- Private data members ----
83 struct slot
84 {
86 hash_t hash;
88 F fitness;
90 unsigned seal {0};
91 };
92
93 std::vector<slot> table_ {};
94 mutable std::vector<std::shared_mutex> locks_ {}; // group-level locks
95
96 std::uint64_t k_mask {0};
97 decltype(slot::seal) seal_ {1};
98
99 // Check the number of slots per lock.
100 static_assert(LOCK_GROUP_SIZE > 0, "LOCK_GROUP_SIZE must be greater than 0");
101};
102
103#include "kernel/cache.tcc"
104
105} // namespace ultra
106
107#endif // include guard
std::optional< F > find(const hash_t &) const
Definition cache.h:158
bool is_valid() const
Definition cache.h:276
void clear() noexcept
Definition cache.h:120
void insert(const hash_t &, const F &)
Definition cache.h:181
bool load(std::istream &)
Definition cache.h:204
void resize(bitwidth)
Definition cache.h:76
bool save(std::ostream &) const
Definition cache.h:238
bitwidth bits() const
Definition cache.h:264
STL namespace.
unsigned bitwidth
Type alias for the number of bits.
Definition cache.h:30
Definition hash_t.h:34