memory.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #pragma once
  6. #include <new>
  7. #include "types.h"
  8. #include "assert.h"
  9. #include "allocator.h"
  10. #include "macros.h"
  11. namespace crown
  12. {
  13. Allocator& default_allocator();
  14. /// @defgroup Memory Memory
  15. namespace memory
  16. {
  17. /// Value used to fill unused memory
  18. const uint32_t PADDING_VALUE = 0xFFFFFFFFu;
  19. /// Returns the pointer @a p aligned to the desired @a align byte
  20. inline void* align_top(void* p, size_t align)
  21. {
  22. CE_ASSERT(align >= 1, "Alignment must be > 1");
  23. CE_ASSERT(align % 2 == 0 || align == 1, "Alignment must be a power of two");
  24. uintptr_t ptr = (uintptr_t)p;
  25. const size_t mod = ptr % align;
  26. if (mod)
  27. {
  28. ptr += align - mod;
  29. }
  30. return (void*) ptr;
  31. }
  32. /// Respects standard behaviour when calling on NULL @a ptr
  33. template <typename T>
  34. inline void call_destructor_and_deallocate(Allocator& a, T* ptr)
  35. {
  36. if (!ptr)
  37. return;
  38. ptr->~T();
  39. a.deallocate(ptr);
  40. }
  41. } // namespace memory
  42. namespace memory_globals
  43. {
  44. /// Constructs the initial default allocators.
  45. /// @note
  46. /// Has to be called before anything else during the engine startup.
  47. void init();
  48. /// Destroys the allocators created with memory_globals::init().
  49. /// @note
  50. /// Should be the last call of the program.
  51. void shutdown();
  52. } // namespace memory_globals
  53. } // namespace crown
  54. /// Allocates memory with @a allocator for the given @a T type
  55. /// and calls constructor on it.
  56. /// @note
  57. /// @a allocator must be a reference to an existing allocator.
  58. #define CE_NEW(allocator, T) new ((allocator).allocate(sizeof(T), CE_ALIGNOF(T))) T
  59. /// Calls destructor on @a ptr and deallocates memory using the
  60. /// given @a allocator.
  61. /// @note
  62. /// @a allocator must be a reference to an existing allocator.
  63. #define CE_DELETE(allocator, ptr) crown::memory::call_destructor_and_deallocate(allocator, ptr)