vitess.io/vitess@v0.16.2/go/bucketpool/bucketpool.go (about) 1 /* 2 Copyright 2019 The Vitess Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package bucketpool 18 19 import ( 20 "math/bits" 21 "sync" 22 ) 23 24 type sizedPool struct { 25 size int 26 pool sync.Pool 27 } 28 29 func newSizedPool(size int) *sizedPool { 30 return &sizedPool{ 31 size: size, 32 pool: sync.Pool{ 33 New: func() any { return makeSlicePointer(size) }, 34 }, 35 } 36 } 37 38 // Pool is actually multiple pools which store buffers of specific size. 39 // i.e. it can be three pools which return buffers 32K, 64K and 128K. 40 type Pool struct { 41 minSize int 42 maxSize int 43 pools []*sizedPool 44 } 45 46 // New returns Pool which has buckets from minSize to maxSize. 47 // Buckets increase with the power of two, i.e with multiplier 2: [2b, 4b, 16b, ... , 1024b] 48 // Last pool will always be capped to maxSize. 49 func New(minSize, maxSize int) *Pool { 50 if maxSize < minSize { 51 panic("maxSize can't be less than minSize") 52 } 53 const multiplier = 2 54 var pools []*sizedPool 55 curSize := minSize 56 for curSize < maxSize { 57 pools = append(pools, newSizedPool(curSize)) 58 curSize *= multiplier 59 } 60 pools = append(pools, newSizedPool(maxSize)) 61 return &Pool{ 62 minSize: minSize, 63 maxSize: maxSize, 64 pools: pools, 65 } 66 } 67 68 func (p *Pool) findPool(size int) *sizedPool { 69 if size > p.maxSize { 70 return nil 71 } 72 div, rem := bits.Div64(0, uint64(size), uint64(p.minSize)) 73 idx := bits.Len64(div) 74 if rem == 0 && div != 0 && (div&(div-1)) == 0 { 75 idx = idx - 1 76 } 77 return p.pools[idx] 78 } 79 80 // Get returns pointer to []byte which has len size. 81 // If there is no bucket with buffers >= size, slice will be allocated. 82 func (p *Pool) Get(size int) *[]byte { 83 sp := p.findPool(size) 84 if sp == nil { 85 return makeSlicePointer(size) 86 } 87 buf := sp.pool.Get().(*[]byte) 88 *buf = (*buf)[:size] 89 return buf 90 } 91 92 // Put returns pointer to slice to some bucket. Discards slice for which there is no bucket 93 func (p *Pool) Put(b *[]byte) { 94 sp := p.findPool(cap(*b)) 95 if sp == nil { 96 return 97 } 98 *b = (*b)[:cap(*b)] 99 sp.pool.Put(b) 100 } 101 102 func makeSlicePointer(size int) *[]byte { 103 data := make([]byte, size) 104 return &data 105 }