Buffer.cpp 1.1 KB

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