Buffer.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "utils/Buffer.h"
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <utility>
  5. Buffer::Buffer(int initialSize)
  6. : length(0), capacity(initialSize <= 0 ? 1 : initialSize),
  7. buffer(static_cast<char*>(malloc(static_cast<unsigned int>(capacity)))) {
  8. }
  9. Buffer::Buffer(const Buffer& other)
  10. : length(other.length), capacity(other.capacity),
  11. buffer(static_cast<char*>(malloc(static_cast<unsigned int>(capacity)))) {
  12. memcpy(buffer, other.buffer, static_cast<unsigned int>(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*>(
  28. realloc(buffer, static_cast<unsigned int>(capacity)));
  29. }
  30. memcpy(buffer + length, data, static_cast<unsigned int>(size));
  31. length += size;
  32. return *this;
  33. }
  34. int Buffer::getLength() const {
  35. return length;
  36. }
  37. Buffer::operator const char*() const {
  38. return buffer;
  39. }
  40. void Buffer::swap(Buffer& other) {
  41. std::swap(length, other.length);
  42. std::swap(capacity, other.capacity);
  43. std::swap(buffer, other.buffer);
  44. }
  45. void Buffer::clear() {
  46. length = 0;
  47. }