Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/jc/cpp/ringbuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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]; }
Expand Down Expand Up @@ -195,14 +195,17 @@ T RingBuffer<T>::Pop()
}

template <typename T>
void RingBuffer<T>::Erase(uint32_t index)
T RingBuffer<T>::Erase(uint32_t index)
{
uint32_t size = Size();
assert(index < size);

// 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)
Expand All @@ -225,6 +228,8 @@ void RingBuffer<T>::Erase(uint32_t index)
--m_Head;
}
m_Full = 0;

return old_value;
}


Expand Down
9 changes: 6 additions & 3 deletions test/ringbuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,8 @@ TEST(RingBufferTest, Erase_Contiguous_Middle)
jc::RingBuffer<int> 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)
Expand All @@ -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};
Expand All @@ -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};
Expand Down