ring_buffer.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma once
  2. #include <util/generic/vector.h>
  3. #include <util/system/yassert.h>
  4. template <typename T>
  5. class TSimpleRingBuffer {
  6. public:
  7. TSimpleRingBuffer(size_t maxSize)
  8. : MaxSize(maxSize)
  9. {
  10. Items.reserve(MaxSize);
  11. }
  12. TSimpleRingBuffer(const TSimpleRingBuffer&) = default;
  13. TSimpleRingBuffer(TSimpleRingBuffer&&) = default;
  14. TSimpleRingBuffer& operator=(const TSimpleRingBuffer&) = default;
  15. TSimpleRingBuffer& operator=(TSimpleRingBuffer&&) = default;
  16. // First available item
  17. size_t FirstIndex() const {
  18. return Begin;
  19. }
  20. size_t AvailSize() const {
  21. return Items.size();
  22. }
  23. // Total number of items inserted
  24. size_t TotalSize() const {
  25. return FirstIndex() + AvailSize();
  26. }
  27. bool IsAvail(size_t index) const {
  28. return index >= FirstIndex() && index < TotalSize();
  29. }
  30. const T& operator[](size_t index) const {
  31. Y_ASSERT(IsAvail(index));
  32. return Items[RealIndex(index)];
  33. }
  34. T& operator[](size_t index) {
  35. Y_ASSERT(IsAvail(index));
  36. return Items[RealIndex(index)];
  37. }
  38. void PushBack(const T& t) {
  39. if (Items.size() < MaxSize) {
  40. Items.push_back(t);
  41. } else {
  42. Items[RealIndex(Begin)] = t;
  43. Begin += 1;
  44. }
  45. }
  46. void Clear() {
  47. Items.clear();
  48. Begin = 0;
  49. }
  50. private:
  51. size_t RealIndex(size_t index) const {
  52. return index % MaxSize;
  53. }
  54. private:
  55. size_t MaxSize;
  56. size_t Begin = 0;
  57. TVector<T> Items;
  58. };
  59. template <typename T, size_t maxSize>
  60. class TStaticRingBuffer: public TSimpleRingBuffer<T> {
  61. public:
  62. TStaticRingBuffer()
  63. : TSimpleRingBuffer<T>(maxSize)
  64. {
  65. }
  66. };