////////////////////////////////////////////////////////
// filename: CVector.cpp
// author: Chafumi Touji
// version: 1.0.0
// date: 2020/03/05
////////////////////////////////////////////////////////

#include <stdio.h>
#include <string.h>
#include "CVector.h"

CVector::CVector(){

	DataSize = sizeof(int);
	ArraySize = VECTOR_BLOCK_SIZE;
	Data = new char[ArraySize * DataSize];
	PushPos = 0;
	ReturnData = new char[sizeof(int)];
}


CVector::CVector( int data_size ){

	DataSize = data_size;
	ArraySize = VECTOR_BLOCK_SIZE;
	Data = new char[ArraySize * DataSize];
	PushPos = 0;
	ReturnData = new char[data_size];
}

CVector::~CVector(){

	delete[] Data;
	Data = NULL;
	delete[] ReturnData;
}

bool CVector::Push(void *data){

	if (PushPos < ArraySize - 1){
		int pos = PushPos * DataSize;
		if ( data != NULL )
			memcpy_s( (char *) Data + pos, ArraySize * DataSize, data, DataSize);
		PushPos++;
	}
	else{
		int org_size = ArraySize;
		ArraySize += VECTOR_BLOCK_SIZE;
		char *new_data = new char[ArraySize * DataSize];
		memset(new_data, 0, ArraySize * DataSize);
		memcpy_s(new_data, ArraySize * DataSize, Data, org_size * DataSize);
		delete[] Data;
		Data = new_data;
		int pos = PushPos * DataSize;
		if ( data != NULL )
			memcpy_s((char *)Data + pos, ArraySize * DataSize, data, DataSize);
		PushPos++;
	}

	return true;
}

void *CVector::Pop(){

	if (PushPos <= 0)
		return NULL;

	memcpy_s(ReturnData, DataSize, (char *) Data + (PushPos - 1) * DataSize, DataSize);
	memset((char *)Data + (PushPos - 1) * DataSize, 0, DataSize);
	PushPos--;

	return ReturnData;
}

void *CVector::GetData( int num ){

	if (PushPos <= 0 || num > PushPos || num < 0 )
		return NULL;

	return (char *)Data + num * DataSize;
}

void CVector::Clear(){

	delete[] Data;
	Data = NULL;
	
	ArraySize = VECTOR_BLOCK_SIZE;
	Data = new char[ArraySize * DataSize];
	memset(Data, 0, ArraySize * DataSize);
	PushPos = 0;
}