diff options
Diffstat (limited to 'pool.go')
| -rw-r--r-- | pool.go | 42 |
1 files changed, 42 insertions, 0 deletions
@@ -0,0 +1,42 @@ +package main + +import ( + "sync" +) + +const MAX_POOL_SIZE = 50 + +// Pool is a simple pool implementation which grows (up to MAX_POOL_SIZE) when +// needed. +type Pool[T any] struct { + New func() (*T, error) + pool [MAX_POOL_SIZE]*T + size int8 + mu sync.Mutex +} + +// Get returns an instance of T from the pool if it's has one. When it doesn't +// - a new instance is created and returned. +func (p *Pool[T]) Get() (*T, error) { + p.mu.Lock() + defer p.mu.Unlock() + last := p.size - 1 + if last < 0 { + return p.New() + } + res := p.pool[last] + p.pool[last] = nil + p.size = last + return res, nil +} + +// Put returns an instance of T to the pool. If the pool is full - does nothing. +func (p *Pool[T]) Put(item *T) { + p.mu.Lock() + defer p.mu.Unlock() + if p.size + 1 > MAX_POOL_SIZE { + return + } + p.pool[p.size] = item + p.size = p.size + 1 +} |
