#include "mmf.h"

/**
*/
CMMF::CMMF(LPCTSTR MMFName, int size, LPCTSTR mutexName) :
m_nSize(size),
m_hMutex(0)
{
	m_hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, m_nSize, MMFName);
	m_pSharedData = MapViewOfFile(m_hFileMapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);

	if(mutexName != NULL)
		m_hMutex = CreateMutex(NULL, FALSE, mutexName);
}

/**
*/
CMMF::~CMMF(void)
{
	UnmapViewOfFile(m_pSharedData);
	CloseHandle(m_hFileMapping);

	if(m_hMutex)
		CloseHandle(m_hMutex);
}

/**
* Copies the current contents of the MMF into pData (buffer must be big enough to receive m_nSize bytes).
* Waits for locked mutex to be released if mutex name was specified during construction.
*/
void CMMF::Read(void* pData, bool read /* = TRUE */)
{
	if(m_hMutex)
		WaitForSingleObject(m_hMutex, INFINITE);

	memcpy(read ? pData : m_pSharedData, read ? m_pSharedData : pData, m_nSize);

	if(m_hMutex)
		ReleaseMutex( m_hMutex );
}

/**
* Copies the contents of pData into the MMF, waiting for the MMF lock to be released if applicable.
*/
void CMMF::Write(void* pData)
{
	Read(pData, false);
}
