-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
44 lines (38 loc) · 720 Bytes
/
pool.go
File metadata and controls
44 lines (38 loc) · 720 Bytes
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
package zsocket
import "sync"
// BufferPool is a generic reusable buffer pool.
type BufferPool interface {
Get() any
Put(any)
}
type defaultBufferPool struct {
size int
pool sync.Pool
}
// NewBufferPool creates a sync.Pool-backed byte buffer pool.
func NewBufferPool(size int) BufferPool {
if size <= 0 {
size = 4096
}
p := &defaultBufferPool{size: size}
p.pool.New = func() any {
b := make([]byte, 0, p.size)
return &b
}
return p
}
func (p *defaultBufferPool) Get() any {
return p.pool.Get()
}
func (p *defaultBufferPool) Put(v any) {
b, ok := v.(*[]byte)
if !ok || b == nil {
return
}
buf := (*b)[:0]
if cap(buf) > p.size*4 {
buf = make([]byte, 0, p.size)
}
*b = buf
p.pool.Put(b)
}