mkql_safe_circular_buffer.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #pragma once
  2. #include <yql/essentials/utils/yql_panic.h>
  3. #include <util/system/yassert.h>
  4. #include <util/generic/maybe.h>
  5. #include <vector>
  6. namespace NKikimr {
  7. namespace NMiniKQL {
  8. template<class T>
  9. class TSafeCircularBuffer {
  10. public:
  11. TSafeCircularBuffer(TMaybe<size_t> size, T emptyValue, size_t initSize = 0)
  12. : Buffer(size ? *size : initSize, emptyValue)
  13. , EmptyValue(emptyValue)
  14. , Unbounded(!size.Defined())
  15. , Count(initSize)
  16. {
  17. if (!Unbounded) {
  18. Y_ABORT_UNLESS(initSize <= *size);
  19. }
  20. }
  21. bool IsUnbounded() const {
  22. return Unbounded;
  23. }
  24. void PushBack(T&& data) {
  25. if (Unbounded) {
  26. Y_ABORT_UNLESS(Head + Count == Size());
  27. Buffer.emplace_back(std::move(data));
  28. } else {
  29. YQL_ENSURE(!IsFull());
  30. Buffer[RealIndex(Head + Count)] = std::move(data);
  31. }
  32. Count++;
  33. MutationCount++;
  34. }
  35. const T& Get(size_t index) const {
  36. if (index < Count) {
  37. return Buffer[RealIndex(Head + index)];
  38. } else {
  39. // Circular buffer out of bounds
  40. return EmptyValue;
  41. }
  42. }
  43. void PopFront() {
  44. if (!Count) {
  45. // Circular buffer not have elements for pop, no elements, no problem
  46. } else {
  47. Buffer[Head] = EmptyValue;
  48. Head = RealIndex(Head+1);
  49. Count--;
  50. }
  51. MutationCount++;
  52. }
  53. size_t Size() const {
  54. return Buffer.size();
  55. }
  56. size_t UsedSize() const {
  57. return Count;
  58. }
  59. ui64 Generation() const {
  60. return MutationCount;
  61. }
  62. void Clean() {
  63. const auto usedSize = UsedSize();
  64. for (size_t index = 0; index < usedSize; ++index) {
  65. Buffer[RealIndex(Head + index)] = EmptyValue;
  66. }
  67. }
  68. void Clear() {
  69. Head = Count = 0;
  70. Buffer.clear();
  71. Buffer.shrink_to_fit();
  72. }
  73. private:
  74. bool IsFull() const {
  75. if (Unbounded) {
  76. return false;
  77. }
  78. return UsedSize() == Size();
  79. }
  80. size_t RealIndex(size_t index) const {
  81. auto size = Size();
  82. Y_ABORT_UNLESS(size);
  83. return index % size;
  84. }
  85. std::vector<T> Buffer;
  86. const T EmptyValue;
  87. const bool Unbounded;
  88. size_t Head = 0;
  89. size_t Count;
  90. ui64 MutationCount = 0;
  91. };
  92. }
  93. }