2
0

Memory.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #ifndef ANKI_UTIL_MEMORY_H
  2. #define ANKI_UTIL_MEMORY_H
  3. #include "anki/util/StdTypes.h"
  4. #include "anki/util/Assert.h"
  5. #include "anki/util/NonCopyable.h"
  6. #include <atomic>
  7. #include <algorithm> // For the std::move
  8. namespace anki {
  9. // Forward
  10. template<typename T>
  11. class Allocator;
  12. /// @addtogroup util
  13. /// @{
  14. /// @addtogroup memory
  15. /// @{
  16. /// Thread safe memory pool
  17. class StackMemoryPool: public NonCopyable
  18. {
  19. public:
  20. /// Default constructor
  21. StackMemoryPool(PtrSize size, U32 alignmentBytes = ANKI_SAFE_ALIGNMENT);
  22. /// Move
  23. StackMemoryPool(StackMemoryPool&& other)
  24. {
  25. *this = std::move(other);
  26. }
  27. /// Destroy
  28. ~StackMemoryPool();
  29. /// Move
  30. StackMemoryPool& operator=(StackMemoryPool&& other);
  31. /// Access the total size
  32. PtrSize getSize() const
  33. {
  34. return memsize;
  35. }
  36. /// Get the allocated size
  37. PtrSize getAllocatedSize() const;
  38. /// Allocate memory
  39. /// @return The allocated memory or nullptr on failure
  40. void* allocate(PtrSize size) throw();
  41. /// Free memory in StackMemoryPool. If the ptr is not the last allocation
  42. /// then nothing happens and the method returns false
  43. ///
  44. /// @param[in] ptr Memory block to deallocate
  45. /// @return True if the deallocation actually happened and false otherwise
  46. Bool free(void* ptr) throw();
  47. /// Reinit the pool. All existing allocated memory will be lost
  48. void reset();
  49. private:
  50. /// Alignment of allocations
  51. U32 alignmentBytes;
  52. /// Pre-allocated memory chunk
  53. U8* memory = nullptr;
  54. /// Size of the pre-allocated memory chunk
  55. PtrSize memsize = 0;
  56. /// Points to the memory and more specifically to the top of the stack
  57. std::atomic<U8*> top = {nullptr};
  58. };
  59. /// Allocate aligned memory
  60. extern void* mallocAligned(PtrSize size, PtrSize alignmentBytes);
  61. /// Free aligned memory
  62. extern void freeAligned(void* ptr);
  63. /// @}
  64. /// @}
  65. } // end namespace anki
  66. #endif