linear_allocator.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "linear_allocator.h"
  6. #include "memory.h"
  7. namespace crown
  8. {
  9. LinearAllocator::LinearAllocator(Allocator& backing, uint32_t size)
  10. : _backing(&backing)
  11. , _physical_start(NULL)
  12. , _total_size(size)
  13. , _offset(0)
  14. {
  15. _physical_start = backing.allocate(size);
  16. }
  17. LinearAllocator::LinearAllocator(void* start, uint32_t size)
  18. : _backing(NULL)
  19. , _physical_start(start)
  20. , _total_size(size)
  21. , _offset(0)
  22. {
  23. }
  24. LinearAllocator::~LinearAllocator()
  25. {
  26. if (_backing)
  27. _backing->deallocate(_physical_start);
  28. CE_ASSERT(_offset == 0, "Memory leak of %ld bytes, maybe you forgot to call clear()?", _offset);
  29. }
  30. void* LinearAllocator::allocate(uint32_t size, uint32_t align)
  31. {
  32. const uint32_t actual_size = size + align;
  33. // Memory exhausted
  34. if (_offset + actual_size > _total_size)
  35. return NULL;
  36. void* user_ptr = memory::align_top((char*) _physical_start + _offset, align);
  37. _offset += actual_size;
  38. return user_ptr;
  39. }
  40. void LinearAllocator::deallocate(void* /*data*/)
  41. {
  42. // Single deallocations not supported. Use clear().
  43. }
  44. void LinearAllocator::clear()
  45. {
  46. _offset = 0;
  47. }
  48. } // namespace crown