stack_allocator.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "stack_allocator.h"
  6. #include "memory.h"
  7. namespace crown
  8. {
  9. StackAllocator::StackAllocator(void* start, size_t size)
  10. : _physical_start(start)
  11. , _total_size(size)
  12. , _top(start)
  13. , _allocation_count(0)
  14. {
  15. }
  16. StackAllocator::~StackAllocator()
  17. {
  18. CE_ASSERT(_allocation_count == 0 && allocated_size() == 0,
  19. "Missing %d deallocations causing a leak of %ld bytes", _allocation_count, allocated_size());
  20. }
  21. void* StackAllocator::allocate(size_t size, size_t align)
  22. {
  23. const size_t actual_size = sizeof(Header) + size + align;
  24. // Memory exhausted
  25. if ((char*) _top + actual_size > (char*) _physical_start + _total_size)
  26. {
  27. return NULL;
  28. }
  29. // The offset from TOS to the start of the buffer
  30. uint32_t offset = (char*) _top - (char*) _physical_start;
  31. // Align user data only, ignore header alignment
  32. _top = (char*) memory::align_top((char*) _top + sizeof(Header), align) - sizeof(Header);
  33. Header* header = (Header*) _top;
  34. header->offset = offset;
  35. header->alloc_id = _allocation_count;
  36. void* user_ptr = (char*) _top + sizeof(Header);
  37. _top = (char*) _top + actual_size;
  38. _allocation_count++;
  39. return user_ptr;
  40. }
  41. void StackAllocator::deallocate(void* data)
  42. {
  43. if (!data)
  44. return;
  45. Header* data_header = (Header*) ((char*)data - sizeof(Header));
  46. CE_ASSERT(data_header->alloc_id == _allocation_count - 1,
  47. "Deallocations must occur in LIFO order");
  48. _top = (char*) _physical_start + data_header->offset;
  49. _allocation_count--;
  50. }
  51. size_t StackAllocator::allocated_size()
  52. {
  53. return (char*) _top - (char*) _physical_start;
  54. }
  55. } // namespace crown