github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/internal/xsync/pool.go (about)

     1  package xsync
     2  
     3  import "sync"
     4  
     5  // pool interface uses for testing with mock or standard sync.Pool for runtime
     6  type pool interface {
     7  	Get() (v any)
     8  	Put(v any)
     9  }
    10  
    11  type Pool[T any] struct {
    12  	p   pool
    13  	New func() *T
    14  
    15  	once sync.Once
    16  }
    17  
    18  func (p *Pool[T]) init() {
    19  	p.once.Do(func() {
    20  		if p.p == nil {
    21  			p.p = &sync.Pool{}
    22  		}
    23  	})
    24  }
    25  
    26  func (p *Pool[T]) GetOrNew() *T {
    27  	p.init()
    28  
    29  	if v := p.p.Get(); v != nil {
    30  		return v.(*T) //nolint:forcetypeassert
    31  	}
    32  
    33  	if p.New != nil {
    34  		return p.New()
    35  	}
    36  
    37  	return new(T)
    38  }
    39  
    40  func (p *Pool[T]) GetOrNil() *T {
    41  	p.init()
    42  
    43  	if v := p.p.Get(); v != nil {
    44  		return v.(*T) //nolint:forcetypeassert
    45  	}
    46  
    47  	return nil
    48  }
    49  
    50  func (p *Pool[T]) Put(t *T) {
    51  	p.init()
    52  
    53  	p.p.Put(t)
    54  }