Skip to content

Commit 337c45a

Browse files
committed
Fix panic on piring.Buffer.PointerTo(-Cap())
Function panic when parameter is equal to -Cap(). Update the ring buffer’s index logic so negative and positive offsets always wrap correctly within bounds
1 parent a3ed728 commit 337c45a

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

piring/piring.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,10 @@ func (b *Buffer[E]) Cap() int {
4242
func (b *Buffer[E]) PointerTo(index int) *E {
4343
idx := index + b.start
4444

45-
if idx < 0 {
46-
idx = len(b.data) + idx%len(b.data)
47-
} else if idx >= len(b.data) {
48-
idx %= len(b.data)
45+
// wrap the index so that both positive and negative values fall
46+
// into the [0, Cap()-1] range
47+
if capacity := len(b.data); capacity > 0 {
48+
idx = ((idx % capacity) + capacity) % capacity
4949
}
5050

5151
return &b.data[idx]

piring/piring_test.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ func TestBuffer(t *testing.T) {
1818
assert.Zero(t, *buffer.PointerTo(0))
1919
})
2020

21-
t.Run("no circle", func(t *testing.T) {
21+
t.Run("no cycle", func(t *testing.T) {
2222
buffer := piring.NewBuffer[int](3)
2323
*buffer.NextWritePointer() = 0
2424
*buffer.NextWritePointer() = 1
@@ -31,7 +31,7 @@ func TestBuffer(t *testing.T) {
3131
assertHas(t, buffer, 2, 2)
3232
})
3333

34-
t.Run("circle", func(t *testing.T) {
34+
t.Run("cycle", func(t *testing.T) {
3535
buffer := piring.NewBuffer[int](2)
3636
*buffer.NextWritePointer() = 0
3737
*buffer.NextWritePointer() = 1
@@ -43,7 +43,7 @@ func TestBuffer(t *testing.T) {
4343
assertHas(t, buffer, 1, 2)
4444
})
4545

46-
t.Run("two circles", func(t *testing.T) {
46+
t.Run("two cycles", func(t *testing.T) {
4747
buffer := piring.NewBuffer[int](2)
4848
*buffer.NextWritePointer() = 0
4949
*buffer.NextWritePointer() = 1
@@ -95,6 +95,14 @@ func TestBuffer(t *testing.T) {
9595
assertHas(t, buffer, 5, *buffer.PointerTo(1))
9696
assertHas(t, buffer, -5, *buffer.PointerTo(1))
9797
})
98+
99+
t.Run("negative index equal to -Cap()", func(t *testing.T) {
100+
buffer := piring.NewBuffer[int](2)
101+
*buffer.NextWritePointer() = 0
102+
*buffer.NextWritePointer() = 1
103+
104+
assertHas(t, buffer, -buffer.Cap(), *buffer.PointerTo(0))
105+
})
98106
}
99107

100108
func assertHas[T any](t *testing.T, buffer *piring.Buffer[T], index int, value T) {

0 commit comments

Comments
 (0)