Skip to content

Commit

Permalink
pool: simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
IrineSistiana committed Mar 26, 2022
1 parent 9f5e951 commit 017fddb
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 19 deletions.
4 changes: 2 additions & 2 deletions dispatcher/pkg/pool/allocator.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const intSize = 32 << (^uint(0) >> 63)
var defaultBufPool = NewAllocator(intSize - 1)

// GetBuf returns a *Buffer from pool with most appropriate cap.
// It panics if size <= 0.
// It panics if size < 0.
func GetBuf(size int) *Buffer {
return defaultBufPool.Get(size)
}
Expand Down Expand Up @@ -77,7 +77,7 @@ func NewAllocator(maxPoolBitsLen int) *Allocator {

// Get returns a []byte from pool with most appropriate cap
func (alloc *Allocator) Get(size int) *Buffer {
if size <= 0 {
if size < 0 {
panic(fmt.Sprintf("invalid slice size %d", size))
}

Expand Down
4 changes: 3 additions & 1 deletion dispatcher/pkg/pool/allocator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ func TestAllocator_Get(t *testing.T) {
wantPanic bool
}{
{-1, 0, true}, // invalid
{0, 0, true}, // invalid
{0, 1, false},
{1, 1, false},
{2, 2, false},
{12, 16, false},
{256, 256, false},
{257, 0, true}, // invalid, too large
Expand Down
22 changes: 6 additions & 16 deletions dispatcher/pkg/pool/msg_buf.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,18 @@
package pool

import (
"fmt"
"github.com/miekg/dns"
)

// There is no such way to give dns.Msg.PackBuffer() a buffer
// with a proper size.
// Just give it a big buf and hope the buf will be reused in most scenes.
const packBufSize = 4096

// PackBuffer packs the dns msg m to wire format.
// Callers should release the buf after they have done with the wire []byte.
func PackBuffer(m *dns.Msg) (wire []byte, buf *Buffer, err error) {
l := m.Len()
if l > dns.MaxMsgSize || l <= 0 {
return nil, nil, fmt.Errorf("msg length %d is invalid", l)
}

// dns.Msg.PackBuffer() needs one more bit than its msg length.
// It also needs a much larger buffer if the msg is compressed.
// It is tedious to force dns.Msg.PackBuffer() to use the buffer.
// Just give it a big buf and hope the buf will be reused in most scenes.
if l > 4095 {
buf = GetBuf(l + 1)
} else {
buf = GetBuf(4096)
}

buf = GetBuf(packBufSize)
wire, err = m.PackBuffer(buf.Bytes())
if err != nil {
buf.Release()
Expand Down

0 comments on commit 017fddb

Please sign in to comment.