96 lines
2.1 KiB
C++
96 lines
2.1 KiB
C++
#ifndef _COMMON_MMAP_HPP_
|
|
#define _COMMON_MMAP_HPP_
|
|
#include <fcntl.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
#include <cstring>
|
|
#include <sys/mman.h>
|
|
#include <common/string.hpp>
|
|
|
|
class MemoryMappedFile
|
|
{
|
|
public:
|
|
enum CreationFlags{ReadOnly,ReadWrite};
|
|
MemoryMappedFile(const String& pathFileName,CreationFlags creationFlags);
|
|
virtual ~MemoryMappedFile();
|
|
bool open(const String& pathFileName,CreationFlags creationFlags);
|
|
bool readLine(String &strLine);
|
|
char readChar(void);
|
|
bool eof(void);
|
|
char peekChar(void);
|
|
void close(void);
|
|
bool isOkay(void);
|
|
off_t tell(void);
|
|
private:
|
|
enum {CarriageReturn=0x0D,LineFeed=0x0A,NullChar=0x00};
|
|
enum {BlockSize=65536};
|
|
bool createMemoryMap(void);
|
|
int getFileAccessFromFlags(CreationFlags creationFlags)const;
|
|
int getMemoryMapAccessFromFlags(CreationFlags creationFlags)const;
|
|
|
|
int mFD = -1;
|
|
unsigned long mIndex;
|
|
off_t mFileLength = -1;
|
|
char *mlpMappedDataBase = 0;
|
|
CreationFlags mCreationFlags;
|
|
};
|
|
|
|
/// @brief
|
|
/// @param pathFileName
|
|
/// @param access
|
|
inline
|
|
MemoryMappedFile::MemoryMappedFile(const String& pathFileName,CreationFlags creationFlags)
|
|
{
|
|
open(pathFileName, creationFlags);
|
|
}
|
|
|
|
inline
|
|
MemoryMappedFile::~MemoryMappedFile()
|
|
{
|
|
}
|
|
|
|
inline
|
|
char MemoryMappedFile::readChar()
|
|
{
|
|
return mlpMappedDataBase[mIndex++];
|
|
}
|
|
|
|
inline
|
|
bool MemoryMappedFile::eof()
|
|
{
|
|
return mIndex<mFileLength?false:true;
|
|
}
|
|
|
|
inline
|
|
char MemoryMappedFile::peekChar()
|
|
{
|
|
return mlpMappedDataBase[mIndex];
|
|
}
|
|
|
|
inline
|
|
off_t MemoryMappedFile::tell(void)
|
|
{
|
|
return mIndex;
|
|
}
|
|
|
|
inline
|
|
bool MemoryMappedFile::readLine(String &strLine)
|
|
{
|
|
off_t beginPosition = mIndex;
|
|
while(mIndex<mFileLength && !(LineFeed==mlpMappedDataBase[mIndex++]));
|
|
off_t currentPosition = mIndex;
|
|
if(beginPosition==currentPosition)return false;
|
|
off_t length = (currentPosition - beginPosition) -1;
|
|
strLine.reserve(length<<1,0);
|
|
::memcpy((char*)strLine,mlpMappedDataBase+beginPosition,length);
|
|
*((char*)strLine+length)=0;
|
|
return true;
|
|
}
|
|
|
|
inline
|
|
bool MemoryMappedFile::isOkay(void)
|
|
{
|
|
return -1==mFD?false:true;
|
|
}
|
|
|
|
#endif |