-
Notifications
You must be signed in to change notification settings - Fork 70
/
bufferpool.go
54 lines (47 loc) 路 1.24 KB
/
bufferpool.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
package bufferpool
import "sync"
// Pool is a wrapper around sync.Pool with a helper Release method on returned objects.
// Objects in the Pool are Buffers which are wrapper of a slice with a pointer to the Pool object.
type Pool struct {
pool sync.Pool
}
// New returns a new Pool for Buffers of size buflen.
func New(buflen int) *Pool {
return &Pool{
pool: sync.Pool{
New: func() interface{} {
b := make([]byte, buflen)
return &b
},
},
}
}
// Get a new Buffer from the pool. datalen must not exceed buffer length given in constructor.
// You should release the Buffer after your work is done by calling Buffer.Release.
func (p *Pool) Get(datalen int) Buffer {
buf := p.pool.Get().(*[]byte)
return newBuffer(buf, datalen, p)
}
// Buffer is a slice with a pointer to Pool.
type Buffer struct {
Data []byte
buf *[]byte
pool *Pool
}
func newBuffer(buf *[]byte, length int, pool *Pool) Buffer {
b := Buffer{
Data: (*buf)[:length],
buf: buf,
pool: pool,
}
// Clear contents before returning to the caller.
for i := range b.Data {
b.Data[i] = 0
}
return b
}
// Release the Buffer and return it to the Pool.
func (b Buffer) Release() {
// argument to Put should be pointer-like to avoid allocations
b.pool.pool.Put(b.buf)
}