Skip to content

Commit

Permalink
bytes_pools with buf ptr (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
micln authored and wongoo committed Jan 4, 2020
1 parent e1a65e2 commit a57121f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
22 changes: 13 additions & 9 deletions bytes/bytes_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ func NewBytesPool(slotSize []int) *BytesPool {
for i, size := range bp.sizes {
size := size
bp.slots[i] = sync.Pool{New: func() interface{} {
return make([]byte, 0, size)
buf := make([]byte, 0, size)
return &buf
}}
}
return bp
Expand All @@ -61,28 +62,31 @@ func (bp *BytesPool) findIndex(size int) int {
}

// AcquireBytes get specific make([]byte, 0, size)
func (bp *BytesPool) AcquireBytes(size int) []byte {
func (bp *BytesPool) AcquireBytes(size int) *[]byte {
idx := bp.findIndex(size)
if idx >= bp.length {
return make([]byte, 0, size)
buf := make([]byte, 0, size)
return &buf
}

return bp.slots[idx].Get().([]byte)[:size]
bufp := bp.slots[idx].Get().(*[]byte)
buf := (*bufp)[:size]
return &buf
}

// ReleaseBytes ...
func (bp *BytesPool) ReleaseBytes(buf []byte) {
bufCap := cap(buf)
func (bp *BytesPool) ReleaseBytes(bufp *[]byte) {
bufCap := cap(*bufp)
idx := bp.findIndex(bufCap)
if idx >= bp.length || bp.sizes[idx] != bufCap {
return
}

bp.slots[idx].Put(buf)
bp.slots[idx].Put(bufp)
}

// AcquireBytes called by defaultBytesPool
func AcquireBytes(size int) []byte { return defaultBytesPool.AcquireBytes(size) }
func AcquireBytes(size int) *[]byte { return defaultBytesPool.AcquireBytes(size) }

// ReleaseBytes called by defaultBytesPool
func ReleaseBytes(buf []byte) { defaultBytesPool.ReleaseBytes(buf) }
func ReleaseBytes(bufp *[]byte) { defaultBytesPool.ReleaseBytes(bufp) }
7 changes: 3 additions & 4 deletions bytes/slice_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,12 @@ func NewSlicePool() *SlicePool {

// Get returns *[]byte from SlicePool
func (p *SlicePool) Get(size int) *[]byte {
b := p.AcquireBytes(size)
return &b
return p.AcquireBytes(size)
}

// Put returns *[]byte to SlicePool
func (p *SlicePool) Put(buf *[]byte) {
p.ReleaseBytes(*buf)
func (p *SlicePool) Put(bufp *[]byte) {
p.ReleaseBytes(bufp)
}

// GetBytes returns *[]byte from SlicePool
Expand Down

0 comments on commit a57121f

Please sign in to comment.