summaryrefslogtreecommitdiff
path: root/syncutil/slicepool.go
blob: 8b566defbbe6be66997cdd7cb78fb0a6ed12d9b3 (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
// Copyright (C) 2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package syncutil

import (
	"git.lukeshu.com/go/containers/typedsync"
)

type SlicePool[T any] struct {
	// TODO(lukeshu): Consider bucketing slices by size, to
	// increase odds that the `cap(ret) >= size` check passes.
	inner typedsync.Pool[[]T]
}

func (p *SlicePool[T]) Get(size int) []T {
	if size == 0 {
		return nil
	}
	ret, ok := p.inner.Get()
	if ok && cap(ret) >= size {
		ret = ret[:size]
	} else {
		ret = make([]T, size)
	}
	return ret
}

func (p *SlicePool[T]) Put(slice []T) {
	if slice == nil {
		return
	}
	p.inner.Put(slice)
}