Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. template <class AllocationPolicy, class ThreadPolicy, class BoundsCheckingPolicy, class MemoryTrackingPolicy, class MemoryTaggingPolicy>
  2. class MemoryArena
  3. {
  4. public:
  5.     template <class AreaPolicy>
  6.     explicit MemoryArena(const AreaPolicy& area)
  7.         : m_allocator(area.GetStart(), area.GetEnd())
  8.     {
  9.     }
  10.  
  11.     void* Allocate(size_t size, size_t alignment, const SourceInfo& sourceInfo)
  12.     {
  13.         m_threadGuard.Enter();
  14.  
  15.         const size_t originalSize = size;
  16.         const size_t newSize = size + BoundsCheckingPolicy::SIZE_FRONT + BoundsCheckingPolicy::SIZE_BACK;
  17.  
  18.         char* plainMemory = static_cast<char*>(m_allocator.Allocate(newSize, alignment, BoundsCheckingPolicy::SIZE_FRONT));
  19.  
  20.         m_boundsChecker.GuardFront(plainMemory);
  21.         m_memoryTagger.TagAllocation(plainMemory + BoundsCheckingPolicy::SIZE_FRONT, originalSize);
  22.         m_boundsChecker.GuardBack(plainMemory + BoundsCheckingPolicy::SIZE_FRONT + originalSize);
  23.  
  24.         m_memoryTracker.OnAllocation(plainMemory, newSize, alignment, sourceInfo);
  25.  
  26.         m_threadGuard.Leave();
  27.  
  28.         return (plainMemory + BoundsCheckingPolicy::SIZE_FRONT);
  29.     }
  30.  
  31.     void Free(void* ptr)
  32.     {
  33.         m_threadGuard.Enter();
  34.  
  35.         char* originalMemory = static_cast<char*>(ptr) - BoundsCheckingPolicy::SIZE_FRONT;
  36.         const size_t allocationSize = m_allocator.GetAllocationSize(originalMemory);
  37.  
  38.         m_boundsChecker.CheckFront(originalMemory);
  39.         m_boundsChecker.CheckBack(originalMemory + allocationSize - BoundsCheckingPolicy::SIZE_BACK);
  40.  
  41.         m_memoryTracker.OnDeallocation(originalMemory);
  42.          
  43.         m_memoryTagger.TagDeallocation(originalMemory, allocationSize);
  44.  
  45.         m_allocator.Free(originalMemory);
  46.  
  47.         m_threadGuard.Leave();
  48.     }
  49.  
  50. private:
  51.  AllocationPolicy m_allocator;
  52.  ThreadPolicy m_threadGuard;
  53.  BoundsCheckingPolicy m_boundsChecker;
  54.  MemoryTrackingPolicy m_memoryTracker;
  55.  MemoryTaggingPolicy m_memoryTagger;
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement