2016-08-19 11:05:15 -04:00
|
|
|
package io
|
2016-01-29 08:39:55 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
2016-08-20 14:55:45 -04:00
|
|
|
"v2ray.com/core/common"
|
|
|
|
"v2ray.com/core/common/alloc"
|
2016-01-29 08:39:55 -05:00
|
|
|
)
|
|
|
|
|
2016-02-06 16:28:35 -05:00
|
|
|
// Reader extends io.Reader with alloc.Buffer.
|
2016-01-29 08:39:55 -05:00
|
|
|
type Reader interface {
|
2016-04-12 15:43:13 -04:00
|
|
|
common.Releasable
|
2016-02-06 16:28:35 -05:00
|
|
|
// Read reads content from underlying reader, and put it into an alloc.Buffer.
|
2016-01-29 08:39:55 -05:00
|
|
|
Read() (*alloc.Buffer, error)
|
|
|
|
}
|
|
|
|
|
2016-02-06 16:28:35 -05:00
|
|
|
// AdaptiveReader is a Reader that adjusts its reading speed automatically.
|
2016-01-29 08:39:55 -05:00
|
|
|
type AdaptiveReader struct {
|
2016-12-02 09:06:04 -05:00
|
|
|
reader io.Reader
|
|
|
|
largeBuffer *alloc.Buffer
|
|
|
|
highVolumn bool
|
2016-01-29 08:39:55 -05:00
|
|
|
}
|
|
|
|
|
2016-02-06 16:28:35 -05:00
|
|
|
// NewAdaptiveReader creates a new AdaptiveReader.
|
2016-04-28 16:31:33 -04:00
|
|
|
// The AdaptiveReader instance doesn't take the ownership of reader.
|
2016-01-29 08:39:55 -05:00
|
|
|
func NewAdaptiveReader(reader io.Reader) *AdaptiveReader {
|
|
|
|
return &AdaptiveReader{
|
2016-12-02 09:06:04 -05:00
|
|
|
reader: reader,
|
2016-01-29 08:39:55 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-06 16:28:35 -05:00
|
|
|
// Read implements Reader.Read().
|
2016-11-27 15:39:09 -05:00
|
|
|
func (v *AdaptiveReader) Read() (*alloc.Buffer, error) {
|
2016-12-02 09:06:04 -05:00
|
|
|
if v.highVolumn && v.largeBuffer.IsEmpty() {
|
|
|
|
if v.largeBuffer == nil {
|
2016-12-07 06:21:24 -05:00
|
|
|
v.largeBuffer = alloc.NewLocalBuffer(32 * 1024)
|
2016-12-02 09:06:04 -05:00
|
|
|
}
|
|
|
|
nBytes, err := v.largeBuffer.FillFrom(v.reader)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if nBytes < alloc.BufferSize {
|
|
|
|
v.highVolumn = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-06 05:03:42 -05:00
|
|
|
buffer := alloc.NewBuffer()
|
2016-12-02 09:06:04 -05:00
|
|
|
if !v.largeBuffer.IsEmpty() {
|
|
|
|
buffer.FillFrom(v.largeBuffer)
|
|
|
|
return buffer, nil
|
|
|
|
}
|
|
|
|
|
2016-11-27 15:39:09 -05:00
|
|
|
_, err := buffer.FillFrom(v.reader)
|
2016-07-17 06:18:34 -04:00
|
|
|
if err != nil {
|
|
|
|
buffer.Release()
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-01-29 08:39:55 -05:00
|
|
|
|
2016-12-02 09:06:04 -05:00
|
|
|
if buffer.IsFull() {
|
|
|
|
v.highVolumn = true
|
|
|
|
}
|
|
|
|
|
2016-01-29 08:39:55 -05:00
|
|
|
return buffer, nil
|
|
|
|
}
|
2016-03-11 17:51:58 -05:00
|
|
|
|
2016-12-06 11:36:28 -05:00
|
|
|
// Release implements Releasable.Release().
|
2016-11-27 15:39:09 -05:00
|
|
|
func (v *AdaptiveReader) Release() {
|
|
|
|
v.reader = nil
|
2016-03-11 17:51:58 -05:00
|
|
|
}
|