Skip to content
Open
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
8 changes: 8 additions & 0 deletions queue/ring.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ type RingBuffer struct {
}

func (rb *RingBuffer) init(size uint64) {
if size == 1 {
// The mask must be a value containing only 1s (left padded with zeros) in its binary
// format (e.g. 0001, 0011, 0111, 1111, and etc.)
// With a size of 1 the mask would be 0 which then in case of having a full queue the
// single item in the ring buffer gets replaced with every insert operation which also makes
// rb.Get() to block since the ring buffer's state becomes invalid despite having a full queue.
size = 2
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very interesting. You have found a bug in the roundUp method that occurs when size <= 1. I propose that we fix that method instead. I also see that it is copied in a few different places so we should move it to a single location.

size = roundUp(size)
rb.nodes = make(nodes, size)
for i := uint64(0); i < size; i++ {
Expand Down
30 changes: 30 additions & 0 deletions queue/ring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,36 @@ import (
"github.com/stretchr/testify/assert"
)

func TestRingInsertWithCapOne(t *testing.T) {
rb := NewRingBuffer(1)
assert.Equal(t, uint64(2), rb.Cap())

err := rb.Put("Hello")
if !assert.Nil(t, err) {
return
}

err = rb.Put("World")
if !assert.Nil(t, err) {
return
}

ok, err := rb.Offer("Hello, Again.")
assert.Nil(t, err)
assert.False(t, ok)

result, err := rb.Get()
if !assert.Nil(t, err) {
return
}
if !assert.NotNil(t, result) {
return
}
assert.Equal(t, result, "Hello")

assert.Equal(t, uint64(1), rb.Len())
}

func TestRingInsert(t *testing.T) {
rb := NewRingBuffer(5)
assert.Equal(t, uint64(8), rb.Cap())
Expand Down