2
0

SparseArray.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright (C) 2009-2016, 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/SparseArray.h>
  7. ANKI_TEST(Util, SparseArray)
  8. {
  9. HeapAllocator<U8> alloc(allocAligned, nullptr);
  10. // Set same key
  11. {
  12. SparseArray<PtrSize> arr;
  13. arr.setAt(alloc, 1000, 123);
  14. auto it = arr.setAt(alloc, 1000, 124);
  15. ANKI_TEST_EXPECT_EQ(*arr.getAt(1000), 124);
  16. arr.erase(alloc, it);
  17. }
  18. // Check destroy
  19. {
  20. SparseArray<PtrSize> arr;
  21. arr.setAt(alloc, 10000, 123);
  22. arr.setAt(alloc, 20000, 124);
  23. arr.setAt(alloc, 30000, 125);
  24. ANKI_TEST_EXPECT_EQ(*arr.getAt(10000), 123);
  25. ANKI_TEST_EXPECT_EQ(*arr.getAt(20000), 124);
  26. ANKI_TEST_EXPECT_EQ(*arr.getAt(30000), 125);
  27. arr.destroy(alloc);
  28. }
  29. // Do complex insertions
  30. {
  31. SparseArray<PtrSize, U32, 32, 3> arr;
  32. arr.setAt(alloc, 32, 1);
  33. // Linear probing
  34. arr.setAt(alloc, 32 * 2, 2);
  35. arr.setAt(alloc, 32 * 3, 3);
  36. // Append to a tree
  37. arr.setAt(alloc, 32 * 4, 4);
  38. // Linear probing
  39. arr.setAt(alloc, 32 + 1, 5);
  40. // Evict node
  41. arr.setAt(alloc, 32 * 2 + 1, 5);
  42. ANKI_TEST_EXPECT_EQ(arr.getSize(), 6);
  43. arr.destroy(alloc);
  44. }
  45. // Fuzzy test
  46. {
  47. const U MAX = 1000;
  48. SparseArray<int, U32, 32, 3> arr;
  49. std::vector<int> numbers;
  50. srand(time(nullptr));
  51. // Insert random
  52. for(U i = 0; i < MAX; ++i)
  53. {
  54. U num;
  55. while(1)
  56. {
  57. num = rand();
  58. if(std::find(numbers.begin(), numbers.end(), int(num)) == numbers.end())
  59. {
  60. // Not found
  61. ANKI_TEST_EXPECT_EQ(arr.getAt(num), arr.getEnd());
  62. arr.setAt(alloc, num, num);
  63. numbers.push_back(num);
  64. break;
  65. }
  66. else
  67. {
  68. // Found
  69. ANKI_TEST_EXPECT_NEQ(arr.getAt(num), arr.getEnd());
  70. }
  71. }
  72. }
  73. ANKI_TEST_EXPECT_EQ(arr.getSize(), MAX);
  74. // Remove randomly
  75. U count = MAX;
  76. while(count--)
  77. {
  78. U idx = rand() % (count + 1);
  79. int num = numbers[idx];
  80. numbers.erase(numbers.begin() + idx);
  81. auto it = arr.getAt(idx);
  82. ANKI_TEST_EXPECT_NEQ(it, arr.getEnd());
  83. ANKI_TEST_EXPECT_EQ(*it, num);
  84. arr.erase(alloc, it);
  85. }
  86. }
  87. }