Skip to content

Commit 92707bf

Browse files
committed
Erase now returns old value
1 parent 7aabdf5 commit 92707bf

2 files changed

Lines changed: 14 additions & 6 deletions

File tree

src/jc/cpp/ringbuffer.h

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,8 @@ class RingBuffer
7777
void PushUnchecked(const T& item);
7878
/// Removes (and returns) the first inserted item from the ring buffer. Asserts if the buffer is empty
7979
T Pop();
80-
/// Removes the element at logical index (0-based) and keeps order
81-
void Erase(uint32_t index);
80+
/// Removes the element at logical index (0-based), keeps order, returns old value
81+
T Erase(uint32_t index);
8282

8383
T& operator[] (size_t i) { assert(i < Size()); return m_Buffer[(m_Tail + i) % m_Max]; }
8484
const T& operator[] (size_t i) const { assert(i < Size()); return m_Buffer[(m_Tail + i) % m_Max]; }
@@ -195,14 +195,17 @@ T RingBuffer<T>::Pop()
195195
}
196196

197197
template <typename T>
198-
void RingBuffer<T>::Erase(uint32_t index)
198+
T RingBuffer<T>::Erase(uint32_t index)
199199
{
200200
uint32_t size = Size();
201201
assert(index < size);
202202

203203
// Compute physical index of the element to erase
204204
uint32_t pos = (m_Tail + index) % m_Max;
205205

206+
// Store old value to return
207+
T old_value = m_Buffer[pos];
208+
206209
// Shift elements left from pos towards head to preserve order
207210
// Stop when the next index equals m_Head (the logical end)
208211
while (true)
@@ -225,6 +228,8 @@ void RingBuffer<T>::Erase(uint32_t index)
225228
--m_Head;
226229
}
227230
m_Full = 0;
231+
232+
return old_value;
228233
}
229234

230235

test/ringbuffer.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,8 @@ TEST(RingBufferTest, Erase_Contiguous_Middle)
411411
jc::RingBuffer<int> rb(8);
412412
for (int i = 0; i < 6; ++i) rb.Push(i); // 0..5
413413

414-
rb.Erase(2); // remove '2'
414+
int removed = rb.Erase(2); // remove '2'
415+
ASSERT_EQ(2, removed);
415416
ASSERT_EQ(5u, rb.Size());
416417
const int expected1[5] = {0,1,3,4,5};
417418
for (uint32_t i = 0; i < 5; ++i)
@@ -427,7 +428,8 @@ TEST(RingBufferTest, Erase_Wrapped_Middle)
427428
for (int i = 0; i < 5; ++i) rb.Pop(); // -> [5,6,7]
428429
for (int i = 8; i < 12; ++i) rb.Push(i); // wrap -> [5,6,7,8,9,10,11]
429430

430-
rb.Erase(3); // remove '8'
431+
int removed2 = rb.Erase(3); // remove '8'
432+
ASSERT_EQ(8, removed2);
431433

432434
ASSERT_EQ(6u, rb.Size());
433435
const int expected2[6] = {5,6,7,9,10,11};
@@ -448,7 +450,8 @@ TEST(RingBufferTest, Erase_HeadZero_TailPositive)
448450
ASSERT_EQ(0u, rb.Head());
449451
ASSERT_EQ(4u, rb.Tail());
450452

451-
rb.Erase(1); // remove '5'
453+
int removed3 = rb.Erase(1); // remove '5'
454+
ASSERT_EQ(5, removed3);
452455

453456
ASSERT_EQ(5u, rb.Size());
454457
const int expected3[5] = {4,6,7,8,9};

0 commit comments

Comments
 (0)