/
buffer_pool.go
95 lines (68 loc) · 1.53 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package types
import (
"bufio"
"io"
"sync"
)
type WritePool interface {
Get(io.Reader) *bufio.Reader
Put(*bufio.Reader)
}
type writePool struct {
sync.Mutex
size int
growSize int
shrinkSize int
growThreshold int
shrinkThreshold int
buffers []*bufio.Reader
}
var _ WritePool = (*writePool)(nil)
func NewWritePool(size, preAlloc, grow, shrink int) (WritePool, error) {
pool := &writePool{
size: size,
growSize: grow,
shrinkSize: shrink,
growThreshold: calcThreshold(preAlloc, grow),
shrinkThreshold: calcThreshold(preAlloc, shrink),
}
for i := 0; i < preAlloc; i++ {
pool.buffers = append(pool.buffers, bufio.NewReaderSize(pool, size))
}
return pool, nil
}
func (b *writePool) Get(rd io.Reader) *bufio.Reader {
b.Lock()
if len(b.buffers) == 0 {
// double amount of buffers
sz := cap(b.buffers)
var buffers []*bufio.Reader
for i := 0; i < sz; i++ {
buffers = append(buffers, bufio.NewReaderSize(b, b.size))
}
b.buffers = append(buffers, b.buffers...)
}
buf := b.buffers[len(b.buffers)-1]
buf.Reset(rd)
b.buffers = b.buffers[:len(b.buffers)-1]
b.Unlock()
return buf
}
func (b *writePool) Put(buf *bufio.Reader) {
b.Lock()
buf.Reset(b)
b.buffers = append(b.buffers, buf)
b.Unlock()
}
func (b *writePool) Read(p []byte) (n int, err error) {
return 0, nil
}
// nolint:unused
func (b *writePool) grow() {
}
// nolint:unused
func (b *writePool) shrink() {
}
func calcThreshold(size, grow int) int {
return (grow * size) / 100
}