AuroraRuntime/Include/Aurora/Threading/Threads/TLSVariable.hpp
2021-06-27 22:25:29 +01:00

66 lines
1.6 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: TLSVariable.hpp
Date: 2021-6-11
Author: Reece
***/
#pragma once
namespace Aurora::Threading::Threads
{
template<typename T>
class TLSVariable
{
private:
int _;
public:
TLSVariable() {}
~TLSVariable()
{
GetThread()->GetTlsView()->Remove(GetHandle());
}
AuUInt64 GetHandle()
{
return (AuUInt64(reinterpret_cast<AuUInt>(&_)) & (~kTlsKeyMask)) | kTlsKeyFollowsConvention | kTlsKeyResettablePointerHandle;
}
T &Get()
{
auto view = GetThread()->GetTlsView();
auto ptr = view->GetOrSetup(GetHandle(),
[](void *buffer) -> void
{
if constexpr (std::is_class_v<T>)
{
new (buffer) T();
}
else
{
//std::memset(buffer, 0, sizeof(T));
}
},
[](void *buffer) -> void
{
if constexpr (std::is_class_v<T>)
{
reinterpret_cast<T *>(buffer)->~T();
}
});
return *reinterpret_cast<T *>(ptr);
}
T& operator ->()
{
return Get();
}
TLSVariable& operator =(const T & val)
{
Get() = val;
return *this;
}
};
}