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 {
|
|
|
|
reader io.Reader
|
|
|
|
allocate func() *alloc.Buffer
|
|
|
|
}
|
|
|
|
|
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{
|
|
|
|
reader: reader,
|
|
|
|
allocate: alloc.NewBuffer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-06 16:28:35 -05:00
|
|
|
// Read implements Reader.Read().
|
2016-01-29 08:39:55 -05:00
|
|
|
func (this *AdaptiveReader) Read() (*alloc.Buffer, error) {
|
2016-07-17 06:18:34 -04:00
|
|
|
buffer := this.allocate().Clear()
|
|
|
|
_, err := buffer.FillFrom(this.reader)
|
|
|
|
if err != nil {
|
|
|
|
buffer.Release()
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-01-29 08:39:55 -05:00
|
|
|
|
2016-05-11 13:54:20 -04:00
|
|
|
if buffer.Len() >= alloc.BufferSize {
|
2016-01-29 08:39:55 -05:00
|
|
|
this.allocate = alloc.NewLargeBuffer
|
2016-05-11 13:54:20 -04:00
|
|
|
} else {
|
2016-01-29 08:39:55 -05:00
|
|
|
this.allocate = alloc.NewBuffer
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer, nil
|
|
|
|
}
|
2016-03-11 17:51:58 -05:00
|
|
|
|
|
|
|
func (this *AdaptiveReader) Release() {
|
|
|
|
this.reader = nil
|
|
|
|
}
|