| 1 |
package util |
| 2 |
|
| 3 |
import "log" |
| 4 |
|
| 5 |
type BytePool struct { |
| 6 |
pool chan []byte |
| 7 |
width int |
| 8 |
} |
| 9 |
|
| 10 |
func NewBytePool(width int, depth int) *BytePool { |
| 11 |
return &BytePool{ |
| 12 |
pool: make(chan []byte, depth), |
| 13 |
width: width, |
| 14 |
} |
| 15 |
} |
| 16 |
|
| 17 |
func (p *BytePool) Close() { |
| 18 |
close(p.pool) |
| 19 |
} |
| 20 |
|
| 21 |
func (p *BytePool) Get() (b []byte) { |
| 22 |
select { |
| 23 |
case b = <-p.pool: |
| 24 |
default: |
| 25 |
b = make([]byte, p.width) |
| 26 |
} |
| 27 |
return b |
| 28 |
} |
| 29 |
|
| 30 |
func (p *BytePool) Put(b []byte) { |
| 31 |
|
| 32 |
|
| 33 |
defer func() { |
| 34 |
if err := recover(); err != nil { |
| 35 |
log.Printf("bytepool: %v", err) |
| 36 |
} |
| 37 |
}() |
| 38 |
|
| 39 |
select { |
| 40 |
case p.pool <- b: |
| 41 |
default: |
| 42 |
} |
| 43 |
} |