88 line
1.8 KiB
C++
88 line
1.8 KiB
C++
#ifndef MAPCACHE_H
|
|
#define MAPCACHE_H
|
|
#include <map>
|
|
#include <set>
|
|
#include <shared_mutex>
|
|
#include <optional>
|
|
#include <string>
|
|
#include "icache.h"
|
|
|
|
/* Thread-Safe Key-Value store */
|
|
template <class T> class MapCache
|
|
{
|
|
private:
|
|
std::unordered_map<std::string, T> cache;
|
|
mutable std::shared_mutex sharedMutex;
|
|
|
|
public:
|
|
std::optional<T> find(const std::string &key) const
|
|
{
|
|
std::shared_lock<std::shared_mutex> 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<std::shared_mutex> lock{sharedMutex};
|
|
this->cache[key] = val;
|
|
}
|
|
void clear()
|
|
{
|
|
std::lock_guard<std::shared_mutex> lock{sharedMutex};
|
|
this->cache.clear();
|
|
}
|
|
|
|
void remove(const std::string &key)
|
|
{
|
|
std::lock_guard<std::shared_mutex> lock{sharedMutex};
|
|
this->cache.erase(key);
|
|
}
|
|
|
|
void removePrefix(const std::string &key)
|
|
{
|
|
std::lock_guard<std::shared_mutex> 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<std::string>, public ICache
|
|
{
|
|
virtual std::optional<std::string> get(std::string_view key) const override
|
|
{
|
|
return MapCache<std::string>::find(std::string(key));
|
|
}
|
|
|
|
virtual void put(std::string_view key, std::string val) override
|
|
{
|
|
MapCache<std::string>::set(std::string(key), val);
|
|
}
|
|
|
|
virtual void remove(std::string_view key) override
|
|
{
|
|
MapCache<std::string>::remove(std::string(key));
|
|
}
|
|
|
|
virtual void removePrefix(std::string_view prefix)
|
|
{
|
|
MapCache<std::string>::removePrefix(std::string(prefix));
|
|
}
|
|
|
|
virtual void clear() override
|
|
{
|
|
MapCache<std::string>::clear();
|
|
}
|
|
|
|
};
|
|
|
|
#endif // MAPCACHE_H
|