BuddyAllocator.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <Tests/Framework/Framework.h>
  6. #include <AnKi/Util/BuddyAllocator.h>
  7. namespace anki {
  8. ANKI_TEST(Util, BuddyAllocator)
  9. {
  10. HeapAllocator<U8> alloc(allocAligned, nullptr);
  11. // Simple
  12. {
  13. BuddyAllocator<4> buddy;
  14. Array<U32, 2> addr;
  15. Bool success = buddy.allocate(alloc, 1, addr[0]);
  16. success = buddy.allocate(alloc, 3, addr[1]);
  17. // buddy.debugPrint();
  18. buddy.free(alloc, addr[0], 1);
  19. buddy.free(alloc, addr[1], 3);
  20. // printf("\n");
  21. // buddy.debugPrint();
  22. }
  23. // Fuzzy
  24. {
  25. BuddyAllocator<32> buddy;
  26. std::vector<std::pair<U32, U32>> allocations;
  27. for(U32 it = 0; it < 1000; ++it)
  28. {
  29. if((getRandom() % 2) == 0)
  30. {
  31. // Do an allocation
  32. U32 addr;
  33. const U32 size = max<U32>(getRandom() % 512, 1);
  34. const Bool success = buddy.allocate(alloc, size, addr);
  35. if(success)
  36. {
  37. allocations.push_back({addr, size});
  38. }
  39. }
  40. else
  41. {
  42. // Do some deallocation
  43. if(allocations.size())
  44. {
  45. const PtrSize randPos = getRandom() % allocations.size();
  46. buddy.free(alloc, allocations[randPos].first, allocations[randPos].second);
  47. allocations.erase(allocations.begin() + randPos);
  48. }
  49. }
  50. }
  51. // Remove the remaining
  52. for(const auto& pair : allocations)
  53. {
  54. buddy.free(alloc, pair.first, pair.second);
  55. }
  56. }
  57. }
  58. } // end namespace anki