1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-18 18:36:11 -05:00
v2fly/common/io/reader.go

63 lines
1.5 KiB
Go
Raw Normal View History

2016-01-29 08:39:55 -05:00
package io // import "github.com/v2ray/v2ray-core/common/io"
import (
"io"
2016-03-11 17:51:58 -05:00
"github.com/v2ray/v2ray-core/common"
2016-01-29 08:39:55 -05:00
"github.com/v2ray/v2ray-core/common/alloc"
)
// ReadFrom reads from a reader and put all content to a buffer.
// If buffer is nil, ReadFrom creates a new normal buffer.
func ReadFrom(reader io.Reader, buffer *alloc.Buffer) (*alloc.Buffer, error) {
if buffer == nil {
buffer = alloc.NewBuffer()
}
nBytes, err := reader.Read(buffer.Value)
buffer.Slice(0, nBytes)
return buffer, err
}
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) {
buffer, err := ReadFrom(this.reader, this.allocate())
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
}
if err != nil {
2016-02-01 06:22:29 -05:00
buffer.Release()
2016-01-29 08:39:55 -05:00
return nil, err
}
return buffer, nil
}
2016-03-11 17:51:58 -05:00
func (this *AdaptiveReader) Release() {
this.reader = nil
}