
#include"PointerList.h"

PointerList::PointerList()
{
	size=0;
	list=0;
	InitializeCriticalSection(&criticalSection);
}

bool PointerList::AddPointer(void* pointer)
{
	EnterCriticalSection(&criticalSection); // thread safe!

	void* retVal=realloc(list,(size+1)*4); // 1 DWORD = 4 bytes!

	if(retVal)
	{
		list=retVal;
		*(int*)((int)list+(size*4))=(int)pointer; // faster than calling memcpy! (slick eh!)
		//memcpy((void*)((int)list+size),&pointer,4);
		size++;
		LeaveCriticalSection(&criticalSection);
		return true;
	}else // memory allocation failed!
	{
		LeaveCriticalSection(&criticalSection);
		return false;
	}
}

void* PointerList::GetPointer(int id)
{
	EnterCriticalSection(&criticalSection);

	if( (0<=id) & (id<size) ) // checks for valid range!
	{	
		void* val=(void*) (*(int*)((int)list+(id*4)));
		LeaveCriticalSection(&criticalSection);
		return val;
	}else // out of range!
	{
		LeaveCriticalSection(&criticalSection);
		return 0;
	}
}

bool PointerList::SetPointer(int id,void* pointer)
{
	EnterCriticalSection(&criticalSection);

	if( (0<=id) & (id<size) )
	{			
		*(int*)((int)list+(id*4))=(int)pointer;
		LeaveCriticalSection(&criticalSection);
		return true;
	}else // out of range!
	{
		LeaveCriticalSection(&criticalSection);
		return false;
	}
}

bool PointerList::RemovePointer(int id)
{
	EnterCriticalSection(&criticalSection);

	if( (0<=id) & (id<size) )
	{	
		if(size==1) // we have only one element!
		{
			free(list);
			list=0;
		}else
		{
			void* newList=malloc((size-1)*4);
			int j=0;
			for(register int i=0;i<size;i++)
			{
				if(i!=id)
				{
					*(int*)((int)newList+(j*4))=*(int*)((int)list+(i*4));
					j++;
				}	
			}
			free(list); // free old list!
			list=newList;
		}
		size--;
		LeaveCriticalSection(&criticalSection);
		return true;
	}else // out of range!
	{
		LeaveCriticalSection(&criticalSection);
		return false;
	}
}

void PointerList::RemoveAll()
{
	EnterCriticalSection(&criticalSection);
	list=0;
	size=0;
	free(list);
	LeaveCriticalSection(&criticalSection);
}

int PointerList::GetID(void* pointer)
{
	EnterCriticalSection(&criticalSection);

	for(register int i=0;i<size;i++)
	{
		if(*(int*)((int)list+(i*4))==(int)pointer)
		{
			LeaveCriticalSection(&criticalSection);
			return i;
		}
	}
	LeaveCriticalSection(&criticalSection);
	return -1;
}

int PointerList::GetSize()
{
	return size;
}

PointerList::~PointerList()
{
	free(list);
	DeleteCriticalSection(&criticalSection);
}