syncthing/buffers/buffers.go

47 lines
612 B
Go
Raw Normal View History

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