BlockArray.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (C) 2009-2023, 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 <Tests/Framework/TestFoo.h>
  7. #include <AnKi/Util/BlockArray.h>
  8. #include <vector>
  9. ANKI_TEST(Util, BlockArray)
  10. {
  11. DefaultMemoryPool::allocateSingleton(allocAligned, nullptr);
  12. // Simple
  13. TestFoo::reset();
  14. {
  15. BlockArray<TestFoo> arr;
  16. auto it = arr.emplace(123);
  17. ANKI_TEST_EXPECT_EQ(it->m_x, 123);
  18. auto it2 = arr.emplace(124);
  19. ANKI_TEST_EXPECT_EQ(it2->m_x, 124);
  20. auto it3 = arr.emplace(666);
  21. ANKI_TEST_EXPECT_EQ(it3->m_x, 666);
  22. arr.erase(arr.getBegin() + 1);
  23. ANKI_TEST_EXPECT_EQ(arr.getSize(), 2);
  24. int sum = 0;
  25. for(auto& it : arr)
  26. {
  27. sum += it.m_x;
  28. }
  29. ANKI_TEST_EXPECT_EQ(sum, 123 + 666);
  30. }
  31. ANKI_TEST_EXPECT_EQ(TestFoo::m_constructorCount, TestFoo::m_destructorCount);
  32. ANKI_TEST_EXPECT_EQ(TestFoo::m_copyCount, 0);
  33. // Fuzzy
  34. TestFoo::reset();
  35. {
  36. constexpr U32 kOperations = 1000;
  37. std::vector<std::pair<int, int>> vec;
  38. BlockArray<TestFoo> arr;
  39. for(U32 op = 0; op < kOperations; ++op)
  40. {
  41. const int opType = rand() % 2u;
  42. if(opType == 0 && vec.size())
  43. {
  44. // Remove something
  45. const int randPos = rand() % vec.size();
  46. ANKI_TEST_EXPECT_EQ(arr[vec[randPos].first].m_x, vec[randPos].second);
  47. arr.erase(arr.getBegin() + vec[randPos].first);
  48. vec.erase(vec.begin() + randPos);
  49. }
  50. else
  51. {
  52. const int randVal = rand();
  53. auto it = arr.emplace(randVal);
  54. vec.push_back({it.getArrayIndex(), randVal});
  55. }
  56. }
  57. ANKI_TEST_EXPECT_EQ(vec.size(), arr.getSize());
  58. for(auto it : vec)
  59. {
  60. ANKI_TEST_EXPECT_EQ(arr[it.first].m_x, it.second);
  61. }
  62. }
  63. DefaultMemoryPool::freeSingleton();
  64. }