1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-31 14:36:50 -05:00
v2fly/common/buf/merge_reader.go
2017-03-27 11:26:44 +02:00

52 lines
754 B
Go

package buf
type MergingReader struct {
reader Reader
timeoutReader TimeoutReader
leftover *Buffer
}
func NewMergingReader(reader Reader) Reader {
return &MergingReader{
reader: reader,
timeoutReader: reader.(TimeoutReader),
}
}
func (r *MergingReader) Read() (*Buffer, error) {
if r.leftover != nil {
return r.leftover, nil
}
b, err := r.reader.Read()
if err != nil {
return nil, err
}
if b.IsFull() {
return b, nil
}
if r.timeoutReader == nil {
return b, nil
}
for {
b2, err := r.timeoutReader.ReadTimeout(0)
if err != nil {
break
}
nBytes := b.Append(b2.Bytes())
b2.SliceFrom(nBytes)
if b2.IsEmpty() {
b2.Release()
} else {
r.leftover = b2
break
}
}
return b, nil
}