ByteBuffer.h 1.7 KB

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