Buffer.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. }
  44. void Buffer::clear() {
  45. length = 0;
  46. }