github.com/yandex/pandora@v0.5.32/core/clientpool/pool.go (about)

     1  package clientpool
     2  
     3  import (
     4  	"errors"
     5  	"sync/atomic"
     6  )
     7  
     8  func New[T any](size int) (*Pool[T], error) {
     9  	if size <= 0 {
    10  		return nil, errors.New("pool size must be greater than zero")
    11  	}
    12  	return &Pool[T]{
    13  		pool: make([]T, 0, size),
    14  	}, nil
    15  }
    16  
    17  type Pool[T any] struct {
    18  	pool []T
    19  	i    atomic.Uint64
    20  }
    21  
    22  func (p *Pool[T]) Add(conn T) {
    23  	p.pool = append(p.pool, conn)
    24  }
    25  
    26  func (p *Pool[T]) Next() T {
    27  	if len(p.pool) == 0 {
    28  		var zero T
    29  		return zero
    30  	}
    31  	i := p.i.Add(1)
    32  	return p.pool[int(i)%len(p.pool)]
    33  }