#include "MString.h"
#include "Log.h"
#include <iostream>
#include <stdlib.h>
#include <iomanip>

namespace coreutils {

   MString::MString() {
      data = NULL;
      length = 0;
      cursor = NULL;
   }

   MString::MString(const char *data) {
      setSize(strlen(data));
      memcpy(this->data, data, length);
      cursor = this->data;
   }

   MString::MString(char *data, size_t length) {
      setSize(length);
      memcpy(this->data, data, length);
      cursor = this->data;
   }

   MString::MString(const char *data, size_t length) {
      setSize(length);      
      memcpy(this->data, data, length);
      cursor = this->data;
   }

   MString::MString(const MString &mstring) {
      setSize(mstring.length);
      memcpy(data, mstring.data, mstring.length);
      cursor = data;
//      Log(LOG_DEBUG_2) << "MString Copy Constructor: ";
   }

   MString::MString(std::string data) {
      setSize(data.length());
      memcpy(this->data, (char *)data.c_str(), data.length());
      cursor = this->data;
   }

   MString::~MString() {
      if(data)
	free(data);
   }
   
   int MString::write(char ch) {
      setSize(length + 1);
      *(data + length - 1) = ch;
      return 1;
   }
   
   int MString::write(ZString &value) {
      int len = length;
      setSize(length + value.getLength());
      memcpy(data + len, value.getData(), value.getLength());
      return value.getLength();      
   }

   void MString::setSize(int size) {
      int cursorOffset = cursor - data;
      int newBufferSize = ((size / 256) + 1) * 256;
      if(bufferSize != newBufferSize) {
	 bufferSize = newBufferSize;
	 data = (char *)realloc(data, bufferSize); 
	 cursor = data + cursorOffset;
      }
      length = size;
   }
         
}
