compact_heap_ut.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include <library/cpp/yt/small_containers/compact_heap.h>
  2. #include <library/cpp/testing/gtest/gtest.h>
  3. #include <random>
  4. namespace NYT {
  5. namespace {
  6. ////////////////////////////////////////////////////////////////////////////////
  7. TEST(CompactHeapTest, Simple)
  8. {
  9. TCompactHeap<int, 2> heap;
  10. heap.push(3);
  11. heap.push(1);
  12. heap.push(2);
  13. EXPECT_EQ(3u, heap.size());
  14. EXPECT_EQ(1, heap.extract_min());
  15. EXPECT_EQ(2, heap.get_min());
  16. EXPECT_EQ(2, heap.extract_min());
  17. EXPECT_EQ(3, heap.extract_min());
  18. EXPECT_TRUE(heap.empty());
  19. }
  20. TEST(CompactHeapTest, SimpleComparator)
  21. {
  22. TCompactHeap<int, 2, std::greater<int>> heap;
  23. heap.push(3);
  24. heap.push(1);
  25. heap.push(2);
  26. EXPECT_EQ(3u, heap.size());
  27. EXPECT_EQ(3, heap.extract_min());
  28. EXPECT_EQ(2, heap.get_min());
  29. EXPECT_EQ(2, heap.extract_min());
  30. EXPECT_EQ(1, heap.extract_min());
  31. EXPECT_TRUE(heap.empty());
  32. }
  33. TEST(CompactHeapTest, Capacity)
  34. {
  35. TCompactHeap<int, 2> heap;
  36. EXPECT_EQ(2u, heap.capacity());
  37. EXPECT_EQ(0u, heap.size());
  38. for (int i = 0; i < 100; ++i) {
  39. heap.push(i);
  40. }
  41. EXPECT_LE(100u, heap.capacity());
  42. EXPECT_EQ(100u, heap.size());
  43. for (int i = 0; i < 99; ++i) {
  44. heap.pop();
  45. }
  46. EXPECT_LE(100u, heap.capacity());
  47. EXPECT_EQ(1u, heap.size());
  48. heap.shrink_to_small();
  49. EXPECT_EQ(2u, heap.capacity());
  50. EXPECT_EQ(1u, heap.size());
  51. }
  52. TEST(CompactHeapTest, Stress)
  53. {
  54. TCompactHeap<int, 3, std::greater<int>> heap;
  55. std::vector<int> values;
  56. std::mt19937 rng(42);
  57. for (int iteration = 0; iteration < 1000; ++iteration) {
  58. EXPECT_EQ(values.size(), heap.size());
  59. EXPECT_EQ(values.empty(), heap.empty());
  60. {
  61. std::vector<int> content(heap.begin(), heap.end());
  62. std::sort(content.rbegin(), content.rend());
  63. EXPECT_EQ(values, content);
  64. }
  65. if (!values.empty()) {
  66. EXPECT_EQ(values[0], heap.get_min());
  67. }
  68. if (values.empty() || rng() % 2 == 0) {
  69. int x = rng() % 100;
  70. heap.push(x);
  71. values.push_back(x);
  72. std::sort(values.rbegin(), values.rend());
  73. } else {
  74. if (rng() % 2 == 0) {
  75. EXPECT_EQ(values[0], heap.extract_min());
  76. } else {
  77. heap.pop();
  78. }
  79. values.erase(values.begin());
  80. }
  81. }
  82. }
  83. ////////////////////////////////////////////////////////////////////////////////
  84. } // namespace
  85. } // namespace NYT