-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.hpp
99 lines (90 loc) · 2.37 KB
/
buffer.hpp
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
95
96
97
98
99
#pragma once
#include <vector>
#include <stdexcept>
#include <cstring>
namespace Utils
{
class Buffer
{
private:
std::vector<unsigned char> buffer;
public:
// 默认构造函数和其它必要构造函数
Buffer() = default;
// 接收初始化列表的构造函数
Buffer(std::initializer_list<unsigned char> initList)
: buffer(initList)
{
}
Buffer(char *initChar, size_t len) : buffer(initChar, initChar + len)
{
}
// 接收基础类型的加法操作
template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, Buffer>::type
operator+(const T &value) const
{
Buffer result(*this); // 复制当前Buffer实例
const unsigned char *valuePtr = reinterpret_cast<const unsigned char *>(&value);
result.buffer.insert(result.buffer.end(), valuePtr, valuePtr + sizeof(T));
return result;
}
// 接收Buffer类型的加法操作
Buffer operator+(const Buffer &other) const
{
Buffer result(*this); // 复制当前Buffer实例
result.buffer.insert(result.buffer.end(), other.buffer.begin(), other.buffer.end());
return result;
}
// 允许与C字符串相加的operator+
Buffer operator+(const char *str) const
{
if (str == nullptr)
{
throw std::invalid_argument("Null pointer provided as string");
}
size_t strLength = std::strlen(str);
Buffer result = *this;
result.buffer.insert(result.buffer.end(), str, str + strLength);
return result;
}
Buffer operator+(const std::string &str) const
{
Buffer result(*this); // 复制当前Buffer实例
result.buffer.insert(result.buffer.end(), str.begin(), str.end());
return result;
}
// 元素访问操作者
unsigned char &operator[](size_t index)
{
if (index >= buffer.size())
{
throw std::out_of_range("Index out of bounds");
}
return buffer[index];
}
const unsigned char &operator[](size_t index) const
{
if (index >= buffer.size())
{
throw std::out_of_range("Index out of bounds");
}
return buffer[index];
}
// 工具函数 (列如 size, data, resize 等)
size_t size() const
{
return buffer.size();
}
const unsigned char *data() const
{
return buffer.data();
}
void resize(size_t newSize)
{
buffer.resize(newSize, 0x90);
}
// 其他必要的成员函数和操作
// ...
};
}