#include "stdafx.h"
#include "DataType.h"
CMemPool *CInterProtocl::m_pool = NULL;
CInterProtocl::CInterProtocl()
: m_nParam1(0)
, m_nParam2(0)
, m_nParam3(0)
, m_len(0)
, m_Reslut(Result_OK)
, m_dataEx(NULL)
, m_lenEx(0)
{
	memset(m_data, 0, ITP_DATA_SIZE);
}

CInterProtocl::~CInterProtocl()
{
	
}

int CInterProtocl::PushData( char *data, int len )
{
	if (len <= 0)
	{
		return 0;
	}
	if (len > ITP_DATA_SIZE)
	{
		m_dataEx = new char[len];
		memcpy(m_dataEx, data, len);
		m_lenEx = len;
	}
	else
	{
		memcpy(m_data, data, len);
		m_len = len;
	}
	
	return len;
}

void CInterProtocl::recycleITP()
{
	if (m_lenEx != 0)
	{
		delete []m_dataEx;
		m_dataEx = NULL;
		m_lenEx = 0;
	}
	m_pool->recycleITP(this);
}

CMemPool::CMemPool()
{
	for (int i=0; i<POOL_ITP_COUNT; i++)
	{
		CInterProtocl *pItp = new CInterProtocl;
		m_itpQueue.push_back(pItp);
	}
}

CMemPool::~CMemPool()
{
	std::deque<CInterProtocl *>::iterator it = m_itpQueue.begin();
	while (it != m_itpQueue.end())
	{
		CInterProtocl *pItp = *it;
		delete pItp;
		pItp = NULL;
	}
	m_itpQueue.clear();
}

CInterProtocl * CMemPool::GetIdleITP()
{
	CInterProtocl *pItp  = NULL;
	mutex.acquire();
	if (m_itpQueue.size() != 0)
	{
		pItp = m_itpQueue.front();
		m_itpQueue.pop_front();
	}
	mutex.release();
	return pItp;
}

void CMemPool::recycleITP( CInterProtocl *pItp )
{
	pItp->m_len = 0;
	mutex.acquire();
	memset(pItp, 0, sizeof(CInterProtocl));
	m_itpQueue.push_back(pItp);
	mutex.release();
}

int CMemPool::getIdleCount()
{
	mutex.acquire();
	int idleCount = m_itpQueue.size();
	mutex.release();
	return idleCount;
}