Buffer.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "utils/Buffer.hpp"
  2. #include "math/Math.hpp"
  3. #include "utils/Utility.hpp"
  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. Core::Error Core::Buffer::copyFrom(const Buffer& other) {
  18. clear();
  19. return add(other.getData(), other.length);
  20. }
  21. Core::Error 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. CORE_RETURN_ERROR(reallocate(buffer, capacity));
  27. }
  28. memoryCopy(buffer + length, data, size);
  29. length += size;
  30. return Error::NONE;
  31. }
  32. int Core::Buffer::getLength() const {
  33. return length;
  34. }
  35. Core::Buffer::operator const char*() const {
  36. return buffer;
  37. }
  38. const char* Core::Buffer::getData() const {
  39. return buffer;
  40. }
  41. void Core::Buffer::swap(Buffer& other) {
  42. Core::swap(length, other.length);
  43. Core::swap(capacity, other.capacity);
  44. Core::swap(buffer, other.buffer);
  45. }
  46. void Core::Buffer::clear() {
  47. length = 0;
  48. }