mirror of
https://github.com/amir20/dozzle.git
synced 2026-08-07 09:04:44 +00:00
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:
@@ -37,6 +37,11 @@ func RingBufferFrom[T any](size int, data []T) *RingBuffer[T] {
|
||||
func (r *RingBuffer[T]) Push(data T) {
|
||||
r.mutex.Lock()
|
||||
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 {
|
||||
r.data[r.start] = data
|
||||
r.start = (r.start + 1) % r.Size
|
||||
|
||||
@@ -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) {
|
||||
rb := NewRingBuffer[int](3)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user