diff options
Diffstat (limited to 'syncutil')
-rw-r--r-- | syncutil/slicepool.go | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/syncutil/slicepool.go b/syncutil/slicepool.go new file mode 100644 index 0000000..8b566de --- /dev/null +++ b/syncutil/slicepool.go @@ -0,0 +1,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) +} |