summaryrefslogtreecommitdiff
path: root/pool.go
blob: 06e355c7b776bf05883c4f12ea50354f281aa908 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
}