Skip to content

Instantly share code, notes, and snippets.

@oberrich
Created July 30, 2022 13:15
Show Gist options
  • Save oberrich/fe03118bf38cbc560fffbb7f1311a71d to your computer and use it in GitHub Desktop.
Save oberrich/fe03118bf38cbc560fffbb7f1311a71d to your computer and use it in GitHub Desktop.
A simple statically allocated cache, auto-clears on overflow
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