2017-04-15 15:07:23 -04:00
|
|
|
package buf
|
|
|
|
|
2017-04-19 15:27:21 -04:00
|
|
|
import "net"
|
2017-04-15 15:07:23 -04:00
|
|
|
|
|
|
|
type MultiBufferWriter interface {
|
|
|
|
WriteMultiBuffer(MultiBuffer) (int, error)
|
|
|
|
}
|
|
|
|
|
2017-04-15 16:22:29 -04:00
|
|
|
type MultiBufferReader interface {
|
|
|
|
ReadMultiBuffer() (MultiBuffer, error)
|
|
|
|
}
|
|
|
|
|
2017-04-15 15:07:23 -04:00
|
|
|
type MultiBuffer []*Buffer
|
|
|
|
|
|
|
|
func NewMultiBuffer() MultiBuffer {
|
2017-04-16 16:33:20 -04:00
|
|
|
return MultiBuffer(make([]*Buffer, 0, 128))
|
2017-04-15 15:07:23 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewMultiBufferValue(b ...*Buffer) MultiBuffer {
|
|
|
|
return MultiBuffer(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *MultiBuffer) Append(buf *Buffer) {
|
|
|
|
*b = append(*b, buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *MultiBuffer) AppendMulti(mb MultiBuffer) {
|
|
|
|
*b = append(*b, mb...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb *MultiBuffer) Read(b []byte) (int, error) {
|
|
|
|
endIndex := len(*mb)
|
|
|
|
totalBytes := 0
|
|
|
|
for i, bb := range *mb {
|
2017-04-19 15:27:21 -04:00
|
|
|
nBytes, _ := bb.Read(b)
|
2017-04-15 15:07:23 -04:00
|
|
|
totalBytes += nBytes
|
|
|
|
b = b[nBytes:]
|
|
|
|
if bb.IsEmpty() {
|
|
|
|
bb.Release()
|
|
|
|
} else {
|
|
|
|
endIndex = i
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
*mb = (*mb)[endIndex:]
|
|
|
|
return totalBytes, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MultiBuffer) Len() int {
|
|
|
|
size := 0
|
|
|
|
for _, b := range mb {
|
|
|
|
size += b.Len()
|
|
|
|
}
|
|
|
|
return size
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MultiBuffer) IsEmpty() bool {
|
|
|
|
for _, b := range mb {
|
|
|
|
if !b.IsEmpty() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mb MultiBuffer) Release() {
|
2017-04-16 07:12:58 -04:00
|
|
|
for i, b := range mb {
|
2017-04-15 15:07:23 -04:00
|
|
|
b.Release()
|
2017-04-16 07:12:58 -04:00
|
|
|
mb[i] = nil
|
2017-04-15 15:07:23 -04:00
|
|
|
}
|
|
|
|
}
|
2017-04-16 16:30:29 -04:00
|
|
|
|
|
|
|
func (mb MultiBuffer) ToNetBuffers() net.Buffers {
|
|
|
|
bs := make([][]byte, len(mb))
|
|
|
|
for i, b := range mb {
|
|
|
|
bs[i] = b.Bytes()
|
|
|
|
}
|
|
|
|
return bs
|
|
|
|
}
|
2017-04-19 04:14:52 -04:00
|
|
|
|
|
|
|
func (mb *MultiBuffer) SliceBySize(size int) MultiBuffer {
|
|
|
|
slice := NewMultiBuffer()
|
|
|
|
sliceSize := 0
|
|
|
|
endIndex := len(*mb)
|
|
|
|
for i, b := range *mb {
|
|
|
|
if b.Len()+sliceSize > size {
|
|
|
|
endIndex = i
|
|
|
|
break
|
|
|
|
}
|
2017-04-19 15:27:21 -04:00
|
|
|
sliceSize += b.Len()
|
2017-04-19 04:14:52 -04:00
|
|
|
slice.Append(b)
|
|
|
|
}
|
|
|
|
*mb = (*mb)[endIndex:]
|
|
|
|
return slice
|
|
|
|
}
|