/*
* @brief Safely Buffer
*/
class Buffer {
public:
Buffer()
: _data(nullptr),
_size(0) {
}
Buffer(const byte* data, size_t size) : _data(nullptr), _size(0) {
if (!data || !size) {
return;
}
allocBuffer(size);
memcpy(_data, data, size);
}
Buffer(size_t size) : _data(nullptr), _size(0) {
allocBuffer(size);
}
Buffer(const Buffer& buffer) : _data(nullptr), _size(0) {
*this = buffer;
}
Buffer(const Buffer* pbuffer) : _data(nullptr), _size(0) {
if (!pbuffer) {
return;
}
*this = *pbuffer;
}
~Buffer() {
releaseBuffer();
}
Buffer& assign(const byte* data, size_t size) {
allocBuffer(size);
if (data && size > 0) {
memcpy(_data, data, size);
}
return *this;
}
byte* data() const {
return _data;
}
size_t size() const {
return _size;
}
size_t length() const {
return size();
}
void resize(size_t size) {
allocBuffer(size);
}
byte& operator[](size_t pos) const {
assert(pos < _size);
return _data[pos];
}
Buffer& operator=(const Buffer& right) {
allocBuffer(right.size());
if (!right.empty()) {
memcpy(_data, right.data(), _size);
}
return *this;
}
bool empty() const {
return (!_data && _size == 0);
}
void clear(){
if(!_data || 0 == _size){
return;
}
memset(_data, 0, _size);
}
void release() {
releaseBuffer();
}
bool operator==(const Buffer& right) const {
if (_size == right.size()) {
for (size_t i = 0; i < _size; i++) {
if ((*this)[i] != right[i]) {
return false;
}
}
return true;
}
return false;
}
private:
void allocBuffer(size_t size) {
releaseBuffer();
_size = size;
if (size) {
_data = new byte[_size];
if (!_data) {
throw std::bad_alloc();
}
memset(_data, 0, _size);
}
}
void releaseBuffer() {
SAFE_DELETE_ARRAY(_data);
_size = 0;
}
private:
byte* _data;
size_t _size;
};
用来替代char*,方便且安全