Skip to content

Commit

Permalink
opt: lazily allocate memory for ring-buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
panjf2000 committed Apr 3, 2020
1 parent 94246dc commit 095ef52
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
6 changes: 3 additions & 3 deletions pool/ringbuffer/ringbuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ type Pool struct {

var defaultPool Pool

func init() {
defaultPool.defaultSize = 1 << 12
}
//func init() {
// defaultPool.defaultSize = 1 << 12
//}

// Get returns an empty byte buffer from the pool.
//
Expand Down
3 changes: 3 additions & 0 deletions ringbuffer/ring_buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ type RingBuffer struct {

// New returns a new RingBuffer whose buffer has the given size.
func New(size int) *RingBuffer {
if size == 0 {
return &RingBuffer{isEmpty: true}
}
size = internal.CeilToPowerOfTwo(size)
return &RingBuffer{
buf: make([]byte, size),
Expand Down
34 changes: 34 additions & 0 deletions ringbuffer/ring_buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,40 @@ func TestRingBuffer_Write(t *testing.T) {
}
}

func TestZeroRingBuffer(t *testing.T) {
rb := New(0)
head, tail := rb.LazyRead(1)
if !(head == nil && tail == nil) {
t.Fatal("expect head and tail are all nil")
}
head, tail = rb.LazyReadAll()
if !(head == nil && tail == nil) {
t.Fatal("expect head and tail are all nil")
}
if rb.Length() != 0 {
t.Fatal("expect length is 0")
}
if rb.Free() != 0 {
t.Fatal("expect free is 0")
}
buf := []byte(strings.Repeat("1234", 12))
rb.Write(buf)
if !(rb.Len() == 64 && rb.Cap() == 64) {
t.Fatalf("expect rb.Len()=64 and rb.Cap=64, but got rb.Len()=%d and rb.Cap()=%d", rb.Len(), rb.Cap())
}
if !(rb.r == 0 && rb.w == 48 && rb.size == 64 && rb.mask == 63) {
t.Fatalf("expect rb.r=0, rb.w=48, rb.size=64, rb.mask=63, but got rb.r=%d, rb.w=%d, rb.size=%d, rb.mask=%d",
rb.r, rb.w, rb.size, rb.mask)
}
if !bytes.Equal(rb.ByteBuffer().Bytes(), buf) {
t.Fatal("expect it is equal")
}
rb.Shift(48)
if !(rb.IsEmpty() && rb.r == 0 && rb.w == 0) {
t.Fatalf("expect rb is empty and rb.r=rb.w=0, but got rb.r=%d and rb.w=%d", rb.r, rb.w)
}
}

func TestRingBuffer_Read(t *testing.T) {
rb := New(64)

Expand Down

0 comments on commit 095ef52

Please sign in to comment.