Memory.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  6. #include <cstdlib>
  7. JPH_SUPPRESS_WARNINGS_STD_END
  8. #include <stdlib.h>
  9. JPH_NAMESPACE_BEGIN
  10. #ifdef JPH_DISABLE_CUSTOM_ALLOCATOR
  11. #define JPH_ALLOC_FN(x) x
  12. #define JPH_ALLOC_SCOPE
  13. #else
  14. #define JPH_ALLOC_FN(x) x##Impl
  15. #define JPH_ALLOC_SCOPE static
  16. #endif
  17. JPH_ALLOC_SCOPE void *JPH_ALLOC_FN(Allocate)(size_t inSize)
  18. {
  19. JPH_ASSERT(inSize > 0);
  20. return malloc(inSize);
  21. }
  22. JPH_ALLOC_SCOPE void *JPH_ALLOC_FN(Reallocate)(void *inBlock, [[maybe_unused]] size_t inOldSize, size_t inNewSize)
  23. {
  24. JPH_ASSERT(inNewSize > 0);
  25. return realloc(inBlock, inNewSize);
  26. }
  27. JPH_ALLOC_SCOPE void JPH_ALLOC_FN(Free)(void *inBlock)
  28. {
  29. free(inBlock);
  30. }
  31. JPH_ALLOC_SCOPE void *JPH_ALLOC_FN(AlignedAllocate)(size_t inSize, size_t inAlignment)
  32. {
  33. JPH_ASSERT(inSize > 0 && inAlignment > 0);
  34. #if defined(JPH_PLATFORM_WINDOWS)
  35. // Microsoft doesn't implement posix_memalign
  36. return _aligned_malloc(inSize, inAlignment);
  37. #else
  38. void *block = nullptr;
  39. JPH_SUPPRESS_WARNING_PUSH
  40. JPH_GCC_SUPPRESS_WARNING("-Wunused-result")
  41. JPH_CLANG_SUPPRESS_WARNING("-Wunused-result")
  42. posix_memalign(&block, inAlignment, inSize);
  43. JPH_SUPPRESS_WARNING_POP
  44. return block;
  45. #endif
  46. }
  47. JPH_ALLOC_SCOPE void JPH_ALLOC_FN(AlignedFree)(void *inBlock)
  48. {
  49. #if defined(JPH_PLATFORM_WINDOWS)
  50. _aligned_free(inBlock);
  51. #else
  52. free(inBlock);
  53. #endif
  54. }
  55. #ifndef JPH_DISABLE_CUSTOM_ALLOCATOR
  56. AllocateFunction Allocate = nullptr;
  57. ReallocateFunction Reallocate = nullptr;
  58. FreeFunction Free = nullptr;
  59. AlignedAllocateFunction AlignedAllocate = nullptr;
  60. AlignedFreeFunction AlignedFree = nullptr;
  61. void RegisterDefaultAllocator()
  62. {
  63. Allocate = AllocateImpl;
  64. Reallocate = ReallocateImpl;
  65. Free = FreeImpl;
  66. AlignedAllocate = AlignedAllocateImpl;
  67. AlignedFree = AlignedFreeImpl;
  68. }
  69. #endif // JPH_DISABLE_CUSTOM_ALLOCATOR
  70. JPH_NAMESPACE_END