Created
July 30, 2022 13:15
-
-
Save oberrich/fe03118bf38cbc560fffbb7f1311a71d to your computer and use it in GitHub Desktop.
A simple statically allocated cache, auto-clears on overflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename ValT, std::size_t Capacity> | |
class StaticCache { | |
public: | |
ValT &operator[](std::uint32_t hash) { | |
for (std::size_t i = 0; i < num_entries; ++i) { | |
if (entries[i].hash == hash) return entries[i].value; | |
} | |
if (++num_entries > Capacity) num_entries = 1; | |
auto &entry = entries[num_entries - 1]; | |
entry.hash = hash; | |
entry.value = ValT{}; | |
return entry.value; | |
} | |
void clear() { num_entries = 0; } | |
private: | |
struct Entry { | |
std::uint32_t hash; | |
ValT value; | |
}; | |
Entry entries[Capacity]; | |
std::size_t num_entries{}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment