Buffer.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "utils/Buffer.h"
  2. #include "math/Math.h"
  3. #include "utils/Utility.h"
  4. Core::Buffer::Buffer(int initialSize)
  5. : length(0), capacity(initialSize <= 0 ? 1 : initialSize), buffer(nullptr) {
  6. }
  7. Core::Buffer::Buffer(Buffer&& other) : Buffer(1) {
  8. swap(other);
  9. }
  10. Core::Buffer::~Buffer() {
  11. free(buffer);
  12. }
  13. Core::Buffer& Core::Buffer::operator=(Buffer&& other) {
  14. swap(other);
  15. return *this;
  16. }
  17. bool Core::Buffer::copyFrom(const Buffer& other) {
  18. clear();
  19. return add(other.getData(), other.length);
  20. }
  21. bool Core::Buffer::add(const void* data, int size) {
  22. if(length + size > capacity || buffer == nullptr) {
  23. while(length + size > capacity) {
  24. capacity += Math::max(4, capacity / 4);
  25. }
  26. char* newBuffer = static_cast<char*>(reallocate(buffer, capacity));
  27. if(newBuffer == nullptr) {
  28. return true;
  29. }
  30. buffer = newBuffer;
  31. }
  32. memoryCopy(buffer + length, data, size);
  33. length += size;
  34. return false;
  35. }
  36. int Core::Buffer::getLength() const {
  37. return length;
  38. }
  39. Core::Buffer::operator const char*() const {
  40. return buffer;
  41. }
  42. const char* Core::Buffer::getData() const {
  43. return buffer;
  44. }
  45. void Core::Buffer::swap(Buffer& other) {
  46. Core::swap(length, other.length);
  47. Core::swap(capacity, other.capacity);
  48. Core::swap(buffer, other.buffer);
  49. }
  50. void Core::Buffer::clear() {
  51. length = 0;
  52. }