#include <cstdlib>
#include <cstring>
#include <utility>

#include "utils/Buffer.h"

Buffer::Buffer(int initialSize)
    : length(0), capacity(initialSize),
      buffer(static_cast<char*>(malloc(initialSize))) {
}

Buffer::Buffer(const Buffer& other)
    : length(other.length), capacity(other.capacity),
      buffer(static_cast<char*>(malloc(capacity))) {
    memcpy(buffer, other.buffer, 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, capacity));
    }
    memcpy(buffer + length, data, 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;
}