Skip to content

Instantly share code, notes, and snippets.

@omerkaya1
Created September 22, 2023 15:53
Show Gist options
  • Save omerkaya1/baf5d21cfcc6b03a09407b5972a1b0a9 to your computer and use it in GitHub Desktop.
Save omerkaya1/baf5d21cfcc6b03a09407b5972a1b0a9 to your computer and use it in GitHub Desktop.
A sized pool of slices of generic type objects
// SizedPool is a channel-based pool of slices objects.
// It retains an arbitrary number of slices of objects and ensures their initial capacity.
type SizedPool[T any] struct {
pool chan []T
cap int
}
func NewSizedPool[T any](size int, cap int) *SizedPool[T] {
return &SizedPool[T]{
pool: make(chan []T, size),
cap: cap,
}
}
// Get either returns a slice of T from the pool or creates one anew.
func (p *SizedPool[T]) Get() []T {
select {
case b := <-p.pool:
return b
default:
return make([]T, 0, p.cap)
}
}
// Put returns an object to the pool, resetting it and zeroing its values first.
// It also ensures that the returned object does not exceed its set capacity by allocating a new slice if necessary.
func (p *SizedPool[T]) Put(s []T) {
for i := range s {
var t T
s[i] = t
}
s = s[:0]
if cap(s) > p.cap {
s = make([]T, 0, p.cap)
}
select {
case p.pool <- s:
default:
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment