1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-19 10:56:06 -05:00
v2fly/common/buf/reader.go

83 lines
1.4 KiB
Go
Raw Normal View History

2016-12-09 07:17:34 -05:00
package buf
2016-12-27 14:53:29 -05:00
import "io"
2016-12-09 07:17:34 -05:00
// BytesToBufferReader is a Reader that adjusts its reading speed automatically.
type BytesToBufferReader struct {
2017-04-15 15:07:23 -04:00
reader io.Reader
buffer *Buffer
2016-12-09 07:17:34 -05:00
}
// Read implements Reader.Read().
2017-04-15 15:07:23 -04:00
func (v *BytesToBufferReader) Read() (MultiBuffer, error) {
if err := v.buffer.Reset(ReadFrom(v.reader)); err != nil {
2016-12-09 07:17:34 -05:00
return nil, err
}
2017-04-15 15:07:23 -04:00
mb := NewMultiBuffer()
for !v.buffer.IsEmpty() {
b := New()
b.AppendSupplier(ReadFrom(v.buffer))
mb.Append(b)
2016-12-09 07:17:34 -05:00
}
2017-04-15 15:07:23 -04:00
return mb, nil
2016-12-09 07:17:34 -05:00
}
2017-04-15 16:22:29 -04:00
type readerAdpater struct {
MultiBufferReader
}
func (r *readerAdpater) Read() (MultiBuffer, error) {
return r.ReadMultiBuffer()
}
2017-02-20 04:33:35 -05:00
type bufferToBytesReader struct {
2016-12-09 07:17:34 -05:00
stream Reader
2017-04-15 15:07:23 -04:00
current MultiBuffer
2017-02-06 18:39:07 -05:00
err error
2016-12-09 07:17:34 -05:00
}
2017-02-20 04:33:35 -05:00
// fill fills in the internal buffer.
func (v *bufferToBytesReader) fill() {
2016-12-09 07:17:34 -05:00
b, err := v.stream.Read()
if err != nil {
2017-02-06 18:39:07 -05:00
v.err = err
2017-04-02 19:07:01 -04:00
return
2016-12-09 07:17:34 -05:00
}
2017-04-02 19:07:01 -04:00
v.current = b
2016-12-09 07:17:34 -05:00
}
2017-02-20 04:33:35 -05:00
func (v *bufferToBytesReader) Read(b []byte) (int, error) {
2017-02-06 18:39:07 -05:00
if v.err != nil {
return 0, v.err
2016-12-09 07:17:34 -05:00
}
if v.current == nil {
2017-02-20 04:33:35 -05:00
v.fill()
2017-02-06 18:39:07 -05:00
if v.err != nil {
return 0, v.err
2016-12-09 07:17:34 -05:00
}
}
nBytes, err := v.current.Read(b)
if v.current.IsEmpty() {
v.current.Release()
v.current = nil
}
return nBytes, err
}
2017-04-15 16:22:29 -04:00
func (v *bufferToBytesReader) ReadMultiBuffer() (MultiBuffer, error) {
if v.err != nil {
return nil, v.err
}
if v.current == nil {
v.fill()
if v.err != nil {
return nil, v.err
}
}
b := v.current
v.current = nil
return b, nil
}