#ifndef MAPCACHE_H #define MAPCACHE_H #include #include #include #include #include #include "icache.h" /* Thread-Safe Key-Value store */ template class MapCache { private: std::unordered_map cache; mutable std::shared_mutex sharedMutex; public: std::optional find(const std::string &key) const { std::shared_lock lock(this->sharedMutex); auto it = this->cache.find(key); if(it != this->cache.end()) { return it->second; } return {}; } void set(const std::string &key, const T &val) { std::lock_guard lock{sharedMutex}; this->cache[key] = val; } void clear() { std::lock_guard lock{sharedMutex}; this->cache.clear(); } void remove(const std::string &key) { std::lock_guard lock{sharedMutex}; this->cache.erase(key); } void removePrefix(const std::string &key) { std::lock_guard lock{sharedMutex}; std::erase_if(this->cache, [key](const auto &item) { auto const& [k, v] = item; return k.starts_with(std::string_view(key)); }); } }; class StringCache : public MapCache, public ICache { virtual std::optional get(std::string_view key) const override { return MapCache::find(std::string(key)); } virtual void put(std::string_view key, std::string val) override { MapCache::set(std::string(key), val); } virtual void remove(std::string_view key) override { MapCache::remove(std::string(key)); } virtual void removePrefix(std::string_view prefix) { MapCache::removePrefix(std::string(prefix)); } virtual void clear() override { MapCache::clear(); } }; #endif // MAPCACHE_H