Change std::ifStream to FileStream of using mmap.
This commit is contained in:
103
src/FileStream/FileStream.cpp
Normal file
103
src/FileStream/FileStream.cpp
Normal file
@@ -0,0 +1,103 @@
|
||||
#include "FileStream.h"
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#ifdef WIN32
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#include <sys/mman.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
const unsigned long long SKIP_UNIT_SIZE = 2147483647;//maxValue of int
|
||||
}
|
||||
|
||||
FileStream::FileStream()
|
||||
#ifdef WIN32
|
||||
: mStream()
|
||||
#else
|
||||
: mPosition(0)
|
||||
, mData(nullptr)
|
||||
, mFd()
|
||||
, mStSize()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
FileStream::~FileStream()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool FileStream::open(const std::string& aFileName)
|
||||
{
|
||||
#ifdef WIN32
|
||||
mStream.open(aFileName.c_str(), std::ios_base::binary | std::ios::in);
|
||||
return true;
|
||||
#else
|
||||
if ((mFd = ::open(aFileName.c_str(), O_RDONLY)) < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
struct stat sb;
|
||||
if (fstat(mFd, &sb) == -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
mStSize = sb.st_size;
|
||||
mData = (int16_t*)mmap(NULL, mStSize, PROT_READ, MAP_SHARED, mFd, 0);
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
void FileStream::seekg(unsigned long long aSkipSize, StreamPosition aFlag)
|
||||
{
|
||||
#ifdef WIN32
|
||||
if(aFlag == StreamPosition::cur)
|
||||
{
|
||||
unsigned long long skipData = aSkipSize % SKIP_UNIT_SIZE;
|
||||
int skipLoop = static_cast<int>((aSkipSize - skipData) / SKIP_UNIT_SIZE);
|
||||
for(int i = 0;i < skipLoop ; ++i)
|
||||
{
|
||||
mStream.seekg(SKIP_UNIT_SIZE,std::ios::cur);
|
||||
}
|
||||
mStream.seekg(static_cast<int>(skipData),std::ios::cur);
|
||||
}
|
||||
else if(aFlag == StreamPosition::begin)
|
||||
{
|
||||
mStream.seekg(static_cast<int>(aSkipSize),std::ios::beg);
|
||||
}
|
||||
#else
|
||||
if(aFlag == StreamPosition::cur)
|
||||
{
|
||||
mPosition += aSkipSize;
|
||||
}
|
||||
else if(aFlag == StreamPosition::begin)
|
||||
{
|
||||
mPosition = aSkipSize;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void FileStream::read(int16_t& aValue)
|
||||
{
|
||||
#ifdef WIN32
|
||||
mStream.read((char*)&aValue,sizeof(int16_t));
|
||||
#else
|
||||
aValue = mData[mPosition/2];
|
||||
mPosition += 2;
|
||||
#endif
|
||||
}
|
||||
|
||||
void FileStream::close()
|
||||
{
|
||||
#ifdef WIN32
|
||||
mStream.close();
|
||||
#else
|
||||
munmap(mData, mStSize);
|
||||
::close(mFd);
|
||||
#endif
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user