cache: Introduce StringCache, switch to unordered_map, default to memory cache if fs cache dir not given
This commit is contained in:
50
cache/mapcache.h
vendored
50
cache/mapcache.h
vendored
@ -5,12 +5,13 @@
|
||||
#include <shared_mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include "icache.h"
|
||||
|
||||
/* Thread-Safe Key-Value store */
|
||||
template <class T> class MapCache
|
||||
{
|
||||
private:
|
||||
std::map<std::string, T> cache;
|
||||
std::unordered_map<std::string, T> cache;
|
||||
mutable std::shared_mutex sharedMutex;
|
||||
|
||||
public:
|
||||
@ -34,6 +35,53 @@ template <class T> class MapCache
|
||||
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
|
||||
|
Reference in New Issue
Block a user