2014-03-12 05:32:26 +00:00
|
|
|
// Package buffers manages a set of reusable byte buffers.
|
2013-12-15 10:43:31 +00:00
|
|
|
package buffers
|
|
|
|
|
2013-12-30 01:33:57 +00:00
|
|
|
const (
|
|
|
|
largeMin = 1024
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
smallBuffers = make(chan []byte, 32)
|
|
|
|
largeBuffers = make(chan []byte, 32)
|
|
|
|
)
|
2013-12-15 10:43:31 +00:00
|
|
|
|
|
|
|
func Get(size int) []byte {
|
2013-12-30 01:33:57 +00:00
|
|
|
var ch = largeBuffers
|
|
|
|
if size < largeMin {
|
|
|
|
ch = smallBuffers
|
|
|
|
}
|
|
|
|
|
2013-12-15 10:43:31 +00:00
|
|
|
var buf []byte
|
|
|
|
select {
|
2013-12-30 01:33:57 +00:00
|
|
|
case buf = <-ch:
|
2013-12-15 10:43:31 +00:00
|
|
|
default:
|
|
|
|
}
|
2013-12-30 01:33:57 +00:00
|
|
|
|
2013-12-15 10:43:31 +00:00
|
|
|
if len(buf) < size {
|
|
|
|
return make([]byte, size)
|
|
|
|
}
|
|
|
|
return buf[:size]
|
|
|
|
}
|
|
|
|
|
|
|
|
func Put(buf []byte) {
|
2013-12-30 01:33:57 +00:00
|
|
|
buf = buf[:cap(buf)]
|
|
|
|
if len(buf) == 0 {
|
2013-12-15 10:43:31 +00:00
|
|
|
return
|
|
|
|
}
|
2013-12-30 01:33:57 +00:00
|
|
|
|
|
|
|
var ch = largeBuffers
|
|
|
|
if len(buf) < largeMin {
|
|
|
|
ch = smallBuffers
|
|
|
|
}
|
|
|
|
|
2013-12-15 10:43:31 +00:00
|
|
|
select {
|
2013-12-30 01:33:57 +00:00
|
|
|
case ch <- buf:
|
2013-12-15 10:43:31 +00:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|