pool.go 707 B

12345678910111213141516171819202122232425262728293031
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package syncs
  4. import "sync"
  5. // Pool is the generic version of [sync.Pool].
  6. type Pool[T any] struct {
  7. pool sync.Pool
  8. // New optionally specifies a function to generate
  9. // a value when Get would otherwise return the zero value of T.
  10. // It may not be changed concurrently with calls to Get.
  11. New func() T
  12. }
  13. // Get selects an arbitrary item from the Pool, removes it from the Pool,
  14. // and returns it to the caller. See [sync.Pool.Get].
  15. func (p *Pool[T]) Get() T {
  16. x, ok := p.pool.Get().(T)
  17. if !ok && p.New != nil {
  18. x = p.New()
  19. }
  20. return x
  21. }
  22. // Put adds x to the pool.
  23. func (p *Pool[T]) Put(x T) {
  24. p.pool.Put(x)
  25. }