-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
59 lines (54 loc) · 814 Bytes
/
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
package pool
import (
"sync"
"github.com/powerpuffpenguin/streamf/config"
)
type Pool struct {
ch chan []byte
size int
pool sync.Pool
}
func New(conf *config.Pool) *Pool {
size := conf.Size
cache := conf.Cache
if size < 1024*4 {
size = 1024 * 32
}
var ch chan []byte
if cache > 0 {
ch = make(chan []byte, cache)
}
p := &Pool{
ch: ch,
size: size,
}
p.pool.New = func() any {
return make([]byte, size)
}
return p
}
func (p *Pool) Size() int {
return p.size
}
func (p *Pool) Get() []byte {
if p.ch != nil {
select {
case b := <-p.ch:
return b[:p.size]
default:
}
}
return p.pool.Get().([]byte)[:p.size]
}
func (p *Pool) Put(b []byte) {
if cap(b) < p.size {
return
} else if p.ch != nil {
select {
case p.ch <- b:
return
default:
}
}
p.pool.Put(b)
}