compact_queue_ut.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include <library/cpp/yt/small_containers/compact_queue.h>
  2. #include <library/cpp/testing/gtest/gtest.h>
  3. #include <queue>
  4. #include <random>
  5. namespace NYT {
  6. namespace {
  7. ////////////////////////////////////////////////////////////////////////////////
  8. TEST(TCompactQueueTest, Simple)
  9. {
  10. TCompactQueue<int, 4> queue;
  11. queue.Push(1);
  12. queue.Push(2);
  13. queue.Push(3);
  14. for (int i = 1; i <= 10; i++) {
  15. EXPECT_EQ(queue.Size(), 3u);
  16. EXPECT_EQ(queue.Front(), i);
  17. EXPECT_EQ(queue.Pop(), i);
  18. queue.Push(i + 3);
  19. }
  20. for (int i = 11; i <= 13; i++) {
  21. EXPECT_EQ(queue.Front(), i);
  22. queue.Pop();
  23. }
  24. EXPECT_TRUE(queue.Empty());
  25. }
  26. TEST(TCompactQueueTest, Reallocation1)
  27. {
  28. TCompactQueue<int, 2> queue;
  29. queue.Push(1);
  30. queue.Push(2);
  31. queue.Push(3);
  32. for (int i = 1; i <= 10; i++) {
  33. EXPECT_EQ(queue.Size(), 3u);
  34. EXPECT_EQ(queue.Front(), i);
  35. EXPECT_EQ(queue.Pop(), i);
  36. queue.Push(i + 3);
  37. }
  38. for (int i = 11; i <= 13; i++) {
  39. EXPECT_EQ(queue.Front(), i);
  40. queue.Pop();
  41. }
  42. EXPECT_TRUE(queue.Empty());
  43. }
  44. TEST(TCompactQueueTest, Reallocation2)
  45. {
  46. TCompactQueue<int, 3> queue;
  47. queue.Push(1);
  48. queue.Push(2);
  49. queue.Push(3);
  50. EXPECT_EQ(queue.Pop(), 1);
  51. queue.Push(4);
  52. queue.Push(5);
  53. EXPECT_EQ(queue.Size(), 4u);
  54. for (int i = 2; i <= 10; i++) {
  55. EXPECT_EQ(queue.Size(), 4u);
  56. EXPECT_EQ(queue.Front(), i);
  57. EXPECT_EQ(queue.Pop(), i);
  58. queue.Push(i + 4);
  59. }
  60. for (int i = 11; i <= 14; i++) {
  61. EXPECT_EQ(queue.Front(), i);
  62. queue.Pop();
  63. }
  64. EXPECT_TRUE(queue.Empty());
  65. }
  66. TEST(TCompactQueueTest, Stress)
  67. {
  68. std::mt19937_64 rng(42);
  69. for (int iteration = 0; iteration < 1000; ++iteration) {
  70. TCompactQueue<int, 4> queue1;
  71. std::queue<int> queue2;
  72. for (int step = 0; step < 10'000; ++step) {
  73. EXPECT_EQ(queue1.Size(), queue2.size());
  74. EXPECT_EQ(queue1.Empty(), queue2.empty());
  75. if (!queue1.Empty()) {
  76. EXPECT_EQ(queue1.Front(), queue2.front());
  77. }
  78. if (queue2.empty() || rng() % 2 == 0) {
  79. int value = rng() % 1'000'000;
  80. queue1.Push(value);
  81. queue2.push(value);
  82. } else {
  83. queue1.Pop();
  84. queue2.pop();
  85. }
  86. }
  87. }
  88. }
  89. ////////////////////////////////////////////////////////////////////////////////
  90. } // namespace
  91. } // namespace NYT