pool_allocator.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "pool_allocator.h"
  6. #include "assert.h"
  7. namespace crown
  8. {
  9. PoolAllocator::PoolAllocator(Allocator& backing, size_t num_blocks, size_t block_size, size_t block_align)
  10. : _backing(backing)
  11. , _start(NULL)
  12. , _freelist(NULL)
  13. , _block_size(block_size)
  14. , _block_align(block_align)
  15. , _num_allocations(0)
  16. , _allocated_size(0)
  17. {
  18. CE_ASSERT(num_blocks > 0, "Unsupported number of blocks");
  19. CE_ASSERT(block_size > 0, "Unsupported block size");
  20. CE_ASSERT(block_align > 0, "Unsupported block alignment");
  21. size_t actual_block_size = block_size + block_align;
  22. size_t pool_size = num_blocks * actual_block_size;
  23. char* mem = (char*) backing.allocate(pool_size, block_align);
  24. // Initialize intrusive freelist
  25. char* cur = mem;
  26. for (size_t bb = 0; bb < num_blocks - 1; bb++)
  27. {
  28. uintptr_t* next = (uintptr_t*) cur;
  29. *next = (uintptr_t) cur + actual_block_size;
  30. cur += actual_block_size;
  31. }
  32. uintptr_t* end = (uintptr_t*) cur;
  33. *end = (uintptr_t) NULL;
  34. _start = mem;
  35. _freelist = mem;
  36. }
  37. PoolAllocator::~PoolAllocator()
  38. {
  39. _backing.deallocate(_start);
  40. }
  41. void* PoolAllocator::allocate(size_t size, size_t align)
  42. {
  43. CE_ASSERT(size == _block_size, "Size must match block size");
  44. CE_ASSERT(align == _block_align, "Align must match block align");
  45. CE_ASSERT(_freelist != NULL, "Out of memory");
  46. uintptr_t next_free = *((uintptr_t*) _freelist);
  47. void* user_ptr = _freelist;
  48. _freelist = (void*) next_free;
  49. _num_allocations++;
  50. _allocated_size += _block_size;
  51. return user_ptr;
  52. }
  53. void PoolAllocator::deallocate(void* data)
  54. {
  55. if (!data)
  56. return;
  57. CE_ASSERT(_num_allocations > 0, "Did not allocate");
  58. uintptr_t* next = (uintptr_t*) data;
  59. *next = (uintptr_t) _freelist;
  60. _freelist = data;
  61. _num_allocations--;
  62. _allocated_size -= _block_size;
  63. }
  64. size_t PoolAllocator::allocated_size()
  65. {
  66. return _allocated_size;
  67. }
  68. } // namespace crown