/***************************************************************************
**
**  This file is part of QGpCoreTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2009-07-22
**  Copyright: 2009-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include "DynamicBuffer.h"
#include "CoreApplication.h"
#include "Global.h"
#include "Trace.h"
#include "MemoryChecker.h"

namespace QGpCoreTools {

/*!
  \class QtbDynamicBuffer QtbDynamicBuffer.h
  \brief Brief description of class still missing

  Full description of class still missing
*/

/*!
  Description of constructor still missing
*/
DynamicBuffer::DynamicBuffer()
{
  TRACE;
  _bufferCapacity=64;
  _buffer=(char *)malloc(_bufferCapacity);
  _bufferIn=0;
  _bufferOut=0;
}

/*!
  Description of destructor still missing
*/
DynamicBuffer::~DynamicBuffer()
{
  TRACE;
  free(_buffer);
}

void DynamicBuffer::clear()
{
  TRACE;
  if(_bufferCapacity>64) {
    free(_buffer);
    _bufferCapacity=64;
    _buffer=(char *)malloc(_bufferCapacity);
  }
  _bufferIn=0;
  _bufferOut=0;
}

void DynamicBuffer::add(const char * data, int byteCount)
{
  TRACE;
  //printf("before %i %i %i - add %i\n",_bufferOut, _bufferIn, _bufferCapacity, byteCount);
  int nextBufferIn=_bufferIn+byteCount;
  int neededBytes=nextBufferIn-_bufferCapacity;
  if(neededBytes>0) {
    // Shift already read bytes
    if(_bufferOut>0) {
      memmove(_buffer,_buffer+_bufferOut, _bufferIn-_bufferOut);
      _bufferIn-=_bufferOut;
      nextBufferIn-=_bufferOut;
      _bufferOut=0;
    }
    if(nextBufferIn>_bufferCapacity) {
      do {
        _bufferCapacity=_bufferCapacity << 1;
      } while(nextBufferIn>_bufferCapacity);
      _buffer=(char *)realloc(_buffer, _bufferCapacity);
    }
  }
  memcpy(_buffer+_bufferIn, data, byteCount);
  _bufferIn=nextBufferIn;
  //printf("after %i %i %i\n",_bufferOut, _bufferIn, _bufferCapacity);
  /*for(int i=0;i<32;i++) {
    printf("%02hhX ",_buffer[_bufferOut+i]);
  }
  printf("\n");*/
}

void DynamicBuffer::release(int byteCount)
{
  _bufferOut+=byteCount;
  ASSERT(_bufferOut<=_bufferIn);
}

} // namespace QGpCoreTools
