AppendBuffer.cpp 2.6 KB


#include "AppendBuffer.h"
#include "stdlib.h"
#include <string.h>
//

namespace DmapCore_30
{

AppendBuffer::AppendBuffer(void)
{
	allSize=0;
	head=0;
	now=0;	
} 

	AppendBuffer::AppendBuffer(const char *fileName)
	{
		allSize = 0;
		head = 0;
		now = 0;
		if (fileName)
		{
			f = fopen(fileName, "wb");
		}
	}

AppendBuffer::~AppendBuffer(void)
{
	Reset();
}

//分配一个新的BUFFER
AppendBuffer::Buffer *AppendBuffer::NewABuffer(void)
{
	Buffer *buf=new Buffer;
	buf->buffer=(char *)malloc(APPEND_BUFFER_SIZE);  //每个BUFFER都留这么大的空间?
	if(buf->buffer==0)
	{
		delete buf;
		return 0;
	}
	buf->next=0;
	buf->bufferNowCount=0;

	return buf;
}
char *AppendBuffer::GetString()
	{
		char *s = (char *)malloc(this->allSize + 1);
		if (s == 0)return 0;
		char *ss = s; int cc = 0;
		for (Buffer *h = head; h;)
		{
			memcpy(ss, h->buffer, h->bufferNowCount);
			ss += h->bufferNowCount;
			//	cc += h->bufferNowCount;
			h = h->next;
		}
		s[this->allSize] = 0;
		return s;
	}
void AppendBuffer::AppendString(const char * str, int len)
{	
	
	if(now==0)AddABuffer(); //当前的指针为0 

	int remain;	
	for(;;)
	{
		remain=APPEND_BUFFER_SIZE-now->bufferNowCount;
		if(remain==0)
		{
			AddABuffer();
			remain=APPEND_BUFFER_SIZE-now->bufferNowCount;
		}
		if(remain>=len)//放得下
		{
			memcpy(now->buffer+now->bufferNowCount,str,len);
			//len-=len;
			now->bufferNowCount+=len;
			this->allSize+=len;			
			break;
		}
		else  //放不下
		{
			memcpy(now->buffer+now->bufferNowCount,str,remain);
			len-=remain;
			now->bufferNowCount=APPEND_BUFFER_SIZE;
			str+=remain;
			this->allSize+=remain;			
			AddABuffer();
		}
	}	
}

//int AppendBuffer::GetSize()
//{
//	int size = 0;
//	for (AppendBuffer::Buffer *pb = this->head; pb; pb = pb->next)
//	{
//		size = size + sizeof(pb->buffer);
//	}
//	return size;
//}


void AppendBuffer::SetBuffer(AppendBuffer::Buffer *buf,const char * str, int len)
{	
	memcpy(buf->buffer,str,len);
	this->allSize+=len;
	buf->bufferNowCount=len;
}

int AppendBuffer::AppendString(const char * str)
{
	AppendString(str,(int)(strlen(str)));
	return 0;
}


int AppendBuffer::AddABuffer(void)
{		
	if(head==0)
	{
		head=NewABuffer();
		now=head;  //now是当前的指针
	}
	else
	{
		now->next=NewABuffer();
		now=now->next;
	}
	if(now==0)return 1;//stbstb
	return 0;
}

int AppendBuffer::AppendOtherOne(AppendBuffer * other)
{
	this->now->next=other->head;
	this->now=other->now;
	this->allSize+=other->allSize;
	other->head=0;
	//other->allSize=0; //stbstb
	//other->now=0;
	return 0;
}

void AppendBuffer::Reset(void)
{
	for(;head;)
	{
		now=head;
		head=now->next;
		free(now->buffer);
		delete now;				
	}	
	head=0;
	now=0;
	allSize=0;
}
	
}