2015-09-09 11:39:06 -04:00
|
|
|
package io
|
|
|
|
|
2015-09-09 11:39:25 -04:00
|
|
|
import (
|
|
|
|
"errors"
|
2015-09-09 11:39:06 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2015-09-09 11:39:25 -04:00
|
|
|
SizeSmall = 16
|
|
|
|
SizeMedium = 128
|
|
|
|
SizeLarge = 512
|
2015-09-09 11:39:06 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2015-09-09 11:39:25 -04:00
|
|
|
ErrorNoChannel = errors.New("No suitable channels found.")
|
2015-09-09 11:39:06 -04:00
|
|
|
)
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
type BufferSet struct {
|
2015-09-09 11:39:25 -04:00
|
|
|
small chan []byte
|
|
|
|
medium chan []byte
|
|
|
|
large chan []byte
|
2015-09-09 11:39:06 -04:00
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func NewBufferSet() *BufferSet {
|
|
|
|
bSet := new(BufferSet)
|
2015-09-09 11:39:25 -04:00
|
|
|
bSet.small = make(chan []byte, 128)
|
|
|
|
bSet.medium = make(chan []byte, 128)
|
|
|
|
bSet.large = make(chan []byte, 128)
|
|
|
|
return bSet
|
2015-09-09 11:39:06 -04:00
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (bSet *BufferSet) detectBucket(size int, strict bool) (chan []byte, error) {
|
2015-09-09 11:39:25 -04:00
|
|
|
if strict {
|
|
|
|
if size == SizeSmall {
|
|
|
|
return bSet.small, nil
|
|
|
|
} else if size == SizeMedium {
|
|
|
|
return bSet.medium, nil
|
|
|
|
} else if size == SizeLarge {
|
|
|
|
return bSet.large, nil
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if size <= SizeSmall {
|
|
|
|
return bSet.small, nil
|
|
|
|
} else if size <= SizeMedium {
|
|
|
|
return bSet.medium, nil
|
|
|
|
} else if size <= SizeLarge {
|
|
|
|
return bSet.large, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, ErrorNoChannel
|
2015-09-09 11:39:06 -04:00
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (bSet *BufferSet) FetchBuffer(minSize int) []byte {
|
2015-09-09 11:39:25 -04:00
|
|
|
var buffer []byte
|
|
|
|
byteChan, err := bSet.detectBucket(minSize, false)
|
|
|
|
if err != nil {
|
|
|
|
return make([]byte, minSize)
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case buffer = <-byteChan:
|
|
|
|
default:
|
|
|
|
buffer = make([]byte, minSize)
|
|
|
|
}
|
|
|
|
return buffer
|
2015-09-09 11:39:06 -04:00
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (bSet *BufferSet) ReturnBuffer(buffer []byte) {
|
2015-09-09 11:39:25 -04:00
|
|
|
byteChan, err := bSet.detectBucket(len(buffer), true)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case byteChan <- buffer:
|
|
|
|
default:
|
|
|
|
}
|
2015-09-09 11:39:06 -04:00
|
|
|
}
|