Initial Comit
This commit is contained in:
74
common/mmap.cpp
Normal file
74
common/mmap.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
#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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user