linear_allocator.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) 2012-2014 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, size_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, size_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. {
  28. _backing->deallocate(_physical_start);
  29. }
  30. CE_ASSERT(_offset == 0, "Memory leak of %ld bytes, maybe you forgot to call clear()?", _offset);
  31. }
  32. void* LinearAllocator::allocate(size_t size, size_t align)
  33. {
  34. const size_t actual_size = size + align;
  35. // Memory exhausted
  36. if (_offset + actual_size > _total_size)
  37. {
  38. return NULL;
  39. }
  40. void* user_ptr = memory::align_top((char*) _physical_start + _offset, align);
  41. _offset += actual_size;
  42. return user_ptr;
  43. }
  44. void LinearAllocator::deallocate(void* /*data*/)
  45. {
  46. // Single deallocations not supported. Use clear().
  47. }
  48. void LinearAllocator::clear()
  49. {
  50. _offset = 0;
  51. }
  52. size_t LinearAllocator::allocated_size()
  53. {
  54. return _offset;
  55. }
  56. } // namespace crown