#ifndef MY_OBJECTPOOL_H
#define MY_OBJECTPOOL_H

//Creates an object pool
//pool: the variable to hold the pool
//numObj: how many objects required in the pool
template <class TItem>
void CreateObjectPool(TItem *&pool, int numObj) {
	union TElement {
		TItem *next;
		TItem item;
	};
	pool = (TItem*)(new char[sizeof(TElement) * numObj + sizeof(TItem*)])
	struct TPool {
		TItem *freePtr;
		TElement items[1];
	} *data = (TPool*)pool;
	data->freePtr = &data->items[0].item;
	for (int i=0; i<numObj-1; ++i)
		data->items[i].next = &data->items[i+1].item;
	data->items[numObj-1].next = NULL;
}

//Destroy the object pool
//pool: the variable holding the pool to destroy
template <class TItem>
void DeleteObjectPool(TItem *pool) {
	delete[] ((char*)pool);
}

//This is essentially replaces your 'new' function
//pool: the pool you wish to allocate from
//returns: an object from the pool, or NULL
template <class TItem>
TItem *AllocateFromObjectPool(TItem *pool) {
	union TElement {
		TItem *next;
		TItem item;
	};
	struct TPool {
		TItem *freePtr;
		TElement items[1];
	} *data = (TPool*)pool;
	TItem *newObj = data->freePtr;
	if (newObj != NULL)
		data->freePtr = ((TElement*)newObj)->next;
	return newObj;
}

//This is essentially replaces your 'delete' function
//pool: the pool that the object came from
//oldObj: an object from the pool to return
template <class TItem>
void ReturnObjectToPool(TItem *pool, TItem *oldObj) {
	union TElement {
		TItem *next;
		TItem item;
	};
	struct TPool {
		TItem *freePtr;
		TElement items[1];
	} *data = (TPool*)pool;
	((TElement*)oldObj)->next = data->freePtr;
	data->freePtr = oldObj;
}

#endif