-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_buffer.h
More file actions
95 lines (92 loc) · 2.53 KB
/
Copy paththread_buffer.h
File metadata and controls
95 lines (92 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#ifndef _THREAD_BUFFER_H_
#define _THREAD_BUFFER_H_
#include <string>
#include "circular_buffer.h"
#include "realbuffer.h"
//用于线程之间通讯,像网络协议一样格式化解析
class thread_buffer
{
public:
thread_buffer(int buffer_size,int data_size):cbuffer_(buffer_size),curLenght_(data_size)
{
tempdata_ = new char[curLenght_];
}
~thread_buffer() {
delete[] tempdata_;
}
//append
bool append(int num) {
return append((char*)&num, sizeof(num));
}
bool append(__int64 num) {
return append((char*)&num, sizeof(num));
}
bool append(const char* pData) {
if (!pData) {
return false;
}
size_t len = strlen(pData);
return append(pData, len);
}
bool append(const char* pData, size_t length) {
if (!pData) {
return false;
}
if (curLenght_ < length){//如果临时buff比写入的小了,先分配好,扩充1倍,防止频繁扩容
curLenght_ *= 2;
tempdata_ = (char*)realloc(tempdata_, curLenght_);
}
return cbuffer_.write(pData, length) > 0;
}
bool append(const std::string& str) {
return append(str.c_str(), str.size());
}
bool append(buffer_base* pBuffer) {
//长度
append(pBuffer->GetLenght());
//所有数据
return append((char*)pBuffer, pBuffer->GetLenght());
}
//get
bool GetInt(int& value) {
return cbuffer_.read((char*)(&value), sizeof(int)) > 0;
}
bool GetInt64(__int64& value) {
return cbuffer_.read((char*)(&value), sizeof(__int64)) > 0;
}
bool GetData(char* data, size_t length) {
return cbuffer_.read(data, length) > 0;
}
char* GetData(size_t length) {
if (curLenght_ < length) {//如果临时buff比写入的小了
curLenght_ = length;
tempdata_ = (char*)realloc(tempdata_, curLenght_);
}
if (cbuffer_.read(tempdata_, length) > 0)
return tempdata_;
return nullptr;
}
buffer_base* GetBuffer() {
int len = 0;
if (!GetInt(len))
return nullptr;
if(GetData(len) == nullptr)
return nullptr;
return (buffer_base*)tempdata_;
}
//
size_t capacity() const {
return cbuffer_.capacity();
}
size_t size() const {
return cbuffer_.size();
}
void clear(){
memset(tempdata_,0, curLenght_);
}
private:
CircularBuffer cbuffer_;
char* tempdata_;
int curLenght_;
};
#endif // ! _THREAD_BUFFER_H_