#include "buffer.h"

namespace cryptrav
{

Buffer::Buffer(QFile *pFile)
{
 fileP = pFile;

 bufferP = new quint8[FILEBUFFER_SIZE];

 length = 0;
 position = 0;

}

qint32         Buffer::read(quint8* ptrData, qint32 sizeData) // relies on "sizeData < buffer-size"
{
 if ( (position + sizeData) > length )
  {
   qint32      sizeHead = length - position;
   qint32      sizeTail = sizeData - sizeHead;

   memcpy(ptrData, bufferP + position, sizeHead);


   length = fileP -> read( (char *)bufferP, FILEBUFFER_SIZE);

   if (sizeTail > length)
    sizeTail = length;


   memcpy(ptrData + sizeHead, bufferP + 0, sizeTail);

   position = sizeTail;


   return (sizeHead + sizeTail);
  }


 memcpy(ptrData, bufferP + position, sizeData);
 position += sizeData;

 return sizeData;
}


qint32         Buffer::write(quint8* ptrData, qint32 sizeData) // relies on "sizeData < buffer-size"
{
 if ( (position + sizeData) > FILEBUFFER_SIZE )
  {
   qint32      sizeHead = FILEBUFFER_SIZE - position;
   qint32      sizeTail = sizeData - sizeHead;

   memcpy(bufferP + position, ptrData, sizeHead);


   fileP -> write( (char *)bufferP, FILEBUFFER_SIZE);


   memcpy(bufferP + 0, ptrData + sizeHead, sizeTail);

   position = sizeTail;
  }
   else
  {
   memcpy(bufferP + position, ptrData, sizeData);
   position += sizeData;
  }

 return sizeData;
}


qint32         Buffer::flush(void)
{
 if (position > 0) {
   return fileP -> write( (char *)bufferP, position);
  }

 return 0;
}


Buffer::~Buffer()
{
 position = 0;
 length = 0;

 memset(bufferP, 0, FILEBUFFER_SIZE);
 delete bufferP;
 bufferP = NULL;

 fileP = NULL;

}

} // namespace "cryptrav"
