Buffer.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2019 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #ifndef DFPSR_BUFFER
  24. #define DFPSR_BUFFER
  25. #include <stdint.h>
  26. #include <memory>
  27. #include <functional>
  28. #include "SafePointer.h"
  29. namespace dsr {
  30. class Buffer {
  31. public:
  32. const int32_t size; // The actually used data
  33. const int32_t bufferSize; // The accessible data
  34. private:
  35. uint8_t *data;
  36. std::function<void(uint8_t *)> destructor;
  37. public:
  38. explicit Buffer(int32_t newSize);
  39. Buffer(int32_t newSize, uint8_t *newData);
  40. ~Buffer();
  41. public:
  42. void replaceDestructor(const std::function<void(uint8_t *)>& newDestructor);
  43. void set(uint8_t value);
  44. uint8_t *getUnsafeData() {
  45. return this->data;
  46. }
  47. // Get the buffer
  48. template <typename T>
  49. SafePointer<T> getSafeData(const char *name) {
  50. return SafePointer<T>(name, (T*)this->data, this->bufferSize, (T*)this->data);
  51. }
  52. // Get the buffer
  53. template <typename T>
  54. const SafePointer<T> getSafeData(const char *name) const {
  55. return SafePointer<T>(name, (T*)this->data, this->bufferSize, (T*)this->data);
  56. }
  57. // Get a part of the buffer
  58. template <typename T>
  59. SafePointer<T> getSafeSlice(const char *name, int offset, int size) {
  60. return SafePointer<T>(name, (T*)this->data, this->bufferSize, (T*)this->data).slice(name, offset, size);
  61. }
  62. std::shared_ptr<Buffer> clone() const;
  63. static std::shared_ptr<Buffer> create(int32_t newSize);
  64. static std::shared_ptr<Buffer> create(int32_t newSize, uint8_t *newData);
  65. // No implicit copies, only pass by reference or pointer
  66. Buffer(const Buffer&) = delete;
  67. Buffer& operator=(const Buffer&) = delete;
  68. };
  69. }
  70. #endif