github.com/ethereum/go-ethereum@v1.16.1/trie/bytepool.go (about)

     1  // Copyright 2024 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package trie
    18  
    19  // bytesPool is a pool for byte slices. It is safe for concurrent use.
    20  type bytesPool struct {
    21  	c chan []byte
    22  	w int
    23  }
    24  
    25  // newBytesPool creates a new bytesPool. The sliceCap sets the capacity of
    26  // newly allocated slices, and the nitems determines how many items the pool
    27  // will hold, at maximum.
    28  func newBytesPool(sliceCap, nitems int) *bytesPool {
    29  	return &bytesPool{
    30  		c: make(chan []byte, nitems),
    31  		w: sliceCap,
    32  	}
    33  }
    34  
    35  // Get returns a slice. Safe for concurrent use.
    36  func (bp *bytesPool) Get() []byte {
    37  	select {
    38  	case b := <-bp.c:
    39  		return b
    40  	default:
    41  		return make([]byte, 0, bp.w)
    42  	}
    43  }
    44  
    45  // GetWithSize returns a slice with specified byte slice size.
    46  func (bp *bytesPool) GetWithSize(s int) []byte {
    47  	b := bp.Get()
    48  	if cap(b) < s {
    49  		return make([]byte, s)
    50  	}
    51  	return b[:s]
    52  }
    53  
    54  // Put returns a slice to the pool. Safe for concurrent use. This method
    55  // will ignore slices that are too small or too large (>3x the cap)
    56  func (bp *bytesPool) Put(b []byte) {
    57  	if c := cap(b); c < bp.w || c > 3*bp.w {
    58  		return
    59  	}
    60  	select {
    61  	case bp.c <- b:
    62  	default:
    63  	}
    64  }