mirror-chatterino2/src/common/UniqueAccess.hpp

102 lines
1.5 KiB
C++
Raw Normal View History

2018-07-14 14:24:18 +02:00
#pragma once
#include <mutex>
#include <type_traits>
namespace chatterino {
template <typename T>
class AccessGuard
{
public:
AccessGuard(T &element, std::mutex &mutex)
: element_(element)
, mutex_(mutex)
{
this->mutex_.lock();
}
~AccessGuard()
{
this->mutex_.unlock();
}
2018-07-15 20:28:54 +02:00
const T *operator->() const
2018-07-14 14:24:18 +02:00
{
return &this->element_;
}
2018-07-15 20:28:54 +02:00
T *operator->()
{
return &this->element_;
}
const T &operator*() const
{
return this->element_;
}
T &operator*()
2018-07-14 14:24:18 +02:00
{
return this->element_;
}
2018-07-15 20:28:54 +02:00
T clone() const
{
return T(this->element_);
}
2018-07-14 14:24:18 +02:00
private:
T &element_;
std::mutex &mutex_;
};
template <typename T>
class UniqueAccess
{
public:
2018-07-15 20:28:54 +02:00
template <typename X = decltype(T())>
2018-07-14 14:24:18 +02:00
UniqueAccess()
: element_(T())
{
}
UniqueAccess(const T &element)
: element_(element)
{
}
UniqueAccess(T &&element)
: element_(element)
{
}
UniqueAccess<T> &operator=(const T &element)
{
this->element_ = element;
return *this;
}
UniqueAccess<T> &operator=(T &&element)
{
this->element_ = element;
return *this;
}
AccessGuard<T> access()
{
return AccessGuard<T>(this->element_, this->mutex_);
}
2018-07-15 20:28:54 +02:00
const AccessGuard<T> access() const
{
return AccessGuard<T>(this->element_, this->mutex_);
}
2018-07-14 14:24:18 +02:00
private:
2018-07-15 20:28:54 +02:00
mutable T element_;
mutable std::mutex mutex_;
2018-07-14 14:24:18 +02:00
};
} // namespace chatterino