You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/buf/reader.go

107 lines
1.9 KiB

package buf
import (
"io"
"v2ray.com/core/common/errors"
)
// BytesToBufferReader is a Reader that adjusts its reading speed automatically.
type BytesToBufferReader struct {
8 years ago
reader io.Reader
buffer []byte
}
// Read implements Reader.Read().
func (r *BytesToBufferReader) Read() (MultiBuffer, error) {
nBytes, err := r.reader.Read(r.buffer)
if err != nil {
return nil, err
}
8 years ago
mb := NewMultiBuffer()
p := r.buffer[:nBytes]
for len(p) > 0 {
8 years ago
b := New()
nBytes, _ := b.Write(p)
8 years ago
mb.Append(b)
p = p[nBytes:]
}
8 years ago
return mb, nil
}
8 years ago
type readerAdpater struct {
MultiBufferReader
}
func (r *readerAdpater) Read() (MultiBuffer, error) {
return r.ReadMultiBuffer()
}
type bufferToBytesReader struct {
stream Reader
leftOver MultiBuffer
}
func (r *bufferToBytesReader) Read(b []byte) (int, error) {
if r.leftOver != nil {
8 years ago
nBytes, _ := r.leftOver.Read(b)
if r.leftOver.IsEmpty() {
r.leftOver.Release()
r.leftOver = nil
}
8 years ago
return nBytes, nil
}
mb, err := r.stream.Read()
if err != nil {
return 0, err
}
8 years ago
nBytes, _ := mb.Read(b)
if !mb.IsEmpty() {
r.leftOver = mb
}
8 years ago
return nBytes, nil
}
8 years ago
func (r *bufferToBytesReader) ReadMultiBuffer() (MultiBuffer, error) {
if r.leftOver != nil {
mb := r.leftOver
r.leftOver = nil
return mb, nil
8 years ago
}
return r.stream.Read()
8 years ago
}
func (r *bufferToBytesReader) writeToInternal(writer io.Writer) (int64, error) {
mbWriter := NewWriter(writer)
totalBytes := int64(0)
if r.leftOver != nil {
8 years ago
if err := mbWriter.Write(r.leftOver); err != nil {
return 0, err
}
totalBytes += int64(r.leftOver.Len())
}
for {
mb, err := r.stream.Read()
if err != nil {
return totalBytes, err
}
totalBytes += int64(mb.Len())
if err := mbWriter.Write(mb); err != nil {
return totalBytes, err
}
}
}
func (r *bufferToBytesReader) WriteTo(writer io.Writer) (int64, error) {
nBytes, err := r.writeToInternal(writer)
if errors.Cause(err) == io.EOF {
return nBytes, nil
}
return nBytes, err
}