diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-12 16:17:02 -0700 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2023-02-12 16:17:02 -0700 |
commit | cfcc753dc8906817e15b1b7c36b4dc12462d12e4 (patch) | |
tree | f5d2aa0caaa4cb336017ba7595c3425f4aa00bfc /lib/containers/slicepool.go | |
parent | 29b6b9f997913f13a0bff8bb1278a61302413615 (diff) | |
parent | f76faa4b8debd9c94751a03dd65e46c80a340a82 (diff) |
Merge branch 'lukeshu/fast'
Diffstat (limited to 'lib/containers/slicepool.go')
-rw-r--r-- | lib/containers/slicepool.go | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/lib/containers/slicepool.go b/lib/containers/slicepool.go new file mode 100644 index 0000000..861691a --- /dev/null +++ b/lib/containers/slicepool.go @@ -0,0 +1,35 @@ +// Copyright (C) 2023 Luke Shumaker <lukeshu@lukeshu.com> +// +// SPDX-License-Identifier: GPL-2.0-or-later + +package containers + +import ( + "git.lukeshu.com/go/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) +} |