MCPcopy Create free account
hub / github.com/comaps/comaps / Cache

Class Cache

libs/base/cache.hpp:15–102  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13// Simple cache that stores list of values.
14template <typename KeyT, typename ValueT>
15class Cache
16{
17 DISALLOW_COPY(Cache);
18
19public:
20 Cache() = default;
21 Cache(Cache && r) = default;
22
23 /// @param[in] logCacheSize is pow of two for number of elements in cache.
24 explicit Cache(uint32_t logCacheSize) { Init(logCacheSize); }
25
26 /// @param[in] logCacheSize is pow of two for number of elements in cache.
27 void Init(uint32_t logCacheSize)
28 {
29 ASSERT(logCacheSize > 0 && logCacheSize < 32, (logCacheSize));
30 static_assert((std::is_same<KeyT, uint32_t>::value || std::is_same<KeyT, uint64_t>::value), "");
31
32 m_cache.reset(new Data[1 << logCacheSize]);
33 m_hashMask = (1 << logCacheSize) - 1;
34
35 Reset();
36 }
37
38 uint32_t GetCacheSize() const { return m_hashMask + 1; }
39
40 // Find value by @key. If @key is found, returns reference to its value.
41 // If @key is not found, some other key is removed and it's value is reused without
42 // re-initialization. It's up to caller to re-initialize the new value if @found == false.
43 // TODO: Return pair<ValueT *, bool> instead?
44 ValueT & Find(KeyT const & key, bool & found)
45 {
46 Data & data = m_cache[Index(key)];
47 if (data.m_Key == key)
48 {
49 found = true;
50 }
51 else
52 {
53 found = false;
54 data.m_Key = key;
55 }
56 return data.m_Value;
57 }
58
59 template <typename F>
60 void ForEachValue(F && f)
61 {
62 for (uint32_t i = 0; i <= m_hashMask; ++i)
63 f(m_cache[i].m_Value);
64 }
65
66 void Reset()
67 {
68 // Initialize m_Cache such, that Index(m_Cache[i].m_Key) != i.
69 for (uint32_t i = 0; i <= m_hashMask; ++i)
70 {
71 KeyT & key = m_cache[i].m_Key;
72 for (key = 0; Index(key) == i; ++key)

Callers 2

CacheStaticGeometryMethod · 0.50
CacheDynamicGeometryMethod · 0.50

Calls 1

IndexClass · 0.50

Tested by

no test coverage detected