Skip to content

RingBuffer with a size of 1 should not be allowed due to an insert bug, so increment a size of one, by one. #218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
}
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