1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 01:57:12 -05:00
v2fly/io/bufferset.go

76 lines
1.4 KiB
Go
Raw Normal View History

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
)
type VBufferSet 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
}
func NewVBufferSet() *VBufferSet {
2015-09-09 11:39:25 -04:00
bSet := new(VBufferSet)
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
}
func (bSet *VBufferSet) 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
}
func (bSet *VBufferSet) 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
}
func (bSet *VBufferSet) 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
}