STLTempAllocator.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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/TempAllocator.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// STL allocator that wraps around TempAllocator
  8. template <typename T>
  9. class STLTempAllocator
  10. {
  11. public:
  12. using value_type = T;
  13. /// Pointer to type
  14. using pointer = T *;
  15. using const_pointer = const T *;
  16. /// Reference to type.
  17. /// Can be removed in C++20.
  18. using reference = T &;
  19. using const_reference = const T &;
  20. using size_type = size_t;
  21. using difference_type = ptrdiff_t;
  22. /// The allocator is not stateless (depends on the temp allocator)
  23. using is_always_equal = std::false_type;
  24. /// Constructor
  25. inline STLTempAllocator(TempAllocator &inAllocator) : mAllocator(inAllocator) { }
  26. /// Constructor from other allocator
  27. template <typename T2>
  28. inline explicit STLTempAllocator(const STLTempAllocator<T2> &inRHS) : mAllocator(inRHS.GetAllocator()) { }
  29. /// Allocate memory
  30. inline pointer allocate(size_type inN)
  31. {
  32. return pointer(mAllocator.Allocate(uint(inN * sizeof(value_type))));
  33. }
  34. /// Free memory
  35. inline void deallocate(pointer inPointer, size_type inN)
  36. {
  37. mAllocator.Free(inPointer, uint(inN * sizeof(value_type)));
  38. }
  39. /// Allocators are not-stateless, assume if allocator address matches that the allocators are the same
  40. inline bool operator == (const STLTempAllocator<T> &inRHS) const
  41. {
  42. return &mAllocator == &inRHS.mAllocator;
  43. }
  44. inline bool operator != (const STLTempAllocator<T> &inRHS) const
  45. {
  46. return &mAllocator != &inRHS.mAllocator;
  47. }
  48. /// Converting to allocator for other type
  49. template <typename T2>
  50. struct rebind
  51. {
  52. using other = STLTempAllocator<T2>;
  53. };
  54. /// Get our temp allocator
  55. TempAllocator & GetAllocator() const
  56. {
  57. return mAllocator;
  58. }
  59. private:
  60. TempAllocator & mAllocator;
  61. };
  62. JPH_NAMESPACE_END