Buffer.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <cstdlib>
  2. #include <cstring>
  3. #include "utils/Buffer.h"
  4. Buffer::Buffer(int initialSize)
  5. : length(0), capacity(initialSize),
  6. buffer(static_cast<char*>(malloc(initialSize))) {
  7. }
  8. Buffer::Buffer(const Buffer& other)
  9. : length(other.length), capacity(other.capacity),
  10. buffer(static_cast<char*>(malloc(capacity))) {
  11. memcpy(buffer, other.buffer, length);
  12. }
  13. Buffer::Buffer(Buffer&& other) : length(0), capacity(0), buffer(nullptr) {
  14. swap(other);
  15. }
  16. Buffer::~Buffer() {
  17. free(buffer);
  18. }
  19. Buffer& Buffer::operator=(Buffer other) {
  20. swap(other);
  21. return *this;
  22. }
  23. Buffer& Buffer::add(const void* data, int size) {
  24. while(length + size > capacity) {
  25. capacity *= 2;
  26. buffer = static_cast<char*>(realloc(buffer, capacity));
  27. }
  28. memcpy(buffer + length, data, size);
  29. length += size;
  30. return *this;
  31. }
  32. int Buffer::getLength() const {
  33. return length;
  34. }
  35. Buffer::operator const char*() const {
  36. return buffer;
  37. }
  38. void Buffer::swap(Buffer& other) {
  39. std::swap(length, other.length);
  40. std::swap(capacity, other.capacity);
  41. std::swap(buffer, other.buffer);
  42. }