2014-06-01 20:50:14 +00:00
|
|
|
// Copyright (C) 2014 Jakob Borg and other contributors. All rights reserved.
|
|
|
|
// Use of this source code is governed by an MIT-style license that can be
|
|
|
|
// found in the LICENSE file.
|
|
|
|
|
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:
|
|
|
|
}
|
|
|
|
}
|