CmFrameAlloc.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include "CmPrerequisitesUtil.h"
  3. namespace CamelotFramework
  4. {
  5. /**
  6. * @brief Frame allocator. Very fast allocations but can only free all of its memory at once.
  7. * Perfect for allocations that last just a single frame.
  8. *
  9. * @note Not thread safe with an exception. "alloc" and "clear" methods need to be called from the same thread.
  10. * "dealloc" is thread safe and can be called from any thread.
  11. *
  12. * Each allocation comes with a pretty hefty 4 byte memory overhead, so don't use it for small allocations.
  13. */
  14. class CM_UTILITY_EXPORT FrameAlloc
  15. {
  16. private:
  17. class MemBlock
  18. {
  19. public:
  20. MemBlock(UINT32 size);
  21. ~MemBlock();
  22. UINT8* alloc(UINT8 amount);
  23. void clear();
  24. UINT8* mData;
  25. UINT32 mFreePtr;
  26. UINT32 mSize;
  27. };
  28. public:
  29. FrameAlloc(UINT32 blockSize = 1024 * 1024);
  30. ~FrameAlloc();
  31. /**
  32. * @brief Allocates a new block of memory of the specified size.
  33. *
  34. * @param amount Amount of memory to allocate, in bytes.
  35. */
  36. UINT8* alloc(UINT32 amount);
  37. /**
  38. * @brief Deallocates a previously allocated block of memory.
  39. *
  40. * @note No deallocation is actually done here. This method is only used for debug purposes
  41. * so it is easier to track down memory leaks and corruption.
  42. *
  43. * Thread safe.
  44. */
  45. void dealloc(UINT8* data);
  46. /**
  47. * @brief Deallocates all allocated memory.
  48. */
  49. void clear();
  50. private:
  51. UINT32 mBlockSize;
  52. Vector<MemBlock*>::type mBlocks;
  53. MemBlock* mFreeBlock;
  54. std::atomic<UINT32> mTotalAllocBytes;
  55. MemBlock* allocBlock(UINT32 wantedSize);
  56. void deallocBlock(MemBlock* block);
  57. };
  58. }