github.com/voedger/voedger@v0.0.0-20240520144910-273e84102129/pkg/appparts/internal/pool/pool.go (about)

     1  /*
     2   * Copyright (c) 2021-present Sigma-Soft, Ltd.
     3   * @author: Nikolay Nikitin
     4   */
     5  
     6  package pool
     7  
     8  // Thread-safe pool of reusable values.
     9  //
    10  // Value is borrowed from poll by calling Borrow() method.
    11  // After using value, it must be returned to pool by calling Release() method.
    12  //
    13  //TODO: adds tests to check that pool is thread-safe
    14  type Pool[T any] struct {
    15  	c chan T
    16  }
    17  
    18  // Creates and returns a new instance of Pool. All passed to New() values are initially placed into the pool.
    19  func New[T any](values []T) *Pool[T] {
    20  	p := &Pool[T]{
    21  		c: make(chan T, len(values)),
    22  	}
    23  	for _, v := range values {
    24  		p.c <- v
    25  	}
    26  	return p
    27  }
    28  
    29  // Borrows a value from pool.
    30  //
    31  // If pool is empty, returns ErrNotEnough.
    32  //
    33  // Borrowed value must be returned to pool by calling Release() method.
    34  func (p *Pool[T]) Borrow() (value T, err error) {
    35  	select {
    36  	case v := <-p.c:
    37  		return v, nil
    38  	default:
    39  		return value, ErrNotEnough
    40  	}
    41  }
    42  
    43  // Returns a value into pool.
    44  func (p *Pool[T]) Release(value T) {
    45  	p.c <- value
    46  }
    47  
    48  // Returns a number of enough values in pool.
    49  func (p *Pool[T]) Len() int {
    50  	return len(p.c)
    51  }