Buffer.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "utils/Buffer.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "utils/Utility.h"
  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. Core::swap(length, other.length);
  42. Core::swap(capacity, other.capacity);
  43. Core::swap(buffer, other.buffer);
  44. }
  45. void Buffer::clear() {
  46. length = 0;
  47. }