Created
July 4, 2024 20:30
-
-
Save valmat/03f2c665725e7821cbf70880a25b6801 to your computer and use it in GitHub Desktop.
LockedKv is a thread safe wrapper on a KV storage
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
#pragma once | |
#include <mutex> | |
#include <utility> | |
#include <type_traits> | |
namespace details { | |
template <typename T, typename = void> | |
struct has_del_method : std::false_type {}; | |
template <typename T> | |
struct has_del_method<T, std::void_t<decltype(std::declval<T&>().del(std::declval<int&>()))>> : std::true_type {}; | |
} | |
template<typename T> | |
class LockedKv final | |
{ | |
public: | |
template<typename... Args> | |
explicit LockedKv(Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args&&...>) : | |
_kv(std::forward<Args>(args)...) {} | |
template<typename... Args> | |
auto get(Args&&... args) noexcept(noexcept(std::declval<T&>().get(std::forward<Args>(args)...))) | |
{ | |
std::lock_guard<std::mutex> lock(_mutex); | |
return _kv.get(std::forward<Args>(args)...); | |
} | |
template<typename... Args> | |
auto set(Args&&... args) noexcept(noexcept(std::declval<T&>().set(std::forward<Args>(args)...))) | |
{ | |
std::lock_guard<std::mutex> lock(_mutex); | |
return _kv.set(std::forward<Args>(args)...); | |
} | |
template<typename... Args> | |
auto del(Args&&... args) noexcept(noexcept(std::declval<T&>().del(std::forward<Args>(args)...))) -> | |
std::enable_if_t<details::has_del_method<T>::value, decltype(std::declval<T&>().del(std::forward<Args>(args)...))> | |
{ | |
std::lock_guard<std::mutex> lock(_mutex); | |
return _kv.del(std::forward<Args>(args)...); | |
} | |
private: | |
T _kv; | |
mutable std::mutex _mutex; | |
}; | |
// Deduction guide | |
template <typename T> | |
LockedKv(T) -> LockedKv<T>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment