Buf网络缓冲区(C++)

Buf网络缓冲区

由于网络协议分包的需要,因此编写buf网络缓冲区,以便分包。

struct SBuf
{
	char* _base=nullptr;
	char* _b=nullptr;
	char* _e=nullptr;	
	size_t _size=0;

	SBuf(size_t size);
	SBuf();
	~SBuf();	
	char* data(){return _b;}
	void append(char* b, int32_t l);
	void consume(int32_t l);
	void clear(){ _b = _e = _base; }
	int32_t len(){return _e-_b;}
};

SBuf::SBuf(size_t size)
{
	_size = size;
	_b=_e=_base = new char[_size];	
	memset(_base,0,_size);
}
SBuf::SBuf()
{
	_size = getpagesize()/2;
	_b = _e = _base = new char[_size];
	memset(_base, 0, _size);
}

SBuf::~SBuf(){
	if (_base)(delete _base);
}
void SBuf::append(char* b, int32_t l)
{
	//_e后面的空间可以容纳当前追加数据
	if (_e + l < _base + _size){ 
		memcpy(_e,b,l);
		_e+=l;
	}else if(_e-_b+l<=_size){ //当前空间可以容纳追加的数据
		memcpy(_base,_b,_e-_b);
		_e = _base+len();
		_b=_base;

		memcpy(_e,b,l);
		_e+=l;
	}else{//空间不足
		char* newbuf = new char[(_size+l)*2];
		memset(newbuf,0, l * 2);
		_size = (_size + l) * 2;
		int32_t len 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值