加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Buffer.h 3.38 KB
一键复制 编辑 原始数据 按行查看 历史
leo_1 提交于 2023-10-25 23:14 . buffer函数实现完成
/***
* @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_;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化