📄 cbuffer.cpp
字号:
/*******************************************************************
*
* DESCRIPTION:
*
* AUTHOR:
*
* HISTORY:
*
* DATE:2002-8-19
*
*******************************************************************/
#include "cBuffer.h"
#include <cstring>
#include <cstdlib>
using namespace yyc;
//*************************************************************************
//*****************************cBuffer**************************************
const int cBuffer::MAX_BUF_SIZE=DEFAULT_BUF_SIZE;
cBuffer::cBuffer()
{
m_ptr=NULL;
m_length=0;
}
cBuffer::cBuffer(int size)
{
if (size>0) {
m_length=size;
m_ptr=(char *)calloc(1,size);
}
else
m_ptr=NULL;
if (m_ptr==NULL) m_length=0;
}
cBuffer::cBuffer(const char *ptr,int size)
{
if (ptr!=NULL&&size>0) {
m_ptr=(char *)malloc(size);
m_length=size;
if(m_ptr!=NULL) memcpy(m_ptr,ptr,size);
}
else
m_ptr=NULL;
if (m_ptr==NULL) m_length=0;
}
/**
* 往buffer缓冲区中添加数据
*
* @param ptr1
* @param size
*
* @return
*/
int cBuffer::append(const char *ptr,int size)
{
if(ptr!=NULL&&size>0)
{
if(m_ptr==NULL)
{
m_ptr=(char *)malloc(size);
m_length=size;
if(m_ptr!=NULL) memcpy(m_ptr,ptr,size);
}
else
{
m_ptr=(char *)realloc(m_ptr,m_length+size);
if(m_ptr!=NULL) memcpy(m_ptr+m_length,ptr,size);
m_length+=size;
}
}
if (m_ptr==NULL) m_length=0;
return m_length;
}
/**
* 设置buffer缓冲中的数据指针和长度
* 不重新分配内存,将buferr中的数据指针指向ptr1
*
* @param ptr1
* @param size
*/
void cBuffer::set(char *ptr,int size)
{
if(m_ptr!=NULL) free(m_ptr);
m_ptr=ptr;
m_length=size;
if(m_ptr==NULL) m_length=0;
}
char& cBuffer::operator [](int pos)
{
if(m_ptr==NULL&&m_length<=pos)
{
throw;
}
return *(m_ptr+pos);
}
int cBuffer::erase(int startp,int endp)
{
if(startp<0) startp=0;
if(endp<0||endp>=m_length) endp=m_length-1;
int size=m_length-(endp-startp+1);
char *ptr1=NULL;
if(size>0)
{
ptr1=(char *)malloc(size);
if(ptr1!=NULL)
{
if(startp>0) memcpy(ptr1,m_ptr,startp);
if((m_length-endp-1)>0) memcpy(ptr1+startp,m_ptr+endp+1,m_length-endp-1);
m_length=size;
}//?if(ptr1!=NULL)
}//?if(size>0)
if(m_ptr!=NULL) free(m_ptr);
m_ptr=ptr1;
if(m_ptr==NULL) m_length=0;
return m_length;
}
cBuffer::~cBuffer()
{
if(m_ptr!=NULL)
{
free(m_ptr);
}
}
//改变缓冲区大小为指定的大小,数据内容不变
int cBuffer::reset(int size)
{
char * ptr1;
if (size>0&&m_ptr!=NULL) {
ptr1=(char *)realloc(m_ptr,size);
m_ptr=ptr1;
m_length=(m_ptr!=NULL)?size:0;
}
else
{
m_length=0;
if(m_ptr!=NULL) free(m_ptr);
m_ptr=NULL;
}
return m_length;
}
int cBuffer::reset(const char *ptr,int size)
{
if(m_ptr!=NULL) free(m_ptr);
m_ptr=NULL;
m_length=0;
if(size>0&&ptr!=NULL)
{
m_ptr=(char *)malloc(size);
m_length=size;
if(m_ptr!=NULL) memcpy(m_ptr,ptr,size);
}
if (m_ptr==NULL) m_length=0;
return m_length;
}
/**
* 得到缓冲区指针
* 同时释放buffer对象对缓冲区空间的所有权
*
* @return 返回缓冲区指针
*/
char * cBuffer::release()
{
char * ptr1;
ptr1=m_ptr;
m_ptr=NULL;
return ptr1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -