#include "AliHLTMemoryFile.h"
#include <cerrno>
ClassImp(AliHLTMemoryFile);
AliHLTMemoryFile::AliHLTMemoryFile()
:
fpBuffer(NULL),
fBufferSize(0),
fPosition(0),
fSize(0),
fErrno(0),
fbClosed(0),
fHeaderSize(0),
fTrailerSize(0)
{
}
AliHLTMemoryFile::AliHLTMemoryFile(void* pBuffer, int iSize)
:
TFile("/dev/null", "CREATE"),
AliHLTLogging(),
fpBuffer((char*)pBuffer),
fBufferSize(iSize),
fPosition(0),
fSize(0),
fErrno(0),
fbClosed(0),
fHeaderSize(0),
fTrailerSize(0)
{
}
AliHLTMemoryFile::~AliHLTMemoryFile()
{
if (!fbClosed) {
HLTWarning("memory file not closed, possible data loss");
}
}
void AliHLTMemoryFile::Close(const Option_t*)
{
CloseMemoryFile();
}
int AliHLTMemoryFile::CloseMemoryFile(int bFlush)
{
fErrno=0;
if (fbClosed) return 0;
if (bFlush) {
TFile::Close();
}
fpBuffer=NULL;
fBufferSize=fPosition=0;
fbClosed=1;
if (fErrno==ENOSPC) {
HLTError("error flushing memory file, buffer too small");
} else if (fErrno>0) {
HLTError("error flushing memory file");
}
return -fErrno;
}
Int_t AliHLTMemoryFile::SysOpen(const char* , Int_t , UInt_t )
{
if (fpBuffer==NULL || fSize==0) return 1;
fErrno=0;
errno=fErrno=ENOSPC;
return -1;
}
Int_t AliHLTMemoryFile::SysClose(Int_t )
{
return 0;
}
Int_t AliHLTMemoryFile::SysRead(Int_t , void *buf, Int_t len)
{
if (buf==NULL) return 0;
fErrno=0;
if (fpBuffer==NULL || fBufferSize==0) return 0;
int read=len<fSize-fPosition?len:fSize-fPosition;
memcpy(buf, fpBuffer+fPosition, read);
fPosition+=read;
if (fPosition>=fSize) fSize=fPosition+1;
return read;
}
Int_t AliHLTMemoryFile::SysWrite(Int_t , const void *buf, Int_t len)
{
if (buf==NULL) return 0;
fErrno=0;
if (len<fBufferSize-fPosition) {
memcpy(fpBuffer+fPosition, buf, len);
fPosition+=len;
if (fPosition>=fSize) fSize=fPosition+1;
return len;
}
errno=fErrno=ENOSPC;
return -1;
}
Long64_t AliHLTMemoryFile::SysSeek(Int_t , Long64_t offset, Int_t whence)
{
fErrno=0;
int position=(int)offset;
switch (whence) {
case SEEK_SET:
break;
case SEEK_CUR:
position+=fPosition;
break;
case SEEK_END:
position+=fSize;
break;
default:
position=-1;
errno=EINVAL;
}
if (position>=0) {
if (position<fBufferSize) {
fPosition=position;
} else {
position=-1;
errno=fErrno=ENOSPC;
}
}
return position;
}
Int_t AliHLTMemoryFile::SysStat(Int_t , Long_t *, Long64_t *size, Long_t *, Long_t *)
{
if (size) *size=fSize;
return 0;
}
Int_t AliHLTMemoryFile::SysSync(Int_t )
{
return 0;
}
int AliHLTMemoryFile::WriteHeaderBuffer(const char* pHeader, int size)
{
fErrno=0;
if (fHeaderSize==0) {
if (fSize+size<fBufferSize) {
if (fSize>0) {
memcpy(fpBuffer+size, fpBuffer, fSize);
}
memcpy(fpBuffer, pHeader, size);
fpBuffer+=size;
fPosition+=size;
fBufferSize-=size;
fHeaderSize=size;
} else {
HLTError("no space left in memory file");
fErrno=ENOSPC;
}
} else {
HLTError("header exists");
fErrno=EEXIST;
}
return -fErrno;
}