diff --git a/src/jc/cpp/ringbuffer.h b/src/jc/cpp/ringbuffer.h index fd6e287..2055a38 100644 --- a/src/jc/cpp/ringbuffer.h +++ b/src/jc/cpp/ringbuffer.h @@ -77,8 +77,8 @@ class RingBuffer void PushUnchecked(const T& item); /// Removes (and returns) the first inserted item from the ring buffer. Asserts if the buffer is empty T Pop(); - /// Removes the element at logical index (0-based) and keeps order - void Erase(uint32_t index); + /// Removes the element at logical index (0-based), keeps order, returns old value + T Erase(uint32_t index); T& operator[] (size_t i) { assert(i < Size()); return m_Buffer[(m_Tail + i) % m_Max]; } const T& operator[] (size_t i) const { assert(i < Size()); return m_Buffer[(m_Tail + i) % m_Max]; } @@ -195,7 +195,7 @@ T RingBuffer::Pop() } template -void RingBuffer::Erase(uint32_t index) +T RingBuffer::Erase(uint32_t index) { uint32_t size = Size(); assert(index < size); @@ -203,6 +203,9 @@ void RingBuffer::Erase(uint32_t index) // Compute physical index of the element to erase uint32_t pos = (m_Tail + index) % m_Max; + // Store old value to return + T old_value = m_Buffer[pos]; + // Shift elements left from pos towards head to preserve order // Stop when the next index equals m_Head (the logical end) while (true) @@ -225,6 +228,8 @@ void RingBuffer::Erase(uint32_t index) --m_Head; } m_Full = 0; + + return old_value; } diff --git a/test/ringbuffer.cpp b/test/ringbuffer.cpp index 8f57682..8e1117b 100644 --- a/test/ringbuffer.cpp +++ b/test/ringbuffer.cpp @@ -411,7 +411,8 @@ TEST(RingBufferTest, Erase_Contiguous_Middle) jc::RingBuffer rb(8); for (int i = 0; i < 6; ++i) rb.Push(i); // 0..5 - rb.Erase(2); // remove '2' + int removed = rb.Erase(2); // remove '2' + ASSERT_EQ(2, removed); ASSERT_EQ(5u, rb.Size()); const int expected1[5] = {0,1,3,4,5}; for (uint32_t i = 0; i < 5; ++i) @@ -427,7 +428,8 @@ TEST(RingBufferTest, Erase_Wrapped_Middle) for (int i = 0; i < 5; ++i) rb.Pop(); // -> [5,6,7] for (int i = 8; i < 12; ++i) rb.Push(i); // wrap -> [5,6,7,8,9,10,11] - rb.Erase(3); // remove '8' + int removed2 = rb.Erase(3); // remove '8' + ASSERT_EQ(8, removed2); ASSERT_EQ(6u, rb.Size()); const int expected2[6] = {5,6,7,9,10,11}; @@ -448,7 +450,8 @@ TEST(RingBufferTest, Erase_HeadZero_TailPositive) ASSERT_EQ(0u, rb.Head()); ASSERT_EQ(4u, rb.Tail()); - rb.Erase(1); // remove '5' + int removed3 = rb.Erase(1); // remove '5' + ASSERT_EQ(5, removed3); ASSERT_EQ(5u, rb.Size()); const int expected3[5] = {4,6,7,8,9};