/** 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/memory/alloclinear.cpp

*/

#include "sgx/core/core.hpp"

CSGXMemoryAllocatorLinear::CSGXMemoryAllocatorLinear (void *ptr, const tMEM_SIZE size, const CSGXMemoryAlignment &alignment) :
	CSGXMemoryAllocator(ptr, size, alignment) {
 
	m_iCurrentIndex = 0;
	m_bLocked = FALSE; 
}
 
 
void * CSGXMemoryAllocatorLinear::alloc(const tMEM_SIZE size) {
	tMEM_SIZE offset = sgxAlign(m_iCurrentIndex, m_Alignment.m_StartAlignment);
	if (offset + size > m_iBlockSize) {
		return NULL;
	}
	void *ptr = (void *)&m_pBlock[offset];
	m_iLastAllocationIndex = m_iCurrentIndex;
	m_iCurrentIndex = offset + size;
	return ptr;
}
 
tBOOL CSGXMemoryAllocatorLinear::freePtr(void *ptr) {
	tMEM_SIZE offset = ((tBYTE *)ptr) - m_pBlock;
 
	// A special feature is that we can free the most recent block
	// and reclaim those bytes for the next alloc.
	if (m_iCurrentIndex == m_iLastAllocationIndex) {
		m_iCurrentIndex = m_iLastAllocationIndex;
	}
	return offset >= 0 && offset < m_iBlockSize ? TRUE : FALSE;
}
 
tBOOL CSGXMemoryAllocatorLinear::freeAll() {
	m_iCurrentIndex = 0;
	return TRUE;
}
 
