ByteBuffer.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/STLAlignedAllocator.h>
  5. JPH_NAMESPACE_BEGIN
  6. /// Underlying data type for ByteBuffer
  7. using ByteBufferVector = std::vector<uint8, STLAlignedAllocator<uint8, JPH_CACHE_LINE_SIZE>>;
  8. /// Simple byte buffer, aligned to a cache line
  9. class ByteBuffer : public ByteBufferVector
  10. {
  11. public:
  12. /// Align the size to a multiple of inSize, returns the length after alignment
  13. size_t Align(size_t inSize)
  14. {
  15. // Assert power of 2
  16. JPH_ASSERT(IsPowerOf2(inSize));
  17. // Calculate new size and resize buffer
  18. size_t s = AlignUp(size(), inSize);
  19. resize(s);
  20. return s;
  21. }
  22. /// Allocate block of data of inSize elements and return the pointer
  23. template <class Type>
  24. Type * Allocate(size_t inSize = 1)
  25. {
  26. // Reserve space
  27. size_t s = size();
  28. resize(s + inSize * sizeof(Type));
  29. // Get data pointer
  30. Type *data = reinterpret_cast<Type *>(&at(s));
  31. // Construct elements
  32. for (Type *d = data, *d_end = data + inSize; d < d_end; ++d)
  33. ::new (d) Type;
  34. // Return pointer
  35. return data;
  36. }
  37. /// Append inData to the buffer
  38. template <class Type>
  39. void AppendVector(const Array<Type> &inData)
  40. {
  41. size_t size = inData.size() * sizeof(Type);
  42. uint8 *data = Allocate<uint8>(size);
  43. memcpy(data, &inData[0], size);
  44. }
  45. /// Get object at inPosition (an offset in bytes)
  46. template <class Type>
  47. const Type * Get(size_t inPosition) const
  48. {
  49. return reinterpret_cast<const Type *>(&at(inPosition));
  50. }
  51. /// Get object at inPosition (an offset in bytes)
  52. template <class Type>
  53. Type * Get(size_t inPosition)
  54. {
  55. return reinterpret_cast<Type *>(&at(inPosition));
  56. }
  57. };
  58. JPH_NAMESPACE_END