AlignedAllocator.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Core/Memory.h>
  5. namespace JPH {
  6. /// STL allocator that takes care that memory is aligned to N bytes
  7. template <typename T, size_t N>
  8. class AlignedAllocator
  9. {
  10. public:
  11. using value_type = T;
  12. /// Pointer to type
  13. using pointer = T *;
  14. using const_pointer = const T *;
  15. /// Reference to type.
  16. /// Can be removed in C++20.
  17. using reference = T &;
  18. using const_reference = const T &;
  19. using size_type = size_t;
  20. using difference_type = ptrdiff_t;
  21. /// Constructor
  22. inline AlignedAllocator() = default;
  23. /// Constructor from other allocator
  24. template <typename T2>
  25. inline explicit AlignedAllocator(const AlignedAllocator<T2, N> &) { }
  26. /// Allocate memory
  27. inline pointer allocate(size_type n)
  28. {
  29. return (pointer)AlignedAlloc(n * sizeof(value_type), N);
  30. }
  31. /// Free memory
  32. inline void deallocate(pointer p, size_type)
  33. {
  34. AlignedFree(p);
  35. }
  36. /// Allocators are stateless so assumed to be equal
  37. inline bool operator == (const AlignedAllocator<T, N>& other) const
  38. {
  39. return true;
  40. }
  41. inline bool operator != (const AlignedAllocator<T, N>& other) const
  42. {
  43. return false;
  44. }
  45. /// Converting to allocator for other type
  46. template <typename T2>
  47. struct rebind
  48. {
  49. using other = AlignedAllocator<T2, N>;
  50. };
  51. };
  52. } // JPH