-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer_pool.go
52 lines (44 loc) · 1016 Bytes
/
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
package buf
import (
"sync"
)
// Pool provides functionality to generate and recycle buffers on demand.
type Pool interface {
// Allocate either returns a unused buffer from the pool, or generates a new one from system.
Allocate() *Buffer
// Free recycles the given buffer.
Free(*Buffer)
}
// SyncPool is a buffer pool based on sync.Pool
type SyncPool struct {
allocator *sync.Pool
}
// NewSyncPool creates a SyncPool with given buffer size.
func NewSyncPool(bufferSize uint32) *SyncPool {
pool := &SyncPool{
allocator: &sync.Pool{
New: func() interface{} { return make([]byte, bufferSize) },
},
}
return pool
}
// Allocate implements Pool.Allocate().
func (p *SyncPool) Allocate() *Buffer {
return &Buffer{
v: p.allocator.Get().([]byte),
pool: p,
}
}
// Free implements Pool.Free().
func (p *SyncPool) Free(buffer *Buffer) {
if buffer.v != nil {
p.allocator.Put(buffer.v)
}
}
const (
// Size of a regular buffer.
Size = 2 * 1024
)
var (
mediumPool Pool = NewSyncPool(Size)
)