-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer_pool.go
60 lines (53 loc) · 1.08 KB
/
buffer_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
package alloc
import (
"sync"
)
type BufferPool struct {
chain chan []byte
allocator *sync.Pool
}
func NewBufferPool(bufferSize, poolSize int) *BufferPool {
pool := &BufferPool{
chain: make(chan []byte, poolSize),
allocator: &sync.Pool{
New: func() interface{} { return make([]byte, bufferSize) },
},
}
for i := 0; i < poolSize/2; i++ {
pool.chain <- make([]byte, bufferSize)
}
return pool
}
func (p *BufferPool) Allocate() *Buffer {
var b []byte
select {
case b = <-p.chain:
default:
b = p.allocator.Get().([]byte)
}
return &Buffer{
head: b,
pool: p,
Value: b[defaultOffset:],
offset: defaultOffset,
}
}
func (p *BufferPool) Free(buffer *Buffer) {
rawBuffer := buffer.head
if rawBuffer == nil {
return
}
select {
case p.chain <- rawBuffer:
default:
p.allocator.Put(rawBuffer)
}
}
const (
SmallBufferSize = 1600 - defaultOffset
BufferSize = 8*1024 - defaultOffset
LargeBufferSize = 64*1024 - defaultOffset
)
var smallPool = NewBufferPool(1600, 128)
var mediumPool = NewBufferPool(8*1024, 128)
var largePool = NewBufferPool(64*1024, 64)