diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-15 15:02:15 -0700 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-15 15:02:15 -0700 |
commit | 21e4e3de9eee057c32595d9596dc8758b32738fc (patch) | |
tree | 7c62e441e8f8f7fea95c8209c63288b616056678 /syncutil | |
parent | 1328996a17776d74b0f1604a428826b6a761dbe4 (diff) |
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) +} |