#include "gosGml.hpp"

//===========================================================================//
// File:	 Text Draw Buffer.cpp											 //
// Project:  gosGml				                                         //
// Contents: 																 //
//---------------------------------------------------------------------------//
// Date      Who    Modification                                             //
// 4/10/00   DP     Created													 //
//---------------------------------------------------------------------------//
// Copyright (C) 2000 Microsoft Corp.						                 //
// All Rights reserved worldwide                                             //
// This unpublished sourcecode is PROPRIETARY and CONFIDENTIAL               //
//===========================================================================//


TextDrawBuffer::TextDrawBuffer(int BufferSize)
	:BufferPos(0),BufferMax(BufferSize)
{
	Buffer=new char[BufferMax];
	AppendFailFunction=0;
};

TextDrawBuffer::~TextDrawBuffer()
{
	delete[] Buffer;
};

int TextDrawBuffer::FreeSpace()
{
	return BufferMax-BufferPos;
};

void TextDrawBuffer::PreInsert(char* Text,int Len)
{
	if(Len<=(BufferMax-BufferPos))
	{
		memmove((Buffer+Len),Buffer,BufferPos);
		BufferPos+=Len;
		memcpy(Buffer,Text,Len);
	}
	else
	if(AppendFailFunction)
	{
		char* Temp=new char[Len+BufferPos+1];
		char* Temp1=Buffer;
		int TempPos=BufferPos;
		int TempClip=BufferMax-Len;
		mstrcpy(Temp,Text);
		memcpy(Temp+Len,Buffer,TempClip);
		Buffer=Temp;
		(*AppendFailFunction)(this);
		Buffer=Temp1;
		memmove(Buffer,(Buffer+TempClip),TempPos-TempClip);
		BufferPos=TempPos-TempClip;
		delete[] Temp;
	}
	else
		STOP(("TextDrawBuffer::PreInsert Overflowed."));
}

int TextDrawBuffer::UsedSpace()
{
	return BufferPos;
};

char* TextDrawBuffer::ExportBuffer()
{
	char* tempstr=new char[BufferPos+2];
	memcpy(tempstr,Buffer,BufferPos);
	tempstr[BufferPos]=(char)0;
	return tempstr;
};

void TextDrawBuffer::Append(char* text,int length)
{
	if(length>(BufferMax-BufferPos))
	{
		if(AppendFailFunction)
		{
			int FS=FreeSpace();
			memcpy((Buffer+BufferPos),text,FS);
			(*AppendFailFunction)(this);
			Append((text+FS),length-FS);
		}
		else
			STOP(("TextDrawBuffer::Append Overflowed."));
	}
	memcpy((Buffer+BufferPos),text,length);
	BufferPos+=length;
}

void TextDrawBuffer::SetAppendFailFunction(TextDrawBufferAppendFailFunction* fn_ptr)
{
	AppendFailFunction=fn_ptr;
}

void TextDrawBuffer::ClearBuffer()
{
	BufferPos=0;
}