12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- #include "utils/Buffer.h"
- #include <cstdlib>
- #include <cstring>
- #include <utility>
- Buffer::Buffer(int initialSize)
- : length(0), capacity(initialSize <= 0 ? 1 : initialSize),
- buffer(static_cast<char*>(malloc(static_cast<unsigned int>(capacity)))) {
- }
- Buffer::Buffer(const Buffer& other)
- : length(other.length), capacity(other.capacity),
- buffer(static_cast<char*>(malloc(static_cast<unsigned int>(capacity)))) {
- memcpy(buffer, other.buffer, static_cast<unsigned int>(length));
- }
- Buffer::Buffer(Buffer&& other) : length(0), capacity(0), buffer(nullptr) {
- swap(other);
- }
- Buffer::~Buffer() {
- free(buffer);
- }
- Buffer& Buffer::operator=(Buffer other) {
- swap(other);
- return *this;
- }
- Buffer& Buffer::add(const void* data, int size) {
- while(length + size > capacity) {
- capacity *= 2;
- buffer = static_cast<char*>(
- realloc(buffer, static_cast<unsigned int>(capacity)));
- }
- memcpy(buffer + length, data, static_cast<unsigned int>(size));
- length += size;
- return *this;
- }
- int Buffer::getLength() const {
- return length;
- }
- Buffer::operator const char*() const {
- return buffer;
- }
- void Buffer::swap(Buffer& other) {
- std::swap(length, other.length);
- std::swap(capacity, other.capacity);
- std::swap(buffer, other.buffer);
- }
- void Buffer::clear() {
- length = 0;
- }
|