storj.io/minio@v0.0.0-20230509071714-0cbc90f649b1/pkg/bpool/bpool.go (about)

     1  // Original work https://github.com/oxtoacart/bpool borrowed
     2  // only bpool.go licensed under Apache 2.0.
     3  
     4  // This file modifies original bpool.go to add one more option
     5  // to provide []byte capacity for better GC management.
     6  
     7  /*
     8   * MinIO Cloud Storage (C) 2018 MinIO, Inc.
     9   *
    10   * Licensed under the Apache License, Version 2.0 (the "License");
    11   * you may not use this file except in compliance with the License.
    12   * You may obtain a copy of the License at
    13   *
    14   *     http://www.apache.org/licenses/LICENSE-2.0
    15   *
    16   * Unless required by applicable law or agreed to in writing, software
    17   * distributed under the License is distributed on an "AS IS" BASIS,
    18   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    19   * See the License for the specific language governing permissions and
    20   * limitations under the License.
    21   */
    22  
    23  package bpool
    24  
    25  // BytePoolCap implements a leaky pool of []byte in the form of a bounded channel.
    26  type BytePoolCap struct {
    27  	c    chan []byte
    28  	w    int
    29  	wcap int
    30  }
    31  
    32  // NewBytePoolCap creates a new BytePool bounded to the given maxSize, with new
    33  // byte arrays sized based on width.
    34  func NewBytePoolCap(maxSize int, width int, capwidth int) (bp *BytePoolCap) {
    35  	return &BytePoolCap{
    36  		c:    make(chan []byte, maxSize),
    37  		w:    width,
    38  		wcap: capwidth,
    39  	}
    40  }
    41  
    42  // Get gets a []byte from the BytePool, or creates a new one if none are
    43  // available in the pool.
    44  func (bp *BytePoolCap) Get() (b []byte) {
    45  	select {
    46  	case b = <-bp.c:
    47  	// reuse existing buffer
    48  	default:
    49  		// create new buffer
    50  		if bp.wcap > 0 {
    51  			b = make([]byte, bp.w, bp.wcap)
    52  		} else {
    53  			b = make([]byte, bp.w)
    54  		}
    55  	}
    56  	return
    57  }
    58  
    59  // Put returns the given Buffer to the BytePool.
    60  func (bp *BytePoolCap) Put(b []byte) {
    61  	select {
    62  	case bp.c <- b:
    63  		// buffer went back into pool
    64  	default:
    65  		// buffer didn't go back into pool, just discard
    66  	}
    67  }
    68  
    69  // Width returns the width of the byte arrays in this pool.
    70  func (bp *BytePoolCap) Width() (n int) {
    71  	return bp.w
    72  }
    73  
    74  // WidthCap returns the cap width of the byte arrays in this pool.
    75  func (bp *BytePoolCap) WidthCap() (n int) {
    76  	return bp.wcap
    77  }