summaryrefslogtreecommitdiff
path: root/typedsync/pool.go
blob: 370d70a8f6494fe0795e96ceb60bd60916b5f393 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package typedsync

import (
	"sync"
)

// Pool is a type-safe equivalent of the standard library's sync.Pool.
//
// See the [sync.Pool documentation] for full details.
//
// [sync.Pool documentation]: https://pkg.go.dev/sync#Pool
type Pool[T any] struct {
	New func() T

	inner sync.Pool
}

func (p *Pool[T]) Get() (val T, ok bool) {
	_val := p.inner.Get()
	switch {
	case _val != nil:
		//nolint:forcetypeassert // Typed wrapper around untyped lib.
		return _val.(T), true
	case p.New != nil:
		return p.New(), true
	default:
		var zero T
		return zero, false
	}
}

func (p *Pool[T]) Put(val T) {
	p.inner.Put(val)
}