Buffer.cpp 1.4 KB

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