-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
99 lines (82 loc) · 1.97 KB
/
pool.go
File metadata and controls
99 lines (82 loc) · 1.97 KB
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
96
97
98
99
package bytespool
import (
"context"
"errors"
"sync"
"sync/atomic"
"golang.org/x/sync/semaphore"
)
const (
unLimitedPoolCapacity int = 0
defaultSegmentSize int = 1024 * 4
)
type segment struct {
data []byte
size int // size of data with content in the segment, size would always increase
offset int // offset of data in the segment, it is used for read
}
var ErrPoolFull = errors.New("pool is full")
var ErrPoolTooSmall = errors.New("pool is too small")
type Pool struct {
sem *semaphore.Weighted
pool sync.Pool
capacity int
curSegmentNum int64
segmentSize int
}
func (bp *Pool) isUnlimited() bool {
return bp.capacity == unLimitedPoolCapacity
}
func (bp *Pool) capacityInBytes() int {
return bp.capacity * bp.segmentSize
}
func (bp *Pool) Get(ctx context.Context) (*segment, error) {
if bp.capacity != unLimitedPoolCapacity {
if err := bp.sem.Acquire(ctx, 1); err != nil {
return nil, err
}
}
atomic.AddInt64(&bp.curSegmentNum, 1)
return bp.pool.Get().(*segment), nil
}
func (bp *Pool) Put(seg *segment) {
// check if the buf is from Pool, do not put it back to pool
if len(seg.data) != bp.segmentSize {
return
}
atomic.AddInt64(&bp.curSegmentNum, -1)
seg.size = 0
seg.offset = 0
bp.pool.Put(seg)
if bp.capacity != unLimitedPoolCapacity {
bp.sem.Release(1)
}
}
// newPool creates a new buffer pool.
// capacity is the number of buffer in the pool.
// segSize is the size of each buffer.
// If capacity is 0, the pool is unlimit.
func newPool(capacity int, segSize int) *Pool {
if capacity < 0 {
panic("capacity must be greater than or equal to 0")
}
if segSize <= 0 {
panic("segSize must be greater than 0")
}
bp := &Pool{
pool: sync.Pool{
New: func() interface{} {
return &segment{
data: make([]byte, segSize),
size: 0,
}
},
},
segmentSize: segSize,
capacity: capacity,
}
if capacity != unLimitedPoolCapacity {
bp.sem = semaphore.NewWeighted(int64(capacity))
}
return bp
}