#include "Buffer.h"

LPBUFFER CreateBuffer(ULONG cSize)
{
	LPBUFFER lpBuf = (LPBUFFER)DefAlloc(sizeof(BUFFER)+cSize);
	
	InitializeBuffer(lpBuf);

	lpBuf->cSize	= cSize;
	lpBuf->lpBuffer	= (LPVOID)((ULONG_PTR)lpBuf + sizeof(BUFFER));

	return lpBuf;
}

BOOL AllocBuffer(LPBUFFER lpBuf, ULONG cSize)
{
	lpBuf->cOffset		= 0;	
	lpBuf->cSize		= cSize;
	if(lpBuf->lpBuffer != NULL)
		DefFree(lpBuf->lpBuffer);

	lpBuf->lpBuffer		= (LPBYTE)DefAlloc(cSize);
	ZeroMemory(&lpBuf->ol, sizeof(OVERLAPPED));
	return TRUE;
}

BOOL AssignPtr(LPBUFFER lpBuf, LPBYTE lpData, ULONG cSize)
{
	lpBuf->cOffset		= 0;	
	lpBuf->cSize		= cSize;
	lpBuf->lpBuffer		= lpData;	
	ZeroMemory(&lpBuf->ol, sizeof(OVERLAPPED));
	return TRUE;
}

BOOL JobDone(LPBUFFER lpBuf, ULONG uProcessed, ULONG uMaxPacketSize)
{
	if((lpBuf->cOffset + uProcessed) == lpBuf->cSize)
	{
		lpBuf->cOffset = 0;
		return TRUE;
	}

	lpBuf->cOffset	+= uProcessed;

	lpBuf->wsa.buf	= (CHAR*)(((ULONG_PTR)lpBuf->lpBuffer)+lpBuf->cOffset);
	if(uMaxPacketSize == 0)
		lpBuf->wsa.len = (lpBuf->cSize - lpBuf->cOffset);
	else
	{
		lpBuf->wsa.len = (lpBuf->cSize - lpBuf->cOffset);
		if(lpBuf->wsa.len > uMaxPacketSize)
			lpBuf->wsa.len = uMaxPacketSize;
	}
	return FALSE;
}

VOID FreeBuffer(LPBUFFER lpBuf)
{
	if(lpBuf->lpBuffer != NULL)
		DefFree(lpBuf->lpBuffer);
	
	lpBuf->cOffset	= 0;
	lpBuf->cSize	= 0;	
}
