github.com/songzhibin97/gkit@v1.2.13/cache/mbuffer/mcache.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package mbuffer
    16  
    17  import (
    18  	"sync"
    19  )
    20  
    21  const maxSize = 46
    22  
    23  // index contains []byte which cap is 1<<index
    24  var caches [maxSize]sync.Pool
    25  
    26  func init() {
    27  	for i := 0; i < maxSize; i++ {
    28  		size := 1 << i
    29  		caches[i].New = func() interface{} {
    30  			buf := make([]byte, 0, size)
    31  			return buf
    32  		}
    33  	}
    34  }
    35  
    36  // calculates which pool to get from
    37  func calcIndex(size int) int {
    38  	if size == 0 {
    39  		return 0
    40  	}
    41  	if isPowerOfTwo(size) {
    42  		return bsr(size)
    43  	}
    44  	return bsr(size) + 1
    45  }
    46  
    47  // Malloc supports one or two integer argument.
    48  // The size specifies the length of the returned slice, which means len(ret) == size.
    49  // A second integer argument may be provided to specify the minimum capacity, which means cap(ret) >= cap.
    50  func Malloc(size int, capacity ...int) []byte {
    51  	if len(capacity) > 1 {
    52  		panic("too many arguments to Malloc")
    53  	}
    54  	var c = size
    55  	if len(capacity) > 0 && capacity[0] > size {
    56  		c = capacity[0]
    57  	}
    58  	var ret = caches[calcIndex(c)].Get().([]byte)
    59  	ret = ret[:size]
    60  	return ret
    61  }
    62  
    63  // Free should be called when the buf is no longer used.
    64  func Free(buf []byte) {
    65  	size := cap(buf)
    66  	if !isPowerOfTwo(size) {
    67  		return
    68  	}
    69  	buf = buf[:0]
    70  	caches[bsr(size)].Put(buf)
    71  }