1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/common/buf/merge_reader.go

54 lines
782 B
Go
Raw Normal View History

2017-03-27 05:12:34 -04:00
package buf
type MergingReader struct {
2017-03-27 05:14:55 -04:00
reader Reader
timeoutReader TimeoutReader
leftover *Buffer
2017-03-27 05:12:34 -04:00
}
func NewMergingReader(reader Reader) Reader {
return &MergingReader{
2017-03-27 05:14:55 -04:00
reader: reader,
timeoutReader: reader.(TimeoutReader),
2017-03-27 05:12:34 -04:00
}
}
func (r *MergingReader) Read() (*Buffer, error) {
if r.leftover != nil {
2017-03-28 07:10:57 -04:00
b := r.leftover
r.leftover = nil
return b, nil
2017-03-27 05:12:34 -04:00
}
b, err := r.reader.Read()
if err != nil {
return nil, err
}
if b.IsFull() {
return b, nil
}
2017-03-27 05:14:55 -04:00
if r.timeoutReader == nil {
return b, nil
}
2017-03-27 05:26:44 -04:00
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
}
2017-03-27 05:12:34 -04:00
}
return b, nil
}