/
slice_pool.go
63 lines (52 loc) · 1.02 KB
/
slice_pool.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package alphacats
import (
"sync"
"github.com/timpalpant/alphacats/gamestate"
)
const maxPoolSize = 1024
type gameNodeSlicePool struct {
mx sync.Mutex
pool [][]GameNode
}
func (p *gameNodeSlicePool) alloc(n int) []GameNode {
p.mx.Lock()
m := len(p.pool)
if m > 0 {
next := p.pool[m-1]
p.pool = p.pool[:m-1]
p.mx.Unlock()
return next[:0]
}
p.mx.Unlock()
return make([]GameNode, 0, n)
}
func (p *gameNodeSlicePool) free(s []GameNode) {
p.mx.Lock()
if len(p.pool) < maxPoolSize {
p.pool = append(p.pool, s[:0])
}
p.mx.Unlock()
}
type actionSlicePool struct {
mx sync.Mutex
pool [][]gamestate.Action
}
func (p *actionSlicePool) alloc(n int) []gamestate.Action {
p.mx.Lock()
if len(p.pool) > 0 {
m := len(p.pool)
next := p.pool[m-1]
p.pool = p.pool[:m-1]
p.mx.Unlock()
return next[:0]
}
p.mx.Unlock()
return make([]gamestate.Action, 0, n)
}
func (p *actionSlicePool) free(s []gamestate.Action) {
p.mx.Lock()
if len(p.pool) < maxPoolSize {
p.pool = append(p.pool, s[:0])
}
p.mx.Unlock()
}