fix(utils): prevent panic when pushing to a zero-size ring buffer (#4840)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
TowyTowy
2026-07-15 22:04:37 +02:00
committed by GitHub
parent 6e65b33161
commit 523ac9f35e
2 changed files with 23 additions and 0 deletions
+5
View File
@@ -37,6 +37,11 @@ func RingBufferFrom[T any](size int, data []T) *RingBuffer[T] {
func (r *RingBuffer[T]) Push(data T) { func (r *RingBuffer[T]) Push(data T) {
r.mutex.Lock() r.mutex.Lock()
defer r.mutex.Unlock() defer r.mutex.Unlock()
if r.Size <= 0 {
// A zero (or negative) capacity buffer holds nothing. Bail out before
// indexing r.data or taking a modulo by r.Size, both of which panic.
return
}
if len(r.data) == r.Size { if len(r.data) == r.Size {
r.data[r.start] = data r.data[r.start] = data
r.start = (r.start + 1) % r.Size r.start = (r.start + 1) % r.Size
+18
View File
@@ -44,6 +44,24 @@ func TestRingBuffer_MarshalJSON(t *testing.T) {
} }
} }
func TestRingBuffer_ZeroSize(t *testing.T) {
// A zero-capacity buffer must hold nothing rather than panic. This is
// reachable from the logs endpoint (?min=0), which builds NewRingBuffer(0).
rb := NewRingBuffer[int](0)
rb.Push(1)
rb.Push(2)
if rb.Len() != 0 {
t.Errorf("Expected len to be 0, got %d", rb.Len())
}
data := rb.Data()
if len(data) != 0 {
t.Errorf("Expected data to be empty, got %v", data)
}
}
func TestRingBuffer_Clear(t *testing.T) { func TestRingBuffer_Clear(t *testing.T) {
rb := NewRingBuffer[int](3) rb := NewRingBuffer[int](3)