proxy_allocator.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (c) 2012-2014 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "assert.h"
  6. #include "proxy_allocator.h"
  7. #include "string_utils.h"
  8. #include "mutex.h"
  9. namespace crown
  10. {
  11. static ProxyAllocator* g_proxy_allocators_head = NULL;
  12. static Mutex g_proxy_allocators_mutex;
  13. ProxyAllocator::ProxyAllocator(const char* name, Allocator& allocator)
  14. : _allocator(allocator)
  15. , _name(name)
  16. , _total_allocated(0)
  17. , _next(NULL)
  18. {
  19. ScopedMutex sm(g_proxy_allocators_mutex);
  20. CE_ASSERT(name != NULL, "Name must be != NULL");
  21. if(g_proxy_allocators_head != NULL)
  22. {
  23. _next = g_proxy_allocators_head;
  24. }
  25. g_proxy_allocators_head = this;
  26. }
  27. void* ProxyAllocator::allocate(size_t size, size_t align)
  28. {
  29. _total_allocated += size;
  30. return _allocator.allocate(size, align);
  31. }
  32. void ProxyAllocator::deallocate(void* data)
  33. {
  34. _allocator.deallocate(data);
  35. }
  36. size_t ProxyAllocator::allocated_size()
  37. {
  38. return _total_allocated;
  39. }
  40. const char* ProxyAllocator::name() const
  41. {
  42. return _name;
  43. }
  44. uint32_t ProxyAllocator::count()
  45. {
  46. ScopedMutex sm(g_proxy_allocators_mutex);
  47. const ProxyAllocator* head = g_proxy_allocators_head;
  48. uint32_t count = 0;
  49. while (head != NULL)
  50. {
  51. ++count;
  52. head = head->_next;
  53. }
  54. return count;
  55. }
  56. ProxyAllocator* ProxyAllocator::find(const char* name)
  57. {
  58. ScopedMutex sm(g_proxy_allocators_mutex);
  59. ProxyAllocator* head = g_proxy_allocators_head;
  60. while (head != NULL)
  61. {
  62. if (strcmp(name, head->name()) == 0)
  63. {
  64. return head;
  65. }
  66. head = head->_next;
  67. }
  68. return NULL;
  69. }
  70. ProxyAllocator* ProxyAllocator::begin()
  71. {
  72. return g_proxy_allocators_head;
  73. }
  74. ProxyAllocator* ProxyAllocator::next(ProxyAllocator* a)
  75. {
  76. if (a == NULL)
  77. {
  78. return NULL;
  79. }
  80. return a->_next;
  81. }
  82. } // namespace crown