Files
CPP/common/mmap.cpp
2025-08-10 11:35:20 -04:00

75 lines
1.6 KiB
C++

#include <common/mmap.hpp>
#include <common/except.hpp>
bool MemoryMappedFile::open(const String& pathFileName,CreationFlags creationFlags)
{
if(isOkay())
{
close();
}
mFD=::open(pathFileName,getFileAccessFromFlags(creationFlags));
mCreationFlags= creationFlags;
if(!isOkay())return false;
struct stat sb;
if(-1==::fstat(mFD,&sb))
{
close();
return false;
}
mFileLength = sb.st_size;
if(!createMemoryMap())
{
close();
return false;
}
return true;
}
bool MemoryMappedFile::createMemoryMap(void)
{
void *pAddress = ::mmap(NULL,mFileLength,getMemoryMapAccessFromFlags(mCreationFlags),mCreationFlags == CreationFlags::ReadOnly?MAP_PRIVATE:MAP_SHARED,mFD,0);
if(MAP_FAILED == pAddress)
{
return false;
}
mlpMappedDataBase = (char *)pAddress;
mIndex=0;
return true;
}
void MemoryMappedFile::close()
{
if(!isOkay())return;
::munmap((void*)mlpMappedDataBase, mFileLength);
::close(mFD);
mFD=-1;
mFileLength=-1;
}
int MemoryMappedFile::getFileAccessFromFlags(CreationFlags creationFlags)const
{
switch(creationFlags)
{
case ReadOnly :
return O_RDONLY | S_IRUSR ;
case ReadWrite :
return O_RDWR | O_CREAT, S_IRUSR | S_IWUSR;
default :
throw new Exception("Undefined creation flag");
}
}
int MemoryMappedFile::getMemoryMapAccessFromFlags(CreationFlags creationFlags)const
{
switch(creationFlags)
{
case ReadOnly :
return PROT_READ;
case ReadWrite :
return PROT_READ | PROT_WRITE;
default :
throw new Exception("Undefined creation flag");
}
}