github.com/webmafia/fast@v0.10.0/pool.go (about)

     1  package fast
     2  
     3  import "sync"
     4  
     5  type Pool[T any] struct {
     6  	pool  sync.Pool
     7  	init  func(*T)
     8  	reset func(*T)
     9  }
    10  
    11  // Created a new pool and accepts two (2) optional callbacks. The first is a initializer, and will be called
    12  // whenever a new item (T) is created. The last is a resetter, and will be called whenever an item is
    13  // released back to the pool.
    14  func NewPool[T any](cb ...func(*T)) *Pool[T] {
    15  	p := new(Pool[T])
    16  
    17  	if len(cb) > 0 {
    18  		p.init = cb[0]
    19  	}
    20  
    21  	if len(cb) > 1 {
    22  		p.reset = cb[1]
    23  	}
    24  
    25  	return p
    26  }
    27  
    28  // Acquires an item from the pool.
    29  func (p *Pool[T]) Acquire() *T {
    30  	if v, ok := p.pool.Get().(*T); ok {
    31  		return v
    32  	}
    33  
    34  	v := new(T)
    35  
    36  	if p.init != nil {
    37  		p.init(v)
    38  	}
    39  
    40  	return v
    41  }
    42  
    43  // Releases an item back to the pool. The item cannot be used after release.
    44  func (p *Pool[T]) Release(v *T) {
    45  	if p.reset != nil {
    46  		p.reset(v)
    47  	}
    48  
    49  	p.pool.Put(v)
    50  }