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/io/reader.go

70 lines
1.4 KiB

package io
import (
"io"
"v2ray.com/core/common"
"v2ray.com/core/common/alloc"
)
9 years ago
// Reader extends io.Reader with alloc.Buffer.
type Reader interface {
common.Releasable
9 years ago
// Read reads content from underlying reader, and put it into an alloc.Buffer.
Read() (*alloc.Buffer, error)
}
9 years ago
// AdaptiveReader is a Reader that adjusts its reading speed automatically.
type AdaptiveReader struct {
reader io.Reader
largeBuffer *alloc.Buffer
highVolumn bool
}
9 years ago
// NewAdaptiveReader creates a new AdaptiveReader.
9 years ago
// The AdaptiveReader instance doesn't take the ownership of reader.
func NewAdaptiveReader(reader io.Reader) *AdaptiveReader {
return &AdaptiveReader{
reader: reader,
}
}
9 years ago
// Read implements Reader.Read().
8 years ago
func (v *AdaptiveReader) Read() (*alloc.Buffer, error) {
if v.highVolumn && v.largeBuffer.IsEmpty() {
if v.largeBuffer == nil {
v.largeBuffer = alloc.NewLocalBuffer(32 * 1024)
}
nBytes, err := v.largeBuffer.FillFrom(v.reader)
if err != nil {
return nil, err
}
if nBytes < alloc.BufferSize {
v.highVolumn = false
}
}
buffer := alloc.NewBuffer()
if !v.largeBuffer.IsEmpty() {
buffer.FillFrom(v.largeBuffer)
return buffer, nil
}
8 years ago
_, err := buffer.FillFrom(v.reader)
8 years ago
if err != nil {
buffer.Release()
return nil, err
}
if buffer.IsFull() {
v.highVolumn = true
}
return buffer, nil
}
8 years ago
// Release implements Releasable.Release().
8 years ago
func (v *AdaptiveReader) Release() {
v.reader = nil
}