代码拉取完成,页面将自动刷新
/***
* @Description:
* @Author: LeoTao
* @Date: 2023-10-21 21:54:23
* @LastEditTime: 2023-10-25 22:54:25
*/
#pragma once
#include <vector>
#include <sys/types.h>
#include <string>
#include <algorithm>
//网络库底层的缓冲区类型定义
/// A buffer class modeled after org.jboss.netty.buffer.ChannelBuffer
///
/// +-------------------+------------------+------------------+
/// | prependable bytes | readable bytes | writable bytes |
/// | | (CONTENT) | |
/// +-------------------+------------------+------------------+
/// | | | |
/// 0 <= readerIndex <= writerIndex <= size
class Buffer
{
public:
static const size_t kCheapPrepend = 8;//限制数据包长度
static const size_t kInitialSize = 1024;//初始化缓冲区大小
explicit Buffer(size_t initialSize = kInitialSize)
: buffer_(kCheapPrepend + initialSize)
, readerIndex_(kCheapPrepend)
, writerIndex_(kCheapPrepend){}
size_t readableBytes() const {return writerIndex_- readerIndex_;}
size_t writeableBytes() const {return buffer_.size() - writerIndex_;}
size_t prependableBytes() const {return readerIndex_;}
const char* peek() {return begin() + readerIndex_;}//返回缓冲区中可读数据的起始地址
//buffer_.size() - writerIndex_ len
void ensureWriteableBytes(size_t len){
if(writeableBytes() < len){
makeSpace(len);
}
}
//把[data,data+len] 内存上的数据,添加到writerable缓冲区中
void append(const char* data, size_t len){
ensureWriteableBytes(len);
std::copy(data, data+len, beginWrite());
writerIndex_ += len;
}
//从fd中读取数据
ssize_t readFd(int fd, int* saveErrno);
char* begin(){return &*buffer_.begin();}//vector底层数组首元素的地址,也就是数组的起始地址
const char* begin() const{return &*buffer_.begin();}
char* beginWrite(){return begin() + writerIndex_;}
const char* beginWrite() const {return begin() + writerIndex_;}
void makeSpace(size_t len){
if(writeableBytes() + prependableBytes() < len + kCheapPrepend){
buffer_.resize(writerIndex_ + len);
} else {
//把前面读过的空闲缓冲区接到可写缓冲区前面
size_t readable = readableBytes();
std::copy(begin() + readerIndex_, begin() + writerIndex_, begin() + kCheapPrepend);
readerIndex_ = kCheapPrepend;
writerIndex_ = readerIndex_ + readable;
}
}
void retrieve(size_t len){
if(len < readableBytes()){
readerIndex_ += len; //应用至读取了缓冲区数据的一部分,就是len,还剩下readerIndex_ - writeIndex_个
} else {
retrieveAll();
}
}
void retrieveAll(){
readerIndex_ = writerIndex_ = kCheapPrepend;
}
//把onMessage函数上报的Buffer数据,转成string类型的数据返回
std::string retrieveAllAsString(){
return retrieveAsString(readableBytes());
}
std::string retrieveAsString(size_t len){
std::string result(peek(), len);
retrieve(len);//对缓冲区进行复位操作
return result;
}
private:
std::vector<char> buffer_;
size_t readerIndex_;
size_t writerIndex_;
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。