/
buffer.go
54 lines (46 loc) · 1.13 KB
/
buffer.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 archiver
// Buffer is a reusable buffer. After the buffer has been used, Release should
// be called so the underlying slice is put back into the pool.
type Buffer struct {
Data []byte
pool *BufferPool
}
// Release puts the buffer back into the pool it came from.
func (b *Buffer) Release() {
pool := b.pool
if pool == nil || cap(b.Data) > pool.defaultSize {
return
}
select {
case pool.ch <- b:
default:
}
}
// BufferPool implements a limited set of reusable buffers.
type BufferPool struct {
ch chan *Buffer
defaultSize int
}
// NewBufferPool initializes a new buffer pool. The pool stores at most max
// items. New buffers are created with defaultSize. Buffers that have grown
// larger are not put back.
func NewBufferPool(max int, defaultSize int) *BufferPool {
b := &BufferPool{
ch: make(chan *Buffer, max),
defaultSize: defaultSize,
}
return b
}
// Get returns a new buffer, either from the pool or newly allocated.
func (pool *BufferPool) Get() *Buffer {
select {
case buf := <-pool.ch:
return buf
default:
}
b := &Buffer{
Data: make([]byte, pool.defaultSize),
pool: pool,
}
return b
}