#pragma once
#ifndef __TlsValue_h__
#define __TlsValue_h__
#include "AutoCriticalSection.h"
template <class T>
class TlsValue
{
public:
TlsValue(void) {
}
TlsValue(const TlsValue& that) {
SetValue(that.GetValue());
}
~TlsValue()
{
TlsFree(m_dwSlot);
}
public:
T GetValue() const
{
return reinterpret_cast<T>(TlsGetValue(const_cast<TlsValue*> (this)->GetSlot()));
}
T SetValue(const T& value)
{
TlsSetValue(GetSlot(), reinterpret_cast<PVOID>(value));
return value;
}
public:
T operator!() {
return !GetValue();
}
T operator~() {
return ~GetValue();
}
T operator+() {
return +GetValue();
}
T operator++() {
SetValue(GetValue() + 1);
return *this;
}
T operator--() {
SetValue(GetValue() - 1);
return *this;
}
T operator-() {
return -GetValue();
}
T operator++(int) {
T temp(GetValue());
SetValue(temp + 1);
return temp;
}
T operator--(int) {
T temp(GetValue());
SetValue(temp - 1);
return temp;
}
T operator%=(const T& value) {
SetValue(GetValue() % value);
return *this;
}
T operator&=(const T& value) {
SetValue(GetValue() & value);
return *this;
}
T operator*=(const T& value) {
SetValue(GetValue() * value);
return *this;
}
T operator+=(const T& value) {
SetValue(GetValue() + value);
return *this;
}
T operator-=(const T& value) {
SetValue(GetValue() - value);
return *this;
}
T operator/=(const T& value) {
SetValue(GetValue() / value);
return *this;
}
T operator<<=(const T& value) {
SetValue(GetValue() << value);
return *this;
}
T operator=(const TlsValue& that) {
return SetValue(that.GetValue());
}
T operator=(const T& value) {
return SetValue(value);
}
T operator>>=(const T& value) {
SetValue(GetValue() >> value);
return *this;
}
T operator^=(const T& value) {
SetValue(GetValue() ^ value);
return *this;
}
T operator|=(const T& value) {
SetValue(GetValue() | value);
return *this;
}
operator T() const
{
return GetValue();
}
protected:
static ZAutoCriticalSection& GetSyncObject()
{
static ZAutoCriticalSection s_cs;
return s_cs;
}
DWORD GetSlot()
{
if (m_dwSlot) return m_dwSlot;
GetSyncObject().Lock(); if (!m_dwSlot) {
m_dwSlot = TlsAlloc(); if (!m_dwSlot) { m_dwSlot = TlsAlloc(); TlsFree(0); }
}
GetSyncObject().Unlock(); return m_dwSlot; }
protected:
DWORD m_dwSlot;
};
typedef TlsValue<DWORD > tlsDWORD;
typedef TlsValue<WORD > tlsWORD;
typedef TlsValue<int > tlsINT;
typedef TlsValue<UINT > tlsUINT;
typedef TlsValue<SHORT > tlsSHORT;
typedef TlsValue<USHORT> tlsUSHORT;
typedef TlsValue<LONG > tlsLONG;
typedef TlsValue<ULONG > tlsULONG;
typedef TlsValue<TCHAR > tlsTCHAR;
typedef TlsValue<WCHAR > tlsWCHAR;
typedef TlsValue<CHAR > tlsCHAR;
typedef TlsValue<BOOL > tlsBOOL;
typedef TlsValue<bool > tlsBool;
#endif