From 21e4e3de9eee057c32595d9596dc8758b32738fc Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Wed, 15 Feb 2023 15:02:15 -0700 Subject: syncutil: Add SlicePool --- syncutil/slicepool.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 syncutil/slicepool.go 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 +// +// 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) +} -- cgit v1.2.3-54-g00ecf