/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/sgx/core/threading/castypes.cpp

*/

#include "sgx/core/core.hpp"

/**
This is the NULL driver version.

Platform drivers should use atomic code because NONE of these implementations
are safe; they assume it works.

The CAS (compare and swap) method only writes the newValue into the
variable given if the value has changed.

SGX Core returns a boolean to indicate success to be consistent with
all methods.

See http://en.wikipedia.org/wiki/lock-free_and_wait-free_algorithms
for good algorithmic links.

*/

tBOOL cas(tCHAR8 &refValue, tCHAR8 oldValue, tCHAR8 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tUCHAR8 &refValue, tUCHAR8 oldValue, tUCHAR8 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tINT16 &refValue, tINT16 oldValue, tINT16 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tUINT16 &refValue, tUINT16 oldValue, tUINT16 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tINT32 &refValue, tINT32 oldValue, tINT32 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tUINT32 &refValue, tUINT32 oldValue, tUINT32 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tINT64 &refValue, tINT64 oldValue, tINT64 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tUINT64 &refValue, tUINT64 oldValue, tUINT64 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tREAL32 &refValue, tREAL32 oldValue, tREAL32 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(tREAL64 &refValue, tREAL64 oldValue, tREAL64 newValue) {
	if (refValue == oldValue) {
		refValue = newValue;
		return TRUE;
	}
	return FALSE;
}

tBOOL cas(void *refPtr, int size, void *oldPtr, void *newPtr) {
	sgxAssert(refPtr != oldPtr);
	sgxAssert(refPtr != newPtr);

	tUINT32 crcOld = sgxGetCRC32(oldPtr, size);
	tUINT32 crcRef = sgxGetCRC32(refPtr, size);

	if (crcRef == crcOld) {
		sgxMemmove(refPtr, newPtr, size);
		return TRUE;
	}
	return FALSE;
}

