Skip to content

Commit

Permalink
syncy: add Pool
Browse files Browse the repository at this point in the history
  • Loading branch information
micvbang committed May 9, 2024
1 parent bc824f8 commit 390b24b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
28 changes: 28 additions & 0 deletions syncy/pool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package syncy

import "sync"

// Pool is a simple wrapper around sync.Pool, providing type safety.
type Pool[T any] struct {
pool *sync.Pool
}

func NewPool[T any](new func() T) *Pool[T] {
pool := &sync.Pool{
New: func() any {
return new()
},
}

return &Pool[T]{
pool: pool,
}
}

func (p *Pool[T]) Put(v T) {
p.pool.Put(v)
}

func (p *Pool[T]) Get() T {
return p.pool.Get().(T)
}
27 changes: 27 additions & 0 deletions syncy/pool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package syncy_test

import (
"testing"

"github.com/micvbang/go-helpy/syncy"
)

func TestPoolSingleResource(t *testing.T) {
p := syncy.NewPool(func() *int {
var n = 0
return &n
})

const expectedN = 10

for i := 0; i < expectedN; i++ {
n := p.Get()
*n += 1
p.Put(n)
}

n := p.Get()
if *n != expectedN {
t.Fatalf("expected n == %d, got n == %d", expectedN, *n)
}
}

0 comments on commit 390b24b

Please sign in to comment.