github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/lang/mcache/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 mcache
    16  
    17  import (
    18  	"sync"
    19  
    20  	"github.com/bytedance/gopkg/lang/dirtmake"
    21  )
    22  
    23  const maxSize = 46
    24  
    25  // index contains []byte which cap is 1<<index
    26  var caches [maxSize]sync.Pool
    27  
    28  func init() {
    29  	for i := 0; i < maxSize; i++ {
    30  		size := 1 << i
    31  		caches[i].New = func() interface{} {
    32  			buf := dirtmake.Bytes(0, size)
    33  			return buf
    34  		}
    35  	}
    36  }
    37  
    38  // calculates which pool to get from
    39  func calcIndex(size int) int {
    40  	if size == 0 {
    41  		return 0
    42  	}
    43  	if isPowerOfTwo(size) {
    44  		return bsr(size)
    45  	}
    46  	return bsr(size) + 1
    47  }
    48  
    49  // Malloc supports one or two integer argument.
    50  // The size specifies the length of the returned slice, which means len(ret) == size.
    51  // A second integer argument may be provided to specify the minimum capacity, which means cap(ret) >= cap.
    52  func Malloc(size int, capacity ...int) []byte {
    53  	if len(capacity) > 1 {
    54  		panic("too many arguments to Malloc")
    55  	}
    56  	var c = size
    57  	if len(capacity) > 0 && capacity[0] > size {
    58  		c = capacity[0]
    59  	}
    60  	var ret = caches[calcIndex(c)].Get().([]byte)
    61  	ret = ret[:size]
    62  	return ret
    63  }
    64  
    65  // Free should be called when the buf is no longer used.
    66  func Free(buf []byte) {
    67  	size := cap(buf)
    68  	if !isPowerOfTwo(size) {
    69  		return
    70  	}
    71  	buf = buf[:0]
    72  	caches[bsr(size)].Put(buf)
    73  }