-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathpool.go
40 lines (34 loc) · 895 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
// Package bufferpool provides a simple buffer pool for getting and returning
// temporary byte slices for use by io.CopyBuffer.
package bufferpool
import "sync"
// BufPool is an interface for getting and returning temporary
// byte slices for use by io.CopyBuffer.
type BufPool interface {
Get() []byte
Put([]byte)
}
type pool struct {
pool *sync.Pool
}
// NewPool creates a new buffer pool for getting and returning temporary
// byte slices for use by io.CopyBuffer.
func NewPool(size int) BufPool {
return &pool{
&sync.Pool{
New: func() interface{} { return make([]byte, size) },
},
}
}
// Get implements the BufPool interface.
func (p *pool) Get() []byte {
return p.pool.Get().([]byte)
}
// Put implements the BufPool interface.
func (p *pool) Put(b []byte) {
if cap(b) == 0 || len(b) != cap(b) {
// Invalid buffer size, discard the buffer
return
}
p.pool.Put(b)
}