memory.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #pragma once
  6. #include "types.h"
  7. #include "error.h"
  8. #include "allocator.h"
  9. #include "macros.h"
  10. #include <new>
  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, uint32_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 uint32_t mod = ptr % align;
  26. if (mod)
  27. ptr += align - mod;
  28. return (void*) ptr;
  29. }
  30. /// Respects standard behaviour when calling on NULL @a ptr
  31. template <typename T>
  32. inline void call_destructor_and_deallocate(Allocator& a, T* ptr)
  33. {
  34. if (!ptr)
  35. return;
  36. ptr->~T();
  37. a.deallocate(ptr);
  38. }
  39. } // namespace memory
  40. namespace memory_globals
  41. {
  42. /// Constructs the initial default allocators.
  43. /// @note
  44. /// Has to be called before anything else during the engine startup.
  45. void init();
  46. /// Destroys the allocators created with memory_globals::init().
  47. /// @note
  48. /// Should be the last call of the program.
  49. void shutdown();
  50. } // namespace memory_globals
  51. } // namespace crown
  52. /// Allocates memory with @a allocator for the given @a T type
  53. /// and calls constructor on it.
  54. /// @note
  55. /// @a allocator must be a reference to an existing allocator.
  56. #define CE_NEW(allocator, T) new ((allocator).allocate(sizeof(T), CE_ALIGNOF(T))) T
  57. /// Calls destructor on @a ptr and deallocates memory using the
  58. /// given @a allocator.
  59. /// @note
  60. /// @a allocator must be a reference to an existing allocator.
  61. #define CE_DELETE(allocator, ptr) crown::memory::call_destructor_and_deallocate(allocator, ptr)